code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ros.internal.node.BaseClientHandshake;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.internal.transport.ConnectionHeaderFields;
/**
* Handshake logic from the client side of a service connection.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceClientHandshake extends BaseClientHandshake {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(ServiceClientHandshake.class);
public ServiceClientHandshake(ConnectionHeader outgoingConnectionHeader) {
super(outgoingConnectionHeader);
}
@Override
public boolean handshake(ConnectionHeader incommingConnectionHeader) {
if (DEBUG) {
log.info("Outgoing service client connection header: " + outgoingConnectionHeader);
log.info("Incoming service server connection header: " + incommingConnectionHeader);
}
setErrorMessage(incommingConnectionHeader.getField(ConnectionHeaderFields.ERROR));
if (getErrorMessage() != null) {
return false;
}
if (!incommingConnectionHeader.getField(ConnectionHeaderFields.TYPE).equals(
incommingConnectionHeader.getField(ConnectionHeaderFields.TYPE))) {
setErrorMessage("Message types don't match.");
}
if (!incommingConnectionHeader.getField(ConnectionHeaderFields.MD5_CHECKSUM).equals(
incommingConnectionHeader.getField(ConnectionHeaderFields.MD5_CHECKSUM))) {
setErrorMessage("Checksums don't match.");
}
return getErrorMessage() == null;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.service;
import com.google.common.base.Preconditions;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.ros.exception.RemoteException;
import org.ros.internal.node.response.StatusCode;
import org.ros.message.MessageDeserializer;
import org.ros.node.service.ServiceResponseListener;
import java.nio.charset.Charset;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
/**
* A Netty {@link SimpleChannelHandler} for service responses.
*
* @author damonkohler@google.com (Damon Kohler)
*/
class ServiceResponseHandler<ResponseType> extends SimpleChannelHandler {
private final Queue<ServiceResponseListener<ResponseType>> responseListeners;
private final MessageDeserializer<ResponseType> deserializer;
private final ExecutorService executorService;
public ServiceResponseHandler(Queue<ServiceResponseListener<ResponseType>> messageListeners,
MessageDeserializer<ResponseType> deserializer, ExecutorService executorService) {
this.responseListeners = messageListeners;
this.deserializer = deserializer;
this.executorService = executorService;
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
final ServiceResponseListener<ResponseType> listener = responseListeners.poll();
Preconditions.checkNotNull(listener, "No listener for incoming service response.");
final ServiceServerResponse response = (ServiceServerResponse) e.getMessage();
final ChannelBuffer buffer = response.getMessage();
executorService.execute(new Runnable() {
@Override
public void run() {
if (response.getErrorCode() == 1) {
listener.onSuccess(deserializer.deserialize(buffer));
} else {
String message = Charset.forName("US-ASCII").decode(buffer.toByteBuffer()).toString();
listener.onFailure(new RemoteException(StatusCode.ERROR, message));
}
}
});
}
}
| Java |
package org.ros.internal.node.service;
enum ServiceResponseDecoderState {
ERROR_CODE, MESSAGE_LENGTH, MESSAGE
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.service;
import com.google.common.base.Preconditions;
import org.ros.exception.DuplicateServiceException;
import org.ros.internal.message.service.ServiceDescription;
import org.ros.internal.node.server.SlaveServer;
import org.ros.message.MessageDeserializer;
import org.ros.message.MessageFactory;
import org.ros.message.MessageSerializer;
import org.ros.namespace.GraphName;
import org.ros.node.service.ServiceClient;
import org.ros.node.service.ServiceResponseBuilder;
import org.ros.node.service.ServiceServer;
import java.util.concurrent.ScheduledExecutorService;
/**
* A factory for {@link ServiceServer}s and {@link ServiceClient}s.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceFactory {
private final GraphName nodeName;
private final SlaveServer slaveServer;
private final ServiceManager serviceManager;
private final ScheduledExecutorService executorService;
private final Object mutex;
public ServiceFactory(GraphName nodeName, SlaveServer slaveServer, ServiceManager serviceManager,
ScheduledExecutorService executorService) {
this.nodeName = nodeName;
this.slaveServer = slaveServer;
this.serviceManager = serviceManager;
this.executorService = executorService;
mutex = new Object();
}
/**
* Creates a {@link DefaultServiceServer} instance and registers it with the
* master.
*
* @param serviceDeclaration
* the {@link ServiceDescription} that is being served
* @param responseBuilder
* the {@link ServiceResponseBuilder} that is used to build responses
* @param deserializer
* a {@link MessageDeserializer} to be used for incoming messages
* @param serializer
* a {@link MessageSerializer} to be used for outgoing messages
* @param messageFactory
* a {@link MessageFactory} to be used for creating responses
* @return a {@link DefaultServiceServer} instance
*/
public <T, S> DefaultServiceServer<T, S> newServer(ServiceDeclaration serviceDeclaration,
ServiceResponseBuilder<T, S> responseBuilder, MessageDeserializer<T> deserializer,
MessageSerializer<S> serializer, MessageFactory messageFactory) {
DefaultServiceServer<T, S> serviceServer;
GraphName name = serviceDeclaration.getName();
synchronized (mutex) {
if (serviceManager.hasServer(name)) {
throw new DuplicateServiceException(String.format("ServiceServer %s already exists.", name));
} else {
serviceServer =
new DefaultServiceServer<T, S>(serviceDeclaration, responseBuilder,
slaveServer.getTcpRosAdvertiseAddress(), deserializer, serializer, messageFactory,
executorService);
serviceManager.addServer(serviceServer);
}
}
return serviceServer;
}
/**
* @param name
* the {@link GraphName} of the {@link DefaultServiceServer}
* @return the {@link DefaultServiceServer} with the given name or
* {@code null} if it does not exist
*/
@SuppressWarnings("unchecked")
public <T, S> DefaultServiceServer<T, S> getServer(GraphName name) {
if (serviceManager.hasServer(name)) {
return (DefaultServiceServer<T, S>) serviceManager.getServer(name);
}
return null;
}
/**
* Gets or creates a {@link DefaultServiceClient} instance.
* {@link DefaultServiceClient}s are cached and reused per service. When a new
* {@link DefaultServiceClient} is created, it is connected to the
* {@link DefaultServiceServer}.
*
* @param serviceDeclaration
* the {@link ServiceDescription} that is being served
* @param deserializer
* a {@link MessageDeserializer} to be used for incoming messages
* @param serializer
* a {@link MessageSerializer} to be used for outgoing messages
* @param messageFactory
* a {@link MessageFactory} to be used for creating requests
* @return a {@link DefaultServiceClient} instance
*/
@SuppressWarnings("unchecked")
public <T, S> DefaultServiceClient<T, S> newClient(ServiceDeclaration serviceDeclaration,
MessageSerializer<T> serializer, MessageDeserializer<S> deserializer,
MessageFactory messageFactory) {
Preconditions.checkNotNull(serviceDeclaration.getUri());
DefaultServiceClient<T, S> serviceClient;
GraphName name = serviceDeclaration.getName();
boolean createdNewClient = false;
synchronized (mutex) {
if (serviceManager.hasClient(name)) {
serviceClient = (DefaultServiceClient<T, S>) serviceManager.getClient(name);
} else {
serviceClient =
DefaultServiceClient.newDefault(nodeName, serviceDeclaration, serializer, deserializer,
messageFactory, executorService);
serviceManager.addClient(serviceClient);
createdNewClient = true;
}
}
if (createdNewClient) {
serviceClient.connect(serviceDeclaration.getUri());
}
return serviceClient;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.service;
import org.jboss.netty.buffer.ChannelBuffer;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
class ServiceServerResponse {
private ChannelBuffer message;
private int errorCode;
private int messageLength;
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
public void setMessage(ChannelBuffer buffer) {
message = buffer;
}
public ChannelBuffer getMessage() {
return message;
}
public void setMessageLength(int messageLength) {
this.messageLength = messageLength;
}
public int getMessageLength() {
return messageLength;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.service;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import org.ros.internal.message.MessageBuffers;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public final class ServiceResponseEncoder extends OneToOneEncoder {
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
if (msg instanceof ServiceServerResponse) {
ServiceServerResponse response = (ServiceServerResponse) msg;
ChannelBuffer buffer = MessageBuffers.dynamicBuffer();
buffer.writeByte(response.getErrorCode());
buffer.writeInt(response.getMessageLength());
buffer.writeBytes(response.getMessage());
return buffer;
} else {
return msg;
}
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.service;
import com.google.common.base.Preconditions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandler;
import org.ros.address.AdvertiseAddress;
import org.ros.concurrent.ListenerGroup;
import org.ros.concurrent.SignalRunnable;
import org.ros.internal.message.service.ServiceDescription;
import org.ros.internal.node.topic.DefaultPublisher;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.internal.transport.ConnectionHeaderFields;
import org.ros.message.MessageDeserializer;
import org.ros.message.MessageFactory;
import org.ros.message.MessageSerializer;
import org.ros.namespace.GraphName;
import org.ros.node.service.DefaultServiceServerListener;
import org.ros.node.service.ServiceResponseBuilder;
import org.ros.node.service.ServiceServer;
import org.ros.node.service.ServiceServerListener;
import java.net.URI;
import java.util.concurrent.ScheduledExecutorService;
/**
* Default implementation of a {@link ServiceServer}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class DefaultServiceServer<T, S> implements ServiceServer<T, S> {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(DefaultPublisher.class);
private final ServiceDeclaration serviceDeclaration;
private final ServiceResponseBuilder<T, S> serviceResponseBuilder;
private final AdvertiseAddress advertiseAddress;
private final MessageDeserializer<T> messageDeserializer;
private final MessageSerializer<S> messageSerializer;
private final MessageFactory messageFactory;
private final ScheduledExecutorService scheduledExecutorService;
private final ListenerGroup<ServiceServerListener<T, S>> listenerGroup;
public DefaultServiceServer(ServiceDeclaration serviceDeclaration,
ServiceResponseBuilder<T, S> serviceResponseBuilder, AdvertiseAddress advertiseAddress,
MessageDeserializer<T> messageDeserializer, MessageSerializer<S> messageSerializer,
MessageFactory messageFactory, ScheduledExecutorService scheduledExecutorService) {
this.serviceDeclaration = serviceDeclaration;
this.serviceResponseBuilder = serviceResponseBuilder;
this.advertiseAddress = advertiseAddress;
this.messageDeserializer = messageDeserializer;
this.messageSerializer = messageSerializer;
this.messageFactory = messageFactory;
this.scheduledExecutorService = scheduledExecutorService;
listenerGroup = new ListenerGroup<ServiceServerListener<T, S>>(scheduledExecutorService);
listenerGroup.add(new DefaultServiceServerListener<T, S>() {
@Override
public void onMasterRegistrationSuccess(ServiceServer<T, S> registrant) {
log.info("Service registered: " + DefaultServiceServer.this);
}
@Override
public void onMasterRegistrationFailure(ServiceServer<T, S> registrant) {
log.info("Service registration failed: " + DefaultServiceServer.this);
}
@Override
public void onMasterUnregistrationSuccess(ServiceServer<T, S> registrant) {
log.info("Service unregistered: " + DefaultServiceServer.this);
}
@Override
public void onMasterUnregistrationFailure(ServiceServer<T, S> registrant) {
log.info("Service unregistration failed: " + DefaultServiceServer.this);
}
});
}
public ChannelBuffer finishHandshake(ConnectionHeader incomingConnectionHeader) {
if (DEBUG) {
log.info("Client handshake header: " + incomingConnectionHeader);
}
ConnectionHeader connectionHeader = toDeclaration().toConnectionHeader();
String expectedChecksum = connectionHeader.getField(ConnectionHeaderFields.MD5_CHECKSUM);
String incomingChecksum =
incomingConnectionHeader.getField(ConnectionHeaderFields.MD5_CHECKSUM);
// TODO(damonkohler): Pull out header field comparison logic.
Preconditions.checkState(incomingChecksum.equals(expectedChecksum)
|| incomingChecksum.equals("*"));
if (DEBUG) {
log.info("Server handshake header: " + connectionHeader);
}
return connectionHeader.encode();
}
@Override
public URI getUri() {
return advertiseAddress.toUri("rosrpc");
}
@Override
public GraphName getName() {
return serviceDeclaration.getName();
}
/**
* @return a new {@link ServiceDeclaration} with this
* {@link DefaultServiceServer}'s {@link URI}
*/
ServiceDeclaration toDeclaration() {
ServiceIdentifier identifier = new ServiceIdentifier(serviceDeclaration.getName(), getUri());
return new ServiceDeclaration(identifier, new ServiceDescription(serviceDeclaration.getType(),
serviceDeclaration.getDefinition(), serviceDeclaration.getMd5Checksum()));
}
public ChannelHandler newRequestHandler() {
return new ServiceRequestHandler<T, S>(serviceDeclaration, serviceResponseBuilder,
messageDeserializer, messageSerializer, messageFactory, scheduledExecutorService);
}
/**
* Signal all {@link ServiceServerListener}s that the {@link ServiceServer}
* has been successfully registered with the master.
*
* <p>
* Each listener is called in a separate thread.
*/
public void signalOnMasterRegistrationSuccess() {
final ServiceServer<T, S> serviceServer = this;
listenerGroup.signal(new SignalRunnable<ServiceServerListener<T, S>>() {
@Override
public void run(ServiceServerListener<T, S> listener) {
listener.onMasterRegistrationSuccess(serviceServer);
}
});
}
/**
* Signal all {@link ServiceServerListener}s that the {@link ServiceServer}
* has failed to register with the master.
*
* <p>
* Each listener is called in a separate thread.
*/
public void signalOnMasterRegistrationFailure() {
final ServiceServer<T, S> serviceServer = this;
listenerGroup.signal(new SignalRunnable<ServiceServerListener<T, S>>() {
@Override
public void run(ServiceServerListener<T, S> listener) {
listener.onMasterRegistrationFailure(serviceServer);
}
});
}
/**
* Signal all {@link ServiceServerListener}s that the {@link ServiceServer}
* has been successfully unregistered with the master.
*
* <p>
* Each listener is called in a separate thread.
*/
public void signalOnMasterUnregistrationSuccess() {
final ServiceServer<T, S> serviceServer = this;
listenerGroup.signal(new SignalRunnable<ServiceServerListener<T, S>>() {
@Override
public void run(ServiceServerListener<T, S> listener) {
listener.onMasterUnregistrationSuccess(serviceServer);
}
});
}
/**
* Signal all {@link ServiceServerListener}s that the {@link ServiceServer}
* has failed to unregister with the master.
*
* <p>
* Each listener is called in a separate thread.
*/
public void signalOnMasterUnregistrationFailure() {
final ServiceServer<T, S> serviceServer = this;
listenerGroup.signal(new SignalRunnable<ServiceServerListener<T, S>>() {
@Override
public void run(ServiceServerListener<T, S> listener) {
listener.onMasterUnregistrationFailure(serviceServer);
}
});
}
@Override
public void shutdown() {
throw new UnsupportedOperationException();
}
@Override
public void addListener(ServiceServerListener<T, S> listener) {
listenerGroup.add(listener);
}
@Override
public String toString() {
return "ServiceServer<" + toDeclaration() + ">";
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.service;
import org.ros.node.service.ServiceServer;
/**
* Listener {@link ServiceManager} events.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public interface ServiceManagerListener {
/**
* Called when a new {@link ServiceServer} is added.
*
* @param server
* the {@link ServiceServer} that was added
*/
void onServiceServerAdded(DefaultServiceServer<?, ?> server);
/**
* Called when a new {@link ServiceServer} is added.
*
* @param server
* the {@link ServiceServer} that was added
*/
void onServiceServerRemoved(DefaultServiceServer<?, ?> server);
}
| Java |
/*/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node;
import org.ros.internal.transport.ClientHandshake;
import org.ros.internal.transport.ConnectionHeader;
/**
* An abstract {@link ClientHandshake} implementation for convenience.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public abstract class BaseClientHandshake implements ClientHandshake {
protected final ConnectionHeader outgoingConnectionHeader;
private String errorMessage;
public BaseClientHandshake(ConnectionHeader outgoingConnectionHeader) {
this.outgoingConnectionHeader = outgoingConnectionHeader;
}
@Override
public ConnectionHeader getOutgoingConnectionHeader() {
return outgoingConnectionHeader;
}
@Override
public String getErrorMessage() {
return errorMessage;
}
protected void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import com.google.common.base.Preconditions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ros.concurrent.CancellableLoop;
import org.ros.node.topic.Publisher;
import java.util.concurrent.ScheduledExecutorService;
/**
* Repeatedly send a message out on a given {@link Publisher}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class RepeatingPublisher<MessageType> {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(RepeatingPublisher.class);
private final Publisher<MessageType> publisher;
private final MessageType message;
private final int frequency;
private final RepeatingPublisherLoop runnable;
/**
* Executor used to run the {@link RepeatingPublisherLoop}.
*/
private final ScheduledExecutorService executorService;
private final class RepeatingPublisherLoop extends CancellableLoop {
@Override
public void loop() throws InterruptedException {
publisher.publish(message);
if (DEBUG) {
log.info(String.format("Published message %s to publisher %s ", message, publisher));
}
Thread.sleep((long) (1000.0d / frequency));
}
}
/**
* @param publisher
* @param message
* @param frequency
* the frequency of publication in Hz
*/
public RepeatingPublisher(Publisher<MessageType> publisher, MessageType message, int frequency,
ScheduledExecutorService executorService) {
this.publisher = publisher;
this.message = message;
this.frequency = frequency;
this.executorService = executorService;
runnable = new RepeatingPublisherLoop();
}
public void start() {
Preconditions.checkState(!runnable.isRunning());
executorService.execute(runnable);
}
public void cancel() {
Preconditions.checkState(runnable.isRunning());
runnable.cancel();
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.MessageEvent;
import org.ros.internal.transport.BaseClientHandshakeHandler;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.internal.transport.ConnectionHeaderFields;
import org.ros.internal.transport.queue.IncomingMessageQueue;
import org.ros.internal.transport.tcp.NamedChannelHandler;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
import java.util.concurrent.ExecutorService;
/**
* Performs a handshake with the connected {@link Publisher} and connects the
* {@link Publisher} to the {@link IncomingMessageQueue} on success.
*
* @author damonkohler@google.com (Damon Kohler)
*
* @param <T>
* the {@link Subscriber} may only subscribe to messages of this type
*/
class SubscriberHandshakeHandler<T> extends BaseClientHandshakeHandler {
private static final Log log = LogFactory.getLog(SubscriberHandshakeHandler.class);
private final IncomingMessageQueue<T> incomingMessageQueue;
public SubscriberHandshakeHandler(ConnectionHeader outgoingConnectionHeader,
final IncomingMessageQueue<T> incomingMessageQueue, ExecutorService executorService) {
super(new SubscriberHandshake(outgoingConnectionHeader), executorService);
this.incomingMessageQueue = incomingMessageQueue;
}
@Override
protected void onSuccess(ConnectionHeader incomingConnectionHeader, ChannelHandlerContext ctx,
MessageEvent e) {
ChannelPipeline pipeline = e.getChannel().getPipeline();
pipeline.remove(SubscriberHandshakeHandler.this);
NamedChannelHandler namedChannelHandler = incomingMessageQueue.getMessageReceiver();
pipeline.addLast(namedChannelHandler.getName(), namedChannelHandler);
String latching = incomingConnectionHeader.getField(ConnectionHeaderFields.LATCHING);
if (latching != null && latching.equals("1")) {
incomingMessageQueue.setLatchMode(true);
}
}
@Override
protected void onFailure(String errorMessage, ChannelHandlerContext ctx, MessageEvent e) {
log.error("Subscriber handshake failed: " + errorMessage);
e.getChannel().close();
}
@Override
public String getName() {
return "SubscriberHandshakeHandler";
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides internal classes for working with topics.
* <p>
* These classes should _not_ be used directly outside of the org.ros package.
*/
package org.ros.internal.node.topic; | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.internal.transport.ConnectionHeaderFields;
import org.ros.namespace.GraphName;
import java.net.URI;
import java.util.Map;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class SubscriberDeclaration {
private final SubscriberIdentifier subscriberIdentifier;
private final TopicDeclaration topicDeclaration;
/**
* Creates a subscriber definition from the headers in a connection header.
*
* @param header
* The header data.
*
* @return The subscriber definition from the header data.
*/
public static SubscriberDeclaration newFromHeader(Map<String, String> header) {
NodeIdentifier nodeIdentifier =
new NodeIdentifier(GraphName.of(header.get(ConnectionHeaderFields.CALLER_ID)), null);
TopicDeclaration topicDeclaration = TopicDeclaration.newFromHeader(header);
return new SubscriberDeclaration(new SubscriberIdentifier(nodeIdentifier,
topicDeclaration.getIdentifier()), topicDeclaration);
}
public SubscriberDeclaration(SubscriberIdentifier subscriberIdentifier,
TopicDeclaration topicDeclaration) {
this.subscriberIdentifier = subscriberIdentifier;
this.topicDeclaration = topicDeclaration;
}
public NodeIdentifier getNodeIdentifier() {
return subscriberIdentifier.getNodeIdentifier();
}
public URI getSlaveUri() {
return subscriberIdentifier.getUri();
}
public GraphName getTopicName() {
return topicDeclaration.getName();
}
public ConnectionHeader toConnectionHeader() {
ConnectionHeader connectionHeader = new ConnectionHeader();
connectionHeader.merge(subscriberIdentifier.toConnectionHeader());
connectionHeader.merge(topicDeclaration.toConnectionHeader());
return connectionHeader;
}
@Override
public String toString() {
return "SubscriberDefinition<" + subscriberIdentifier + ", " + topicDeclaration + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result =
prime * result + ((subscriberIdentifier == null) ? 0 : subscriberIdentifier.hashCode());
result = prime * result + ((topicDeclaration == null) ? 0 : topicDeclaration.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SubscriberDeclaration other = (SubscriberDeclaration) obj;
if (subscriberIdentifier == null) {
if (other.subscriberIdentifier != null)
return false;
} else if (!subscriberIdentifier.equals(other.subscriberIdentifier))
return false;
if (topicDeclaration == null) {
if (other.topicDeclaration != null)
return false;
} else if (!topicDeclaration.equals(other.topicDeclaration))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.ros.internal.message.topic.TopicDescription;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.internal.transport.ConnectionHeaderFields;
import org.ros.namespace.GraphName;
import java.util.List;
import java.util.Map;
/**
* A topic in a ROS graph.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class TopicDeclaration {
private final TopicIdentifier topicIdentifier;
private final TopicDescription topicDescription;
/**
* @param header
* a {@link Map} of header fields
* @return a new {@link TopicDeclaration} from the given header
*/
public static TopicDeclaration newFromHeader(Map<String, String> header) {
Preconditions.checkArgument(header.containsKey(ConnectionHeaderFields.TOPIC));
GraphName name = GraphName.of(header.get(ConnectionHeaderFields.TOPIC));
String type = header.get(ConnectionHeaderFields.TYPE);
String definition = header.get(ConnectionHeaderFields.MESSAGE_DEFINITION);
String md5Checksum = header.get(ConnectionHeaderFields.MD5_CHECKSUM);
TopicDescription topicDescription = new TopicDescription(type, definition, md5Checksum);
return new TopicDeclaration(new TopicIdentifier(name), topicDescription);
}
public static TopicDeclaration newFromTopicName(GraphName topicName,
TopicDescription topicDescription) {
return new TopicDeclaration(new TopicIdentifier(topicName), topicDescription);
}
public TopicDeclaration(TopicIdentifier topicIdentifier, TopicDescription topicDescription) {
Preconditions.checkNotNull(topicIdentifier);
Preconditions.checkNotNull(topicDescription);
this.topicIdentifier = topicIdentifier;
this.topicDescription = topicDescription;
}
public TopicIdentifier getIdentifier() {
return topicIdentifier;
}
public GraphName getName() {
return topicIdentifier.getName();
}
public String getMessageType() {
return topicDescription.getType();
}
public ConnectionHeader toConnectionHeader() {
ConnectionHeader connectionHeader = new ConnectionHeader();
connectionHeader.merge(topicIdentifier.toConnectionHeader());
connectionHeader.addField(ConnectionHeaderFields.TYPE, topicDescription.getType());
connectionHeader.addField(ConnectionHeaderFields.MESSAGE_DEFINITION,
topicDescription.getDefinition());
connectionHeader.addField(ConnectionHeaderFields.MD5_CHECKSUM,
topicDescription.getMd5Checksum());
return connectionHeader;
}
public List<String> toList() {
return Lists.newArrayList(getName().toString(), getMessageType());
}
@Override
public String toString() {
return "Topic<" + topicIdentifier + ", " + topicDescription.toString() + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((topicDescription == null) ? 0 : topicDescription.hashCode());
result = prime * result + ((topicIdentifier == null) ? 0 : topicIdentifier.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TopicDeclaration other = (TopicDeclaration) obj;
if (topicDescription == null) {
if (other.topicDescription != null)
return false;
} else if (!topicDescription.equals(other.topicDescription))
return false;
if (topicIdentifier == null) {
if (other.topicIdentifier != null)
return false;
} else if (!topicIdentifier.equals(other.topicIdentifier))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import com.google.common.base.Preconditions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.ros.concurrent.ListenerGroup;
import org.ros.concurrent.SignalRunnable;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.internal.transport.ConnectionHeaderFields;
import org.ros.internal.transport.queue.OutgoingMessageQueue;
import org.ros.message.MessageFactory;
import org.ros.message.MessageSerializer;
import org.ros.node.topic.DefaultPublisherListener;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.PublisherListener;
import org.ros.node.topic.Subscriber;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Default implementation of a {@link Publisher}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class DefaultPublisher<T> extends DefaultTopicParticipant implements Publisher<T> {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(DefaultPublisher.class);
/**
* The maximum delay before shutdown will begin even if all
* {@link PublisherListener}s have not yet returned from their
* {@link PublisherListener#onShutdown(Publisher)} callback.
*/
private static final long DEFAULT_SHUTDOWN_TIMEOUT = 5;
private static final TimeUnit DEFAULT_SHUTDOWN_TIMEOUT_UNITS = TimeUnit.SECONDS;
/**
* Queue of all messages being published by this {@link Publisher}.
*/
private final OutgoingMessageQueue<T> outgoingMessageQueue;
private final ListenerGroup<PublisherListener<T>> listeners;
private final NodeIdentifier nodeIdentifier;
private final MessageFactory messageFactory;
public DefaultPublisher(NodeIdentifier nodeIdentifier, TopicDeclaration topicDeclaration,
MessageSerializer<T> serializer, MessageFactory messageFactory,
ScheduledExecutorService executorService) {
super(topicDeclaration);
this.nodeIdentifier = nodeIdentifier;
this.messageFactory = messageFactory;
outgoingMessageQueue = new OutgoingMessageQueue<T>(serializer, executorService);
listeners = new ListenerGroup<PublisherListener<T>>(executorService);
listeners.add(new DefaultPublisherListener<T>() {
@Override
public void onMasterRegistrationSuccess(Publisher<T> registrant) {
log.info("Publisher registered: " + DefaultPublisher.this);
}
@Override
public void onMasterRegistrationFailure(Publisher<T> registrant) {
log.info("Publisher registration failed: " + DefaultPublisher.this);
}
@Override
public void onMasterUnregistrationSuccess(Publisher<T> registrant) {
log.info("Publisher unregistered: " + DefaultPublisher.this);
}
@Override
public void onMasterUnregistrationFailure(Publisher<T> registrant) {
log.info("Publisher unregistration failed: " + DefaultPublisher.this);
}
});
}
@Override
public void setLatchMode(boolean enabled) {
outgoingMessageQueue.setLatchMode(enabled);
}
@Override
public boolean getLatchMode() {
return outgoingMessageQueue.getLatchMode();
}
@Override
public void shutdown(long timeout, TimeUnit unit) {
signalOnShutdown(timeout, unit);
outgoingMessageQueue.shutdown();
}
@Override
public void shutdown() {
shutdown(DEFAULT_SHUTDOWN_TIMEOUT, DEFAULT_SHUTDOWN_TIMEOUT_UNITS);
}
public PublisherIdentifier getIdentifier() {
return new PublisherIdentifier(nodeIdentifier, getTopicDeclaration().getIdentifier());
}
public PublisherDeclaration toDeclaration() {
return PublisherDeclaration.newFromNodeIdentifier(nodeIdentifier, getTopicDeclaration());
}
@Override
public boolean hasSubscribers() {
return outgoingMessageQueue.getNumberOfChannels() > 0;
}
@Override
public int getNumberOfSubscribers() {
return outgoingMessageQueue.getNumberOfChannels();
}
@Override
public T newMessage() {
return messageFactory.newFromType(getTopicDeclaration().getMessageType());
}
@Override
public void publish(T message) {
if (DEBUG) {
log.info(String.format("Publishing message %s on topic %s.", message, getTopicName()));
}
outgoingMessageQueue.add(message);
}
/**
* Complete connection handshake on buffer. This generates the connection
* header for this publisher to send and also updates the connection state of
* this publisher.
*
* @return encoded connection header from subscriber
*/
public ChannelBuffer finishHandshake(ConnectionHeader incomingHeader) {
ConnectionHeader topicDefinitionHeader = getTopicDeclarationHeader();
if (DEBUG) {
log.info("Subscriber handshake header: " + incomingHeader);
log.info("Publisher handshake header: " + topicDefinitionHeader);
}
// TODO(damonkohler): Return errors to the subscriber over the wire.
String incomingType = incomingHeader.getField(ConnectionHeaderFields.TYPE);
String expectedType = topicDefinitionHeader.getField(ConnectionHeaderFields.TYPE);
boolean messageTypeMatches =
incomingType.equals(expectedType)
|| incomingType.equals(Subscriber.TOPIC_MESSAGE_TYPE_WILDCARD);
Preconditions.checkState(messageTypeMatches, "Unexpected message type " + incomingType + " != "
+ expectedType);
String incomingChecksum = incomingHeader.getField(ConnectionHeaderFields.MD5_CHECKSUM);
String expectedChecksum = topicDefinitionHeader.getField(ConnectionHeaderFields.MD5_CHECKSUM);
boolean checksumMatches =
incomingChecksum.equals(expectedChecksum)
|| incomingChecksum.equals(Subscriber.TOPIC_MESSAGE_TYPE_WILDCARD);
Preconditions.checkState(checksumMatches, "Unexpected message MD5 " + incomingChecksum + " != "
+ expectedChecksum);
ConnectionHeader outgoingConnectionHeader = toDeclaration().toConnectionHeader();
// TODO(damonkohler): Force latch mode to be consistent throughout the life
// of the publisher.
outgoingConnectionHeader.addField(ConnectionHeaderFields.LATCHING, getLatchMode() ? "1" : "0");
return outgoingConnectionHeader.encode();
}
/**
* Add a {@link Subscriber} connection to this {@link Publisher}.
*
* @param subscriberIdentifer
* the {@link SubscriberIdentifier} of the new subscriber
* @param channel
* the communication {@link Channel} to the {@link Subscriber}
*/
public void addSubscriber(SubscriberIdentifier subscriberIdentifer, Channel channel) {
if (DEBUG) {
log.info(String.format("Adding subscriber %s channel %s to publisher %s.",
subscriberIdentifer, channel, this));
}
outgoingMessageQueue.addChannel(channel);
signalOnNewSubscriber(subscriberIdentifer);
}
@Override
public void addListener(PublisherListener<T> listener) {
listeners.add(listener);
}
/**
* Signal all {@link PublisherListener}s that the {@link Publisher} has
* successfully registered with the master.
* <p>
* Each listener is called in a separate thread.
*/
@Override
public void signalOnMasterRegistrationSuccess() {
final Publisher<T> publisher = this;
listeners.signal(new SignalRunnable<PublisherListener<T>>() {
@Override
public void run(PublisherListener<T> listener) {
listener.onMasterRegistrationSuccess(publisher);
}
});
}
/**
* Signal all {@link PublisherListener}s that the {@link Publisher} has failed
* to register with the master.
* <p>
* Each listener is called in a separate thread.
*/
@Override
public void signalOnMasterRegistrationFailure() {
final Publisher<T> publisher = this;
listeners.signal(new SignalRunnable<PublisherListener<T>>() {
@Override
public void run(PublisherListener<T> listener) {
listener.onMasterRegistrationFailure(publisher);
}
});
}
/**
* Signal all {@link PublisherListener}s that the {@link Publisher} has
* successfully unregistered with the master.
* <p>
* Each listener is called in a separate thread.
*/
@Override
public void signalOnMasterUnregistrationSuccess() {
final Publisher<T> publisher = this;
listeners.signal(new SignalRunnable<PublisherListener<T>>() {
@Override
public void run(PublisherListener<T> listener) {
listener.onMasterUnregistrationSuccess(publisher);
}
});
}
/**
* Signal all {@link PublisherListener}s that the {@link Publisher} has failed
* to unregister with the master.
* <p>
* Each listener is called in a separate thread.
*/
@Override
public void signalOnMasterUnregistrationFailure() {
final Publisher<T> publisher = this;
listeners.signal(new SignalRunnable<PublisherListener<T>>() {
@Override
public void run(PublisherListener<T> listener) {
listener.onMasterUnregistrationFailure(publisher);
}
});
}
/**
* Signal all {@link PublisherListener}s that the {@link Publisher} has a new
* {@link Subscriber}.
* <p>
* Each listener is called in a separate thread.
*
* @param subscriberIdentifier
* the {@link SubscriberIdentifier} of the new {@link Subscriber}
*/
private void signalOnNewSubscriber(final SubscriberIdentifier subscriberIdentifier) {
final Publisher<T> publisher = this;
listeners.signal(new SignalRunnable<PublisherListener<T>>() {
@Override
public void run(PublisherListener<T> listener) {
listener.onNewSubscriber(publisher, subscriberIdentifier);
}
});
}
/**
* Signal all {@link PublisherListener}s that the {@link Publisher} is being
* shut down. Listeners should exit quickly since they may block shut down.
* <p>
* Each listener is called in a separate thread.
*
* @param timeout
* @param unit
*/
private void signalOnShutdown(long timeout, TimeUnit unit) {
final Publisher<T> publisher = this;
try {
listeners.signal(new SignalRunnable<PublisherListener<T>>() {
@Override
public void run(PublisherListener<T> listener) {
listener.onShutdown(publisher);
}
}, timeout, unit);
} catch (InterruptedException e) {
// Ignored since we do not guarantee that all listeners will finish before
// shutdown begins.
}
}
@Override
public String toString() {
return "Publisher<" + toDeclaration() + ">";
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import org.ros.namespace.GraphName;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
import java.util.Collection;
import java.util.Map;
/**
* Manages a collection of {@link Publisher}s and {@link Subscriber}s.
*
* @author kwc@willowgarage.com (Ken Conley)
* @author damonkohler@google.com (Damon Kohler)
*/
public class TopicParticipantManager {
/**
* A mapping from topic name to {@link Subscriber}.
*/
private final Map<GraphName, DefaultSubscriber<?>> subscribers;
/**
* A mapping from topic name to {@link Publisher}.
*/
private final Map<GraphName, DefaultPublisher<?>> publishers;
/**
* A mapping from {@link Subscriber} to its connected
* {@link PublisherIdentifier}s.
*/
private final Multimap<DefaultSubscriber<?>, PublisherIdentifier> subscriberConnections;
/**
* A mapping from {@link Publisher} to its connected
* {@link SubscriberIdentifier}s.
*/
private final Multimap<DefaultPublisher<?>, SubscriberIdentifier> publisherConnections;
// TODO(damonkohler): Change to ListenerGroup.
private TopicParticipantManagerListener listener;
public TopicParticipantManager() {
publishers = Maps.newConcurrentMap();
subscribers = Maps.newConcurrentMap();
subscriberConnections = HashMultimap.create();
publisherConnections = HashMultimap.create();
}
public void setListener(TopicParticipantManagerListener listener) {
this.listener = listener;
}
public boolean hasSubscriber(GraphName topicName) {
return subscribers.containsKey(topicName);
}
public boolean hasPublisher(GraphName topicName) {
return publishers.containsKey(topicName);
}
public DefaultPublisher<?> getPublisher(GraphName topicName) {
return publishers.get(topicName);
}
public DefaultSubscriber<?> getSubscriber(GraphName topicName) {
return subscribers.get(topicName);
}
public void addPublisher(DefaultPublisher<?> publisher) {
publishers.put(publisher.getTopicName(), publisher);
if (listener != null) {
listener.onPublisherAdded(publisher);
}
}
public void removePublisher(DefaultPublisher<?> publisher) {
publishers.remove(publisher.getTopicName());
if (listener != null) {
listener.onPublisherRemoved(publisher);
}
}
public void addSubscriber(DefaultSubscriber<?> subscriber) {
subscribers.put(subscriber.getTopicName(), subscriber);
if (listener != null) {
listener.onSubscriberAdded(subscriber);
}
}
public void removeSubscriber(DefaultSubscriber<?> subscriber) {
subscribers.remove(subscriber.getTopicName());
if (listener != null) {
listener.onSubscriberRemoved(subscriber);
}
}
public void addSubscriberConnection(DefaultSubscriber<?> subscriber,
PublisherIdentifier publisherIdentifier) {
subscriberConnections.put(subscriber, publisherIdentifier);
}
public void removeSubscriberConnection(DefaultSubscriber<?> subscriber,
PublisherIdentifier publisherIdentifier) {
subscriberConnections.remove(subscriber, publisherIdentifier);
}
public void addPublisherConnection(DefaultPublisher<?> publisher,
SubscriberIdentifier subscriberIdentifier) {
publisherConnections.put(publisher, subscriberIdentifier);
}
public void removePublisherConnection(DefaultPublisher<?> publisher,
SubscriberIdentifier subscriberIdentifier) {
publisherConnections.remove(publisher, subscriberIdentifier);
}
public Collection<DefaultSubscriber<?>> getSubscribers() {
return ImmutableList.copyOf(subscribers.values());
}
public Collection<PublisherIdentifier> getSubscriberConnections(DefaultSubscriber<?> subscriber) {
return ImmutableList.copyOf(subscriberConnections.get(subscriber));
}
public Collection<DefaultPublisher<?>> getPublishers() {
return ImmutableList.copyOf(publishers.values());
}
public Collection<SubscriberIdentifier> getPublisherConnections(DefaultPublisher<?> publisher) {
return ImmutableList.copyOf(publisherConnections.get(publisher));
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.namespace.GraphName;
import org.ros.node.Node;
import org.ros.node.topic.Publisher;
import java.net.URI;
import java.util.Collection;
import java.util.Set;
/**
* All information needed to identify a publisher.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class PublisherIdentifier {
private final NodeIdentifier nodeIdentifier;
private final TopicIdentifier topicIdentifier;
public static Collection<PublisherIdentifier> newCollectionFromUris(
Collection<URI> publisherUris, TopicDeclaration topicDeclaration) {
Set<PublisherIdentifier> publishers = Sets.newHashSet();
for (URI uri : publisherUris) {
NodeIdentifier nodeIdentifier = new NodeIdentifier(null, uri);
publishers.add(new PublisherIdentifier(nodeIdentifier, topicDeclaration.getIdentifier()));
}
return publishers;
}
public static PublisherIdentifier newFromStrings(String nodeName, String uri, String topicName) {
return new PublisherIdentifier(NodeIdentifier.forNameAndUri(nodeName, uri),
TopicIdentifier.forName(topicName));
}
public PublisherIdentifier(NodeIdentifier nodeIdentifier, TopicIdentifier topicIdentifier) {
Preconditions.checkNotNull(nodeIdentifier);
Preconditions.checkNotNull(topicIdentifier);
this.nodeIdentifier = nodeIdentifier;
this.topicIdentifier = topicIdentifier;
}
public ConnectionHeader toConnectionHeader() {
ConnectionHeader connectionHeader = new ConnectionHeader();
connectionHeader.merge(nodeIdentifier.toConnectionHeader());
connectionHeader.merge(topicIdentifier.toConnectionHeader());
return connectionHeader;
}
public NodeIdentifier getNodeIdentifier() {
return nodeIdentifier;
}
/**
* @return the {@link GraphName} of the {@link Node} hosting this
* {@link Publisher}
*/
public GraphName getNodeName() {
return nodeIdentifier.getName();
}
/**
* @return the {@link URI} of the {@link Node} hosting this {@link Publisher}
*/
public URI getNodeUri() {
return nodeIdentifier.getUri();
}
/**
* @return the {@link TopicIdentifier} for the {@link Publisher}'s topic
*/
public TopicIdentifier getTopicIdentifier() {
return topicIdentifier;
}
/**
* @return the {@link GraphName} of this {@link Publisher}'s topic
*/
public GraphName getTopicName() {
return topicIdentifier.getName();
}
@Override
public String toString() {
return "PublisherIdentifier<" + nodeIdentifier + ", " + topicIdentifier + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + nodeIdentifier.hashCode();
result = prime * result + topicIdentifier.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PublisherIdentifier other = (PublisherIdentifier) obj;
if (!nodeIdentifier.equals(other.nodeIdentifier))
return false;
if (!topicIdentifier.equals(other.topicIdentifier))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import com.google.common.base.Preconditions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ros.internal.node.BaseClientHandshake;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.internal.transport.ConnectionHeaderFields;
/**
* Handshake logic from the subscriber side of a topic connection.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class SubscriberHandshake extends BaseClientHandshake {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(SubscriberHandshake.class);
public SubscriberHandshake(ConnectionHeader outgoingConnectionHeader) {
super(outgoingConnectionHeader);
Preconditions.checkNotNull(outgoingConnectionHeader.getField(ConnectionHeaderFields.TYPE));
Preconditions.checkNotNull(outgoingConnectionHeader
.getField(ConnectionHeaderFields.MD5_CHECKSUM));
}
@Override
public boolean handshake(ConnectionHeader incommingConnectionHeader) {
if (DEBUG) {
log.info("Outgoing subscriber connection header: " + outgoingConnectionHeader);
log.info("Incoming publisher connection header: " + incommingConnectionHeader);
}
setErrorMessage(incommingConnectionHeader.getField(ConnectionHeaderFields.ERROR));
String incomingType = incommingConnectionHeader.getField(ConnectionHeaderFields.TYPE);
if (incomingType == null) {
setErrorMessage("Incoming type cannot be null.");
} else if (!incomingType.equals(outgoingConnectionHeader.getField(ConnectionHeaderFields.TYPE))) {
setErrorMessage("Message types don't match.");
}
String incomingMd5Checksum =
incommingConnectionHeader.getField(ConnectionHeaderFields.MD5_CHECKSUM);
if (incomingMd5Checksum == null) {
setErrorMessage("Incoming MD5 checksum cannot be null.");
} else if (!incomingMd5Checksum.equals(outgoingConnectionHeader
.getField(ConnectionHeaderFields.MD5_CHECKSUM))) {
setErrorMessage("Checksums don't match.");
}
return getErrorMessage() == null;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import com.google.common.base.Preconditions;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.internal.transport.ConnectionHeaderFields;
import org.ros.namespace.GraphName;
/**
* The identifier for a topic in a ROS graph.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class TopicIdentifier {
private final GraphName name;
public static TopicIdentifier forName(String name) {
return new TopicIdentifier(GraphName.of(name));
}
public TopicIdentifier(GraphName name) {
Preconditions.checkNotNull(name);
Preconditions.checkArgument(name.isGlobal());
this.name = name;
}
public ConnectionHeader toConnectionHeader() {
ConnectionHeader connectionHeader = new ConnectionHeader();
connectionHeader.addField(ConnectionHeaderFields.TOPIC, name.toString());
return connectionHeader;
}
public GraphName getName() {
return name;
}
@Override
public String toString() {
return "TopicIdentifier<" + name + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
TopicIdentifier other = (TopicIdentifier) obj;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Sets;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ros.concurrent.ListenerGroup;
import org.ros.concurrent.SignalRunnable;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.internal.transport.ProtocolNames;
import org.ros.internal.transport.queue.IncomingMessageQueue;
import org.ros.internal.transport.tcp.TcpClientManager;
import org.ros.message.MessageDeserializer;
import org.ros.message.MessageListener;
import org.ros.node.topic.DefaultSubscriberListener;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
import org.ros.node.topic.SubscriberListener;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Default implementation of a {@link Subscriber}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class DefaultSubscriber<T> extends DefaultTopicParticipant implements Subscriber<T> {
private static final Log log = LogFactory.getLog(DefaultPublisher.class);
/**
* The maximum delay before shutdown will begin even if all
* {@link SubscriberListener}s have not yet returned from their
* {@link SubscriberListener#onShutdown(Subscriber)} callback.
*/
private static final int DEFAULT_SHUTDOWN_TIMEOUT = 5;
private static final TimeUnit DEFAULT_SHUTDOWN_TIMEOUT_UNITS = TimeUnit.SECONDS;
private final NodeIdentifier nodeIdentifier;
private final ScheduledExecutorService executorService;
private final IncomingMessageQueue<T> incomingMessageQueue;
private final Set<PublisherIdentifier> knownPublishers;
private final TcpClientManager tcpClientManager;
private final Object mutex;
/**
* Manages the {@link SubscriberListener}s for this {@link Subscriber}.
*/
private final ListenerGroup<SubscriberListener<T>> subscriberListeners;
public static <S> DefaultSubscriber<S> newDefault(NodeIdentifier nodeIdentifier,
TopicDeclaration description, ScheduledExecutorService executorService,
MessageDeserializer<S> deserializer) {
return new DefaultSubscriber<S>(nodeIdentifier, description, deserializer, executorService);
}
private DefaultSubscriber(NodeIdentifier nodeIdentifier, TopicDeclaration topicDeclaration,
MessageDeserializer<T> deserializer, ScheduledExecutorService executorService) {
super(topicDeclaration);
this.nodeIdentifier = nodeIdentifier;
this.executorService = executorService;
incomingMessageQueue = new IncomingMessageQueue<T>(deserializer, executorService);
knownPublishers = Sets.newHashSet();
tcpClientManager = new TcpClientManager(executorService);
mutex = new Object();
SubscriberHandshakeHandler<T> subscriberHandshakeHandler =
new SubscriberHandshakeHandler<T>(toDeclaration().toConnectionHeader(),
incomingMessageQueue, executorService);
tcpClientManager.addNamedChannelHandler(subscriberHandshakeHandler);
subscriberListeners = new ListenerGroup<SubscriberListener<T>>(executorService);
subscriberListeners.add(new DefaultSubscriberListener<T>() {
@Override
public void onMasterRegistrationSuccess(Subscriber<T> registrant) {
log.info("Subscriber registered: " + DefaultSubscriber.this);
}
@Override
public void onMasterRegistrationFailure(Subscriber<T> registrant) {
log.info("Subscriber registration failed: " + DefaultSubscriber.this);
}
@Override
public void onMasterUnregistrationSuccess(Subscriber<T> registrant) {
log.info("Subscriber unregistered: " + DefaultSubscriber.this);
}
@Override
public void onMasterUnregistrationFailure(Subscriber<T> registrant) {
log.info("Subscriber unregistration failed: " + DefaultSubscriber.this);
}
});
}
public SubscriberIdentifier toIdentifier() {
return new SubscriberIdentifier(nodeIdentifier, getTopicDeclaration().getIdentifier());
}
public SubscriberDeclaration toDeclaration() {
return new SubscriberDeclaration(toIdentifier(), getTopicDeclaration());
}
public Collection<String> getSupportedProtocols() {
return ProtocolNames.SUPPORTED;
}
@Override
public boolean getLatchMode() {
return incomingMessageQueue.getLatchMode();
}
@Override
public void addMessageListener(MessageListener<T> messageListener, int limit) {
incomingMessageQueue.addListener(messageListener, limit);
}
@Override
public void addMessageListener(MessageListener<T> messageListener) {
addMessageListener(messageListener, 1);
}
@VisibleForTesting
public void addPublisher(PublisherIdentifier publisherIdentifier, InetSocketAddress address) {
synchronized (mutex) {
// TODO(damonkohler): If the connection is dropped, knownPublishers should
// be updated.
if (knownPublishers.contains(publisherIdentifier)) {
return;
}
tcpClientManager.connect(toString(), address);
// TODO(damonkohler): knownPublishers is duplicate information that is
// already available to the TopicParticipantManager.
knownPublishers.add(publisherIdentifier);
signalOnNewPublisher(publisherIdentifier);
}
}
/**
* Updates the list of {@link Publisher}s for the topic that this
* {@link Subscriber} is interested in.
*
* @param publisherIdentifiers
* {@link Collection} of {@link PublisherIdentifier}s for the
* subscribed topic
*/
public void updatePublishers(Collection<PublisherIdentifier> publisherIdentifiers) {
for (final PublisherIdentifier publisherIdentifier : publisherIdentifiers) {
executorService.execute(new UpdatePublisherRunnable<T>(this, nodeIdentifier,
publisherIdentifier));
}
}
@Override
public void shutdown(long timeout, TimeUnit unit) {
signalOnShutdown(timeout, unit);
incomingMessageQueue.shutdown();
tcpClientManager.shutdown();
subscriberListeners.shutdown();
}
@Override
public void shutdown() {
shutdown(DEFAULT_SHUTDOWN_TIMEOUT, DEFAULT_SHUTDOWN_TIMEOUT_UNITS);
}
@Override
public void addSubscriberListener(SubscriberListener<T> listener) {
subscriberListeners.add(listener);
}
/**
* Signal all {@link SubscriberListener}s that the {@link Subscriber} has
* successfully registered with the master.
* <p>
* Each listener is called in a separate thread.
*/
@Override
public void signalOnMasterRegistrationSuccess() {
final Subscriber<T> subscriber = this;
subscriberListeners.signal(new SignalRunnable<SubscriberListener<T>>() {
@Override
public void run(SubscriberListener<T> listener) {
listener.onMasterRegistrationSuccess(subscriber);
}
});
}
/**
* Signal all {@link SubscriberListener}s that the {@link Subscriber} has
* failed to register with the master.
*
* <p>
* Each listener is called in a separate thread.
*/
@Override
public void signalOnMasterRegistrationFailure() {
final Subscriber<T> subscriber = this;
subscriberListeners.signal(new SignalRunnable<SubscriberListener<T>>() {
@Override
public void run(SubscriberListener<T> listener) {
listener.onMasterRegistrationFailure(subscriber);
}
});
}
/**
* Signal all {@link SubscriberListener}s that the {@link Subscriber} has
* successfully unregistered with the master.
* <p>
* Each listener is called in a separate thread.
*/
@Override
public void signalOnMasterUnregistrationSuccess() {
final Subscriber<T> subscriber = this;
subscriberListeners.signal(new SignalRunnable<SubscriberListener<T>>() {
@Override
public void run(SubscriberListener<T> listener) {
listener.onMasterUnregistrationSuccess(subscriber);
}
});
}
/**
* Signal all {@link SubscriberListener}s that the {@link Subscriber} has
* failed to unregister with the master.
* <p>
* Each listener is called in a separate thread.
*/
@Override
public void signalOnMasterUnregistrationFailure() {
final Subscriber<T> subscriber = this;
subscriberListeners.signal(new SignalRunnable<SubscriberListener<T>>() {
@Override
public void run(SubscriberListener<T> listener) {
listener.onMasterUnregistrationFailure(subscriber);
}
});
}
/**
* Signal all {@link SubscriberListener}s that a new {@link Publisher} has
* connected.
* <p>
* Each listener is called in a separate thread.
*/
public void signalOnNewPublisher(final PublisherIdentifier publisherIdentifier) {
final Subscriber<T> subscriber = this;
subscriberListeners.signal(new SignalRunnable<SubscriberListener<T>>() {
@Override
public void run(SubscriberListener<T> listener) {
listener.onNewPublisher(subscriber, publisherIdentifier);
}
});
}
/**
* Signal all {@link SubscriberListener}s that the {@link Subscriber} has shut
* down.
* <p>
* Each listener is called in a separate thread.
*/
private void signalOnShutdown(long timeout, TimeUnit unit) {
final Subscriber<T> subscriber = this;
try {
subscriberListeners.signal(new SignalRunnable<SubscriberListener<T>>() {
@Override
public void run(SubscriberListener<T> listener) {
listener.onShutdown(subscriber);
}
}, timeout, unit);
} catch (InterruptedException e) {
// Ignored since we do not guarantee that all listeners will finish before
// shutdown begins.
}
}
@Override
public String toString() {
return "Subscriber<" + getTopicDeclaration() + ">";
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.master.client.TopicSystemState;
import org.ros.namespace.GraphName;
import java.util.List;
/**
* Base definition of a {@link TopicSystemState}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public abstract class DefaultTopicParticipant implements TopicParticipant {
private final TopicDeclaration topicDeclaration;
public DefaultTopicParticipant(TopicDeclaration topicDeclaration) {
this.topicDeclaration = topicDeclaration;
}
/**
* @return the {@link TopicDeclaration} of this {@link TopicParticipant}
*/
public TopicDeclaration getTopicDeclaration() {
return topicDeclaration;
}
public List<String> getTopicDeclarationAsList() {
return topicDeclaration.toList();
}
@Override
public GraphName getTopicName() {
return topicDeclaration.getName();
}
@Override
public String getTopicMessageType() {
return topicDeclaration.getMessageType();
}
/**
* @return the connection header for the {@link TopicSystemState}
*/
public ConnectionHeader getTopicDeclarationHeader() {
return topicDeclaration.toConnectionHeader();
}
/**
* Signal that the {@link TopicSystemState} successfully registered with the master.
*/
public abstract void signalOnMasterRegistrationSuccess();
/**
* Signal that the {@link TopicSystemState} failed to register with the master.
*/
public abstract void signalOnMasterRegistrationFailure();
/**
* Signal that the {@link TopicSystemState} successfully unregistered with the master.
*/
public abstract void signalOnMasterUnregistrationSuccess();
/**
* Signal that the {@link TopicSystemState} failed to unregister with the master.
*/
public abstract void signalOnMasterUnregistrationFailure();
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
/**
* Listener for {@link TopicParticipantManager} events.
*
* @author kwc@willowgarage.com (Ken Conley)
* @author damonkohler@google.com (Damon Kohler)
*/
public interface TopicParticipantManagerListener {
/**
* Called when a new {@link Publisher} is added.
*
* @param publisher
* the {@link Publisher} that was added
*/
void onPublisherAdded(DefaultPublisher<?> publisher);
/**
* Called when a new {@link Publisher} is removed.
*
* @param publisher
* the {@link Publisher} that was removed
*/
void onPublisherRemoved(DefaultPublisher<?> publisher);
/**
* Called when a {@link Subscriber} is added.
*
* @param subscriber
* the {@link Subscriber} that was added
*/
void onSubscriberAdded(DefaultSubscriber<?> subscriber);
/**
* Called when a {@link Subscriber} is removed.
*
* @param subscriber
* the {@link Subscriber} that was removed
*/
void onSubscriberRemoved(DefaultSubscriber<?> subscriber);
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ros.exception.RemoteException;
import org.ros.internal.node.client.SlaveClient;
import org.ros.internal.node.response.Response;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.internal.node.server.SlaveServer;
import org.ros.internal.node.xmlrpc.XmlRpcTimeoutException;
import org.ros.internal.transport.ProtocolDescription;
import org.ros.internal.transport.ProtocolNames;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
/**
* A {@link Runnable} which is used whenever new publishers are being added to a
* {@link DefaultSubscriber}. It takes care of registration between the {@link Subscriber}
* and remote {@link Publisher}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
class UpdatePublisherRunnable<MessageType> implements Runnable {
private static final Log log = LogFactory.getLog(UpdatePublisherRunnable.class);
private final DefaultSubscriber<MessageType> subscriber;
private final PublisherIdentifier publisherIdentifier;
private final NodeIdentifier nodeIdentifier;
/**
* @param subscriber
* @param nodeIdentifier
* {@link NodeIdentifier} of the {@link Subscriber}'s
* {@link SlaveServer}
* @param publisherIdentifier
* {@link PublisherIdentifier} of the new {@link Publisher}
*/
public UpdatePublisherRunnable(DefaultSubscriber<MessageType> subscriber,
NodeIdentifier nodeIdentifier, PublisherIdentifier publisherIdentifier) {
this.subscriber = subscriber;
this.nodeIdentifier = nodeIdentifier;
this.publisherIdentifier = publisherIdentifier;
}
@Override
public void run() {
SlaveClient slaveClient;
try {
slaveClient = new SlaveClient(nodeIdentifier.getName(), publisherIdentifier.getNodeUri());
Response<ProtocolDescription> response =
slaveClient.requestTopic(subscriber.getTopicName(), ProtocolNames.SUPPORTED);
// TODO(kwc): all of this logic really belongs in a protocol handler
// registry.
ProtocolDescription selected = response.getResult();
if (ProtocolNames.SUPPORTED.contains(selected.getName())) {
subscriber.addPublisher(publisherIdentifier, selected.getAddress());
} else {
log.error("Publisher returned unsupported protocol selection: " + response);
}
} catch (RemoteException e) {
// TODO(damonkohler): Retry logic is needed at the XML-RPC layer.
log.error(e);
} catch (XmlRpcTimeoutException e) {
// TODO(damonkohler): see above note re: retry
log.error(e);
} catch (RuntimeException e) {
// TODO(kwc):
// org.apache.xmlrpc.XmlRpcException/java.net.ConnectException's are
// leaking through as java.lang.reflect.UndeclaredThrowableExceptions.
// This is happening whenever the node attempts to connect to a stale
// publisher (i.e. a publisher that is no longer online).
log.error(e);
}
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import com.google.common.base.Preconditions;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.namespace.GraphName;
import java.net.URI;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class PublisherDeclaration {
private final PublisherIdentifier publisherIdentifier;
private final TopicDeclaration topicDeclaration;
public static PublisherDeclaration newFromNodeIdentifier(NodeIdentifier nodeIdentifier,
TopicDeclaration topicDeclaration) {
Preconditions.checkNotNull(nodeIdentifier);
Preconditions.checkNotNull(topicDeclaration);
return new PublisherDeclaration(new PublisherIdentifier(nodeIdentifier,
topicDeclaration.getIdentifier()), topicDeclaration);
}
public PublisherDeclaration(PublisherIdentifier publisherIdentifier,
TopicDeclaration topicDeclaration) {
Preconditions.checkNotNull(publisherIdentifier);
Preconditions.checkNotNull(topicDeclaration);
Preconditions.checkArgument(publisherIdentifier.getTopicIdentifier().equals(
topicDeclaration.getIdentifier()));
this.publisherIdentifier = publisherIdentifier;
this.topicDeclaration = topicDeclaration;
}
public ConnectionHeader toConnectionHeader() {
ConnectionHeader connectionHeader = publisherIdentifier.toConnectionHeader();
connectionHeader.merge(topicDeclaration.toConnectionHeader());
return connectionHeader;
}
public NodeIdentifier getSlaveIdentifier() {
return publisherIdentifier.getNodeIdentifier();
}
public GraphName getSlaveName() {
return publisherIdentifier.getNodeIdentifier().getName();
}
public URI getSlaveUri() {
return publisherIdentifier.getNodeUri();
}
public GraphName getTopicName() {
return topicDeclaration.getName();
}
public String getTopicMessageType() {
return topicDeclaration.getMessageType();
}
@Override
public String toString() {
return "PublisherDefinition<" + publisherIdentifier + ", " + topicDeclaration + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((publisherIdentifier == null) ? 0 : publisherIdentifier.hashCode());
result = prime * result + ((topicDeclaration == null) ? 0 : topicDeclaration.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PublisherDeclaration other = (PublisherDeclaration) obj;
if (publisherIdentifier == null) {
if (other.publisherIdentifier != null)
return false;
} else if (!publisherIdentifier.equals(other.publisherIdentifier))
return false;
if (topicDeclaration == null) {
if (other.topicDeclaration != null)
return false;
} else if (!topicDeclaration.equals(other.topicDeclaration))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import com.google.common.base.Preconditions;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.namespace.GraphName;
import java.net.URI;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class SubscriberIdentifier {
private final NodeIdentifier nodeIdentifier;
private final TopicIdentifier topicIdentifier;
public SubscriberIdentifier(NodeIdentifier nodeIdentifier, TopicIdentifier topicIdentifier) {
Preconditions.checkNotNull(nodeIdentifier);
Preconditions.checkNotNull(topicIdentifier);
this.nodeIdentifier = nodeIdentifier;
this.topicIdentifier = topicIdentifier;
}
public ConnectionHeader toConnectionHeader() {
ConnectionHeader connectionHeader = new ConnectionHeader();
connectionHeader.merge(nodeIdentifier.toConnectionHeader());
connectionHeader.merge(topicIdentifier.toConnectionHeader());
return connectionHeader;
}
public NodeIdentifier getNodeIdentifier() {
return nodeIdentifier;
}
public URI getUri() {
return nodeIdentifier.getUri();
}
public TopicIdentifier getTopicIdentifier() {
return topicIdentifier;
}
public GraphName getTopicName() {
return topicIdentifier.getName();
}
@Override
public String toString() {
return "SubscriberIdentifier<" + nodeIdentifier + ", " + topicIdentifier + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((nodeIdentifier == null) ? 0 : nodeIdentifier.hashCode());
result = prime * result + ((topicIdentifier == null) ? 0 : topicIdentifier.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SubscriberIdentifier other = (SubscriberIdentifier) obj;
if (nodeIdentifier == null) {
if (other.nodeIdentifier != null)
return false;
} else if (!nodeIdentifier.equals(other.nodeIdentifier))
return false;
if (topicIdentifier == null) {
if (other.topicIdentifier != null)
return false;
} else if (!topicIdentifier.equals(other.topicIdentifier))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.message.MessageDeserializer;
import org.ros.namespace.GraphName;
import org.ros.node.topic.DefaultSubscriberListener;
import org.ros.node.topic.Subscriber;
import java.util.concurrent.ScheduledExecutorService;
/**
* A factory for {@link Subscriber} instances.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class SubscriberFactory {
private final NodeIdentifier nodeIdentifier;
private final TopicParticipantManager topicParticipantManager;
private final ScheduledExecutorService executorService;
private final Object mutex;
public SubscriberFactory(NodeIdentifier nodeIdentifier,
TopicParticipantManager topicParticipantManager, ScheduledExecutorService executorService) {
this.nodeIdentifier = nodeIdentifier;
this.topicParticipantManager = topicParticipantManager;
this.executorService = executorService;
mutex = new Object();
}
/**
* Gets or creates a {@link Subscriber} instance. {@link Subscriber}s are
* cached and reused per topic. When a new {@link Subscriber} is generated, it
* is registered with the master.
*
* @param <T>
* the message type associated with the new {@link Subscriber}
* @param topicDeclaration
* {@link TopicDeclaration} that is subscribed to
* @param messageDeserializer
* the {@link MessageDeserializer} to use for incoming messages
* @return a new or cached {@link Subscriber} instance
*/
@SuppressWarnings("unchecked")
public <T> Subscriber<T> newOrExisting(TopicDeclaration topicDeclaration,
MessageDeserializer<T> messageDeserializer) {
synchronized (mutex) {
GraphName topicName = topicDeclaration.getName();
if (topicParticipantManager.hasSubscriber(topicName)) {
return (DefaultSubscriber<T>) topicParticipantManager.getSubscriber(topicName);
} else {
DefaultSubscriber<T> subscriber =
DefaultSubscriber.newDefault(nodeIdentifier, topicDeclaration, executorService,
messageDeserializer);
subscriber.addSubscriberListener(new DefaultSubscriberListener<T>() {
@Override
public void onNewPublisher(Subscriber<T> subscriber,
PublisherIdentifier publisherIdentifier) {
topicParticipantManager.addSubscriberConnection((DefaultSubscriber<T>) subscriber,
publisherIdentifier);
}
@Override
public void onShutdown(Subscriber<T> subscriber) {
topicParticipantManager.removeSubscriber((DefaultSubscriber<T>) subscriber);
}
});
topicParticipantManager.addSubscriber(subscriber);
return subscriber;
}
}
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import org.ros.namespace.GraphName;
/**
* Represents a ROS topic.
*
* @see <a href="http://www.ros.org/wiki/Topics">Topics documentation</a>
*
* @author damonkohler@google.com (Damon Kohler)
*/
public interface TopicParticipant {
/**
* @return the name of the subscribed topic
*/
GraphName getTopicName();
/**
* @return the message type (e.g. "std_msgs/String")
*/
String getTopicMessageType();
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.topic;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.message.MessageFactory;
import org.ros.message.MessageSerializer;
import org.ros.namespace.GraphName;
import org.ros.node.topic.DefaultPublisherListener;
import org.ros.node.topic.Publisher;
import java.util.concurrent.ScheduledExecutorService;
/**
* A factory for {@link Publisher} instances.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class PublisherFactory {
private final TopicParticipantManager topicParticipantManager;
private final MessageFactory messageFactory;
private final ScheduledExecutorService executorService;
private final NodeIdentifier nodeIdentifier;
private final Object mutex;
public PublisherFactory(NodeIdentifier nodeIdentifier,
TopicParticipantManager topicParticipantManager, MessageFactory messageFactory,
ScheduledExecutorService executorService) {
this.nodeIdentifier = nodeIdentifier;
this.topicParticipantManager = topicParticipantManager;
this.messageFactory = messageFactory;
this.executorService = executorService;
mutex = new Object();
}
/**
* Gets or creates a {@link Publisher} instance. {@link Publisher}s are cached
* and reused per topic. When a new {@link Publisher} is generated, it is
* registered with the master.
*
* @param <T>
* the message type associated with the {@link Publisher}
* @param topicDeclaration
* {@link TopicDeclaration} that is being published
* @param messageSerializer
* the {@link MessageSerializer} used for published messages
* @return a new or cached {@link Publisher} instance
*/
@SuppressWarnings("unchecked")
public <T> Publisher<T> newOrExisting(TopicDeclaration topicDeclaration,
MessageSerializer<T> messageSerializer) {
GraphName topicName = topicDeclaration.getName();
synchronized (mutex) {
if (topicParticipantManager.hasPublisher(topicName)) {
return (DefaultPublisher<T>) topicParticipantManager.getPublisher(topicName);
} else {
DefaultPublisher<T> publisher =
new DefaultPublisher<T>(nodeIdentifier, topicDeclaration, messageSerializer,
messageFactory, executorService);
publisher.addListener(new DefaultPublisherListener<T>() {
@Override
public void onNewSubscriber(Publisher<T> publisher,
SubscriberIdentifier subscriberIdentifier) {
topicParticipantManager.addPublisherConnection((DefaultPublisher<T>) publisher,
subscriberIdentifier);
}
@Override
public void onShutdown(Publisher<T> publisher) {
topicParticipantManager.removePublisher((DefaultPublisher<T>) publisher);
}
});
topicParticipantManager.addPublisher(publisher);
return publisher;
}
}
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
/**
* @author kwc@willowgarage.com (Ken Conley)
*/
public class ObjectResultFactory implements ResultFactory<Object> {
@Override
public Object newFromValue(Object value) {
return value;
}
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class VoidResultFactory implements ResultFactory<Void> {
@Override
public Void newFromValue(Object value) {
return null;
}
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
import com.google.common.collect.Lists;
import org.ros.exception.RemoteException;
import org.ros.exception.RosRuntimeException;
import java.util.List;
/**
* The response from an XML-RPC call.
*
* @author damonkohler@google.com (Damon Kohler)
*
* @param <T>
*/
public class Response<T> {
private final StatusCode statusCode;
private final String statusMessage;
private final T result;
public static <T> Response<T> newError(String message, T value) {
return new Response<T>(StatusCode.ERROR, message, value);
}
public static <T> Response<T> newFailure(String message, T value) {
return new Response<T>(StatusCode.FAILURE, message, value);
}
public static <T> Response<T> newSuccess(String message, T value) {
return new Response<T>(StatusCode.SUCCESS, message, value);
}
/**
* Creates a {@link Response} from the {@link List} of {@link Object}s
* returned from an XML-RPC call. Throws {@link RemoteException} if the
* {@link StatusCode} is StatusCode.FAILURE.
*
* @param <T>
* @param response
* the {@link List} of {@link Object}s returned from the XML-RPC call
* @param resultFactory
* a {@link ResultFactory} that creates a result from the third
* {@link Object} in the {@link Response}
* @return a {@link Response} using the specified {@link ResultFactory} to
* generate the result
* @throws RemoteException
* if the {@link Response}'s {@link StatusCode} indicates
* StatusCode.FAILURE.
*/
public static <T> Response<T> fromListCheckedFailure(List<Object> response,
ResultFactory<T> resultFactory) throws RemoteException {
StatusCode statusCode;
String message;
try {
statusCode = StatusCode.fromInt((Integer) response.get(0));
message = (String) response.get(1);
if (statusCode == StatusCode.FAILURE) {
throw new RemoteException(statusCode, message);
}
} catch (ClassCastException e) {
throw new RosRuntimeException(
"Remote side did not return correct type (status code/message).", e);
}
try {
return new Response<T>(statusCode, message, resultFactory.newFromValue(response.get(2)));
} catch (ClassCastException e) {
throw new RosRuntimeException("Remote side did not return correct value type.", e);
}
}
/**
* Creates a {@link Response} from the {@link List} of {@link Object}s
* returned from an XML-RPC call. Throws {@link RemoteException} if the
* {@link StatusCode} is not a success.
*
* @param <T>
* @param response
* the {@link List} of {@link Object}s returned from the XML-RPC call
* @param resultFactory
* a {@link ResultFactory} that creates a result from the third
* {@link Object} in the {@link Response}
* @return a {@link Response} using the specified {@link ResultFactory} to
* generate the result
* @throws RemoteException
* if the {@link Response}'s {@link StatusCode} does not indicate
* success
*/
public static <T> Response<T> fromListChecked(List<Object> response,
ResultFactory<T> resultFactory) throws RemoteException {
StatusCode statusCode;
String message;
try {
statusCode = StatusCode.fromInt((Integer) response.get(0));
message = (String) response.get(1);
if (statusCode != StatusCode.SUCCESS) {
throw new RemoteException(statusCode, message);
}
} catch (ClassCastException e) {
throw new RosRuntimeException(
"Remote side did not return correct type (status code/message).", e);
}
try {
return new Response<T>(statusCode, message, resultFactory.newFromValue(response.get(2)));
} catch (ClassCastException e) {
throw new RosRuntimeException("Remote side did not return correct value type.", e);
}
}
public Response(int statusCode, String statusMessage, T value) {
this(StatusCode.fromInt(statusCode), statusMessage, value);
}
public Response(StatusCode statusCode, String statusMessage, T value) {
this.statusCode = statusCode;
this.statusMessage = statusMessage;
this.result = value;
}
public List<Object> toList() {
return Lists.newArrayList(statusCode.toInt(), statusMessage, result == null ? "null" : result);
}
public StatusCode getStatusCode() {
return statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
public T getResult() {
return result;
}
@Override
public String toString() {
return "Response<" + statusCode + ", " + statusMessage + ", " + result + ">";
}
public boolean isSuccess() {
return statusCode == StatusCode.SUCCESS;
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides internal classes for representing RPC results.
* <p>
* These classes should _not_ be used directly outside of the org.ros package.
*/
package org.ros.internal.node.response; | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
import java.util.Arrays;
import java.util.List;
import org.ros.address.AdvertiseAddress;
import org.ros.internal.transport.ProtocolDescription;
import org.ros.internal.transport.ProtocolNames;
import org.ros.internal.transport.tcp.TcpRosProtocolDescription;
import com.google.common.base.Preconditions;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ProtocolDescriptionResultFactory implements ResultFactory<ProtocolDescription> {
@Override
public ProtocolDescription newFromValue(Object value) {
List<Object> protocolParameters = Arrays.asList((Object[]) value);
Preconditions.checkState(protocolParameters.size() == 3);
Preconditions.checkState(protocolParameters.get(0).equals(ProtocolNames.TCPROS));
AdvertiseAddress address = new AdvertiseAddress((String) protocolParameters.get(1));
address.setStaticPort((Integer) protocolParameters.get(2));
return new TcpRosProtocolDescription(address);
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.ros.master.client.SystemState;
import org.ros.master.client.TopicSystemState;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* A {@link ResultFactory} to take an object and turn it into a
* {@link SystemState} instance.
*
* @author Keith M. Hughes
*/
public class SystemStateResultFactory implements ResultFactory<SystemState> {
@Override
public SystemState newFromValue(Object value) {
Object[] vals = (Object[]) value;
Map<String, Set<String>> publisherMap = getPublishers(vals[0]);
Map<String, Set<String>> subscriberMap = getSubscribers(vals[1]);
Map<String, TopicSystemState> topics = Maps.newHashMap();
for (Entry<String, Set<String>> publisherData : publisherMap.entrySet()) {
String topicName = publisherData.getKey();
Set<String> subscriberNodes = subscriberMap.remove(topicName);
// Return empty lists if no subscribers
if (subscriberNodes == null) {
subscriberNodes = Sets.newHashSet();
}
topics.put(topicName,
new TopicSystemState(topicName, publisherData.getValue(),
subscriberNodes));
}
for (Entry<String, Set<String>> subscriberData : subscriberMap
.entrySet()) {
// At this point there are no publishers with the same topic name
HashSet<String> noPublishers = Sets.newHashSet();
String topicName = subscriberData.getKey();
topics.put(topicName, new TopicSystemState(topicName,
noPublishers, subscriberData.getValue()));
}
// TODO(keith): Get service state in here.
return new SystemState(topics.values());
}
/**
* Extract out the publisher data.
*
* @param pubPairs
* the list of lists containing both a topic name and a list of
* publisher nodes for that topic
*
* @return a mapping from topic name to the set of publishers for that topic
*/
private Map<String, Set<String>> getPublishers(Object pubPairs) {
Map<String, Set<String>> topicToPublishers = Maps.newHashMap();
for (Object topicData : Arrays.asList((Object[]) pubPairs)) {
String topicName = (String) ((Object[]) topicData)[0];
Set<String> publishers =Sets.newHashSet();
Object[] publisherData = (Object[])((Object[]) topicData)[1];
for (Object publisher : publisherData) {
publishers.add(publisher.toString());
}
topicToPublishers.put(topicName, publishers);
}
return topicToPublishers;
}
/**
* Extract out the subscriber data.
*
* @param subPairs
* the list of lists containing both a topic name and a list of
* subscriber nodes for that topic
*
* @return a mapping from topic name to the set of subscribers for that
* topic
*/
private Map<String, Set<String>> getSubscribers(Object subPairs) {
Map<String, Set<String>> topicToSubscribers = Maps.newHashMap();
for (Object topicData : Arrays.asList((Object[]) subPairs)) {
String topicName = (String) ((Object[]) topicData)[0];
Set<String> subscribers =Sets.newHashSet();
Object[] subscriberData = (Object[])((Object[]) topicData)[1];
for (Object subscriber : subscriberData) {
subscribers.add(subscriber.toString());
}
topicToSubscribers.put(topicName, subscribers);
}
return topicToSubscribers;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
public enum StatusCode {
ERROR(-1), FAILURE(0), SUCCESS(1);
private final int intValue;
private StatusCode(int value) {
this.intValue = value;
}
public int toInt() {
return intValue;
}
public static StatusCode fromInt(int intValue) {
switch (intValue) {
case -1:
return ERROR;
case 1:
return SUCCESS;
case 0:
default:
return FAILURE;
}
}
@Override
public String toString() {
switch (this) {
case ERROR:
return "Error";
case SUCCESS:
return "Success";
case FAILURE:
default:
return "Failure";
}
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class StringResultFactory implements ResultFactory<String> {
@Override
public String newFromValue(Object value) {
return (String) value;
}
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
/**
* @author kwc@willowgarage.com (Ken Conley)
*/
public class BooleanResultFactory implements ResultFactory<Boolean> {
@Override
public Boolean newFromValue(Object value) {
return (Boolean) value;
}
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
import com.google.common.collect.Lists;
import org.ros.internal.message.topic.TopicDescription;
import org.ros.internal.node.topic.TopicDeclaration;
import org.ros.namespace.GraphName;
import java.util.Arrays;
import java.util.List;
/**
* A {@link ResultFactory} to take an object and turn it into a list of
* {@link TopicDeclaration} instances.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class TopicListResultFactory implements ResultFactory<List<TopicDeclaration>> {
@Override
public List<TopicDeclaration> newFromValue(Object value) {
List<TopicDeclaration> descriptions = Lists.newArrayList();
List<Object> topics = Arrays.asList((Object[]) value);
for (Object topic : topics) {
String name = (String) ((Object[]) topic)[0];
String type = (String) ((Object[]) topic)[1];
descriptions.add(TopicDeclaration.newFromTopicName(GraphName.of(name), new TopicDescription(type, null,
null)));
}
return descriptions;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class IntegerResultFactory implements ResultFactory<Integer> {
@Override
public Integer newFromValue(Object value) {
return (Integer) value;
}
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
import java.util.Arrays;
import java.util.List;
import com.google.common.collect.Lists;
/**
* @author kwc@willowgarage.com (Ken Conley)
*/
public class StringListResultFactory implements ResultFactory<List<String>> {
@Override
public List<String> newFromValue(Object value) {
List<String> strings = Lists.newArrayList();
List<Object> objects = Arrays.asList((Object[]) value);
for (Object topic : objects) {
strings.add((String) topic);
}
return strings;
}
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import org.ros.exception.RosRuntimeException;
import com.google.common.collect.Lists;
/**
* A {@link ResultFactory} to take an object and turn it into a list of URLIs.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class UriListResultFactory implements ResultFactory<List<URI>> {
@Override
public List<URI> newFromValue(Object value) {
List<Object> values = Arrays.asList((Object[]) value);
List<URI> uris = Lists.newArrayList();
for (Object uri : values) {
try {
uris.add(new URI((String) uri));
} catch (URISyntaxException e) {
throw new RosRuntimeException(e);
}
}
return uris;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
/**
* @author damonkohler@google.com (Damon Kohler)
*
* @param <T>
* the result type
*/
public interface ResultFactory<T> {
/**
* @param value
* @return a value to be returned as the result part of a {@link Response}
*/
public T newFromValue(Object value);
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
import java.net.URI;
import java.net.URISyntaxException;
import org.ros.exception.RosRuntimeException;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class UriResultFactory implements ResultFactory<URI> {
@Override
public URI newFromValue(Object value) {
try {
return new URI((String) value);
} catch (URISyntaxException e) {
throw new RosRuntimeException(e);
}
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.response;
import java.util.List;
import org.ros.master.client.TopicType;
import com.google.common.collect.Lists;
/**
* A {@link ResultFactory} to take an object and turn it into a list of
* {@link TopicType} instances.
*
* @author Keith M. Hughes
*/
public class TopicTypeListResultFactory implements
ResultFactory<List<TopicType>> {
@Override
public List<TopicType> newFromValue(Object value) {
List<TopicType> topics = Lists.newArrayList();
for (Object pair : (Object[]) value) {
topics.add(new TopicType((String) ((Object[]) pair)[0],
(String) ((Object[]) pair)[1]));
}
return topics;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server;
import com.google.common.collect.Lists;
import org.ros.address.AdvertiseAddress;
import org.ros.address.BindAddress;
import org.ros.internal.node.client.MasterClient;
import org.ros.internal.node.parameter.ParameterManager;
import org.ros.internal.node.service.ServiceManager;
import org.ros.internal.node.topic.DefaultPublisher;
import org.ros.internal.node.topic.DefaultSubscriber;
import org.ros.internal.node.topic.PublisherIdentifier;
import org.ros.internal.node.topic.SubscriberIdentifier;
import org.ros.internal.node.topic.TopicDeclaration;
import org.ros.internal.node.topic.TopicParticipantManager;
import org.ros.internal.node.xmlrpc.SlaveXmlRpcEndpointImpl;
import org.ros.internal.system.Process;
import org.ros.internal.transport.ProtocolDescription;
import org.ros.internal.transport.ProtocolNames;
import org.ros.internal.transport.tcp.TcpRosProtocolDescription;
import org.ros.internal.transport.tcp.TcpRosServer;
import org.ros.namespace.GraphName;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class SlaveServer extends XmlRpcServer {
private final GraphName nodeName;
private final MasterClient masterClient;
private final TopicParticipantManager topicParticipantManager;
private final ParameterManager parameterManager;
private final TcpRosServer tcpRosServer;
public SlaveServer(GraphName nodeName, BindAddress tcpRosBindAddress,
AdvertiseAddress tcpRosAdvertiseAddress, BindAddress xmlRpcBindAddress,
AdvertiseAddress xmlRpcAdvertiseAddress, MasterClient master,
TopicParticipantManager topicParticipantManager, ServiceManager serviceManager,
ParameterManager parameterManager, ScheduledExecutorService executorService) {
super(xmlRpcBindAddress, xmlRpcAdvertiseAddress);
this.nodeName = nodeName;
this.masterClient = master;
this.topicParticipantManager = topicParticipantManager;
this.parameterManager = parameterManager;
this.tcpRosServer =
new TcpRosServer(tcpRosBindAddress, tcpRosAdvertiseAddress, topicParticipantManager,
serviceManager, executorService);
}
public AdvertiseAddress getTcpRosAdvertiseAddress() {
return tcpRosServer.getAdvertiseAddress();
}
/**
* Start the XML-RPC server. This start() routine requires that the
* {@link TcpRosServer} is initialized first so that the slave server returns
* correct information when topics are requested.
*/
public void start() {
super.start(org.ros.internal.node.xmlrpc.SlaveXmlRpcEndpointImpl.class,
new SlaveXmlRpcEndpointImpl(this));
tcpRosServer.start();
}
// TODO(damonkohler): This should also shut down the Node.
@Override
public void shutdown() {
super.shutdown();
tcpRosServer.shutdown();
}
public List<Object> getBusStats(String callerId) {
throw new UnsupportedOperationException();
}
public List<Object> getBusInfo(String callerId) {
List<Object> busInfo = Lists.newArrayList();
// The connection ID field is opaque to the user. A monotonically increasing
// integer for now is sufficient.
int id = 0;
for (DefaultPublisher<?> publisher : getPublications()) {
for (SubscriberIdentifier subscriberIdentifier : topicParticipantManager
.getPublisherConnections(publisher)) {
List<String> publisherBusInfo = Lists.newArrayList();
publisherBusInfo.add(Integer.toString(id));
publisherBusInfo.add(subscriberIdentifier.getNodeIdentifier().getName().toString());
// TODO(damonkohler): Pull out BusInfo constants.
publisherBusInfo.add("o");
// TODO(damonkohler): Add getter for protocol to topic participants.
publisherBusInfo.add(ProtocolNames.TCPROS);
publisherBusInfo.add(publisher.getTopicName().toString());
busInfo.add(publisherBusInfo);
id++;
}
}
for (DefaultSubscriber<?> subscriber : getSubscriptions()) {
for (PublisherIdentifier publisherIdentifer : topicParticipantManager
.getSubscriberConnections(subscriber)) {
List<String> subscriberBusInfo = Lists.newArrayList();
subscriberBusInfo.add(Integer.toString(id));
// Subscriber connection PublisherIdentifiers are populated with node
// URIs instead of names. As a result, the only identifier information
// available is the URI.
subscriberBusInfo.add(publisherIdentifer.getNodeIdentifier().getUri().toString());
// TODO(damonkohler): Pull out BusInfo constants.
subscriberBusInfo.add("i");
// TODO(damonkohler): Add getter for protocol to topic participants.
subscriberBusInfo.add(ProtocolNames.TCPROS);
subscriberBusInfo.add(publisherIdentifer.getTopicName().toString());
busInfo.add(subscriberBusInfo);
id++;
}
}
return busInfo;
}
public URI getMasterUri() {
return masterClient.getRemoteUri();
}
/**
* @return PID of this process if available, throws
* {@link UnsupportedOperationException} otherwise.
*/
@Override
public int getPid() {
return Process.getPid();
}
public Collection<DefaultSubscriber<?>> getSubscriptions() {
return topicParticipantManager.getSubscribers();
}
public Collection<DefaultPublisher<?>> getPublications() {
return topicParticipantManager.getPublishers();
}
/**
* @param parameterName
* @param parameterValue
* @return the number of parameter subscribers that received the update
*/
public int paramUpdate(GraphName parameterName, Object parameterValue) {
return parameterManager.updateParameter(parameterName, parameterValue);
}
public void publisherUpdate(String callerId, String topicName, Collection<URI> publisherUris) {
GraphName graphName = GraphName.of(topicName);
if (topicParticipantManager.hasSubscriber(graphName)) {
DefaultSubscriber<?> subscriber = topicParticipantManager.getSubscriber(graphName);
TopicDeclaration topicDeclaration = subscriber.getTopicDeclaration();
Collection<PublisherIdentifier> identifiers =
PublisherIdentifier.newCollectionFromUris(publisherUris, topicDeclaration);
subscriber.updatePublishers(identifiers);
}
}
public ProtocolDescription requestTopic(String topicName, Collection<String> protocols)
throws ServerException {
// TODO(damonkohler): Use NameResolver.
// Canonicalize topic name.
GraphName graphName = GraphName.of(topicName).toGlobal();
if (!topicParticipantManager.hasPublisher(graphName)) {
throw new ServerException("No publishers for topic: " + graphName);
}
for (String protocol : protocols) {
if (protocol.equals(ProtocolNames.TCPROS)) {
try {
return new TcpRosProtocolDescription(tcpRosServer.getAdvertiseAddress());
} catch (Exception e) {
throw new ServerException(e);
}
}
}
throw new ServerException("No supported protocols specified.");
}
/**
* @return a {@link NodeIdentifier} for this {@link SlaveServer}
*/
public NodeIdentifier toNodeIdentifier() {
return new NodeIdentifier(nodeName, getUri());
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides internal classes for servers.
* <p>
* These classes should _not_ be used directly outside of the org.ros package.
*/
package org.ros.internal.node.server; | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server;
import com.google.common.base.Preconditions;
import org.ros.exception.RosRuntimeException;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.internal.transport.ConnectionHeaderFields;
import org.ros.namespace.GraphName;
import org.ros.node.Node;
import java.net.URI;
import java.net.URISyntaxException;
/**
* A node slave identifier which combines the node name of a node with the URI
* for contacting the node's XMLRPC server.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class NodeIdentifier {
private final GraphName name;
private final URI uri;
public static NodeIdentifier forName(String name) {
return new NodeIdentifier(GraphName.of(name), null);
}
public static NodeIdentifier forUri(String uri) {
try {
return new NodeIdentifier(null, new URI(uri));
} catch (URISyntaxException e) {
throw new RosRuntimeException(e);
}
}
public static NodeIdentifier forNameAndUri(String name, String uri) {
try {
return new NodeIdentifier(GraphName.of(name), new URI(uri));
} catch (URISyntaxException e) {
throw new RosRuntimeException(e);
}
}
/**
* Constructs a new {@link NodeIdentifier}.
*
* Note that either {@code nodeName} or {@code uri} may be null but not both.
* This is necessary because either is enough to uniquely identify a
* {@link SlaveServer} and because, depending on context, one or the other may
* not be available.
*
* Although either value may be {@code null}, we do not treat {@code null} as
* a wildcard with respect to equality. Even though it should be safe to do
* so, wildcards are unnecessary in this case and would likely lead to buggy
* code.
*
* @param name
* the {@link GraphName} that the {@link Node} is known as
* @param uri
* the {@link URI} of the {@link Node}'s {@link SlaveServer} XML-RPC server
*/
public NodeIdentifier(GraphName name, URI uri) {
Preconditions.checkArgument(name != null || uri != null);
if (name != null) {
Preconditions.checkArgument(name.isGlobal());
}
this.name = name;
this.uri = uri;
}
public GraphName getName() {
return name;
}
public URI getUri() {
return uri;
}
public ConnectionHeader toConnectionHeader() {
ConnectionHeader connectionHeader = new ConnectionHeader();
connectionHeader.addField(ConnectionHeaderFields.CALLER_ID, name.toString());
return connectionHeader;
}
@Override
public String toString() {
return "NodeIdentifier<" + name + ", " + uri + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((uri == null) ? 0 : uri.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NodeIdentifier other = (NodeIdentifier) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (uri == null) {
if (other.uri != null)
return false;
} else if (!uri.equals(other.uri))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.server.RequestProcessorFactoryFactory;
/**
* @author damonkohler@google.com (Damon Kohler)
*
* @param <T>
*/
class NodeRequestProcessorFactoryFactory<T extends org.ros.internal.node.xmlrpc.XmlRpcEndpoint>
implements RequestProcessorFactoryFactory {
private final RequestProcessorFactory factory = new NodeRequestProcessorFactory();
private final T node;
public NodeRequestProcessorFactoryFactory(T instance) {
this.node = instance;
}
@SuppressWarnings("rawtypes")
@Override
public RequestProcessorFactory getRequestProcessorFactory(Class unused) {
return factory;
}
private class NodeRequestProcessorFactory implements RequestProcessorFactory {
@Override
public Object getRequestProcessor(XmlRpcRequest xmlRpcRequest) {
return node;
}
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.server.PropertyHandlerMapping;
import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;
import org.apache.xmlrpc.webserver.WebServer;
import org.ros.address.AdvertiseAddress;
import org.ros.address.BindAddress;
import org.ros.exception.RosRuntimeException;
import org.ros.internal.system.Process;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Base class for an XML-RPC server.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class XmlRpcServer {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(XmlRpcServer.class);
private final WebServer server;
private final AdvertiseAddress advertiseAddress;
private final CountDownLatch startLatch;
public XmlRpcServer(BindAddress bindAddress, AdvertiseAddress advertiseAddress) {
InetSocketAddress address = bindAddress.toInetSocketAddress();
server = new WebServer(address.getPort(), address.getAddress());
this.advertiseAddress = advertiseAddress;
this.advertiseAddress.setPortCallable(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return server.getPort();
}
});
startLatch = new CountDownLatch(1);
}
/**
* Start up the remote calling server.
*
* @param instanceClass
* the class of the remoting server
*
* @param instance
* an instance of the remoting server class
*/
public <T extends org.ros.internal.node.xmlrpc.XmlRpcEndpoint> void start(Class<T> instanceClass,
T instance) {
org.apache.xmlrpc.server.XmlRpcServer xmlRpcServer = server.getXmlRpcServer();
PropertyHandlerMapping phm = new PropertyHandlerMapping();
phm.setRequestProcessorFactoryFactory(new NodeRequestProcessorFactoryFactory<T>(instance));
try {
phm.addHandler("", instanceClass);
} catch (XmlRpcException e) {
throw new RosRuntimeException(e);
}
xmlRpcServer.setHandlerMapping(phm);
XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig();
serverConfig.setEnabledForExtensions(false);
serverConfig.setContentLengthOptional(false);
try {
server.start();
} catch (IOException e) {
throw new RosRuntimeException(e);
}
if (DEBUG) {
log.info("Bound to: " + getUri());
}
startLatch.countDown();
}
/**
* Shut the remote call server down.
*/
public void shutdown() {
server.shutdown();
}
/**
* @return the {@link URI} of the server
*/
public URI getUri() {
return advertiseAddress.toUri("http");
}
public InetSocketAddress getAddress() {
return advertiseAddress.toInetSocketAddress();
}
public AdvertiseAddress getAdvertiseAddress() {
return advertiseAddress;
}
public void awaitStart() throws InterruptedException {
startLatch.await();
}
public boolean awaitStart(long timeout, TimeUnit unit) throws InterruptedException {
return startLatch.await(timeout, unit);
}
/**
* @return PID of node process if available, throws
* {@link UnsupportedOperationException} otherwise.
*/
public int getPid() {
return Process.getPid();
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServerException extends Exception {
private static final long serialVersionUID = 1L;
public ServerException(String message) {
super(message);
}
/**
* @param e the wrapped {@link Exception}
*/
public ServerException(Exception e) {
super(e);
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides internal classes for the server side of the master.
* <p>
* These classes should _not_ be used directly outside of the org.ros package.
*/
package org.ros.internal.node.server.master; | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server.master;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ros.address.AdvertiseAddress;
import org.ros.address.BindAddress;
import org.ros.internal.node.client.SlaveClient;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.internal.node.server.SlaveServer;
import org.ros.internal.node.server.XmlRpcServer;
import org.ros.internal.node.topic.TopicParticipant;
import org.ros.internal.node.xmlrpc.MasterXmlRpcEndpointImpl;
import org.ros.master.client.TopicSystemState;
import org.ros.namespace.GraphName;
import org.ros.node.Node;
import org.ros.node.service.ServiceServer;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
import java.net.URI;
import java.util.Collection;
import java.util.List;
/**
* The {@link MasterServer} provides naming and registration services to the
* rest of the {@link Node}s in the ROS system. It tracks {@link Publisher}s and
* {@link Subscriber}s to {@link TopicSystemState}s as well as
* {@link ServiceServer}s. The role of the {@link MasterServer} is to enable
* individual ROS {@link Node}s to locate one another. Once these {@link Node}s
* have located each other they communicate with each other peer-to-peer.
*
* @see <a href="http://www.ros.org/wiki/Master">Master documentation</a>
*
* @author damonkohler@google.com (Damon Kohler)
* @author khughes@google.com (Keith M. Hughes)
*/
public class MasterServer extends XmlRpcServer implements MasterRegistrationListener {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(MasterServer.class);
/**
* Position in the {@link #getSystemState()} for publisher information.
*/
public static final int SYSTEM_STATE_PUBLISHERS = 0;
/**
* Position in the {@link #getSystemState()} for subscriber information.
*/
public static final int SYSTEM_STATE_SUBSCRIBERS = 1;
/**
* Position in the {@link #getSystemState()} for service information.
*/
public static final int SYSTEM_STATE_SERVICES = 2;
/**
* The node name (i.e. the callerId XML-RPC field) used when the
* {@link MasterServer} contacts a {@link SlaveServer}.
*/
private static final GraphName MASTER_NODE_NAME = GraphName.of("/master");
/**
* The manager for handling master registration information.
*/
private final MasterRegistrationManagerImpl masterRegistrationManager;
public MasterServer(BindAddress bindAddress, AdvertiseAddress advertiseAddress) {
super(bindAddress, advertiseAddress);
masterRegistrationManager = new MasterRegistrationManagerImpl(this);
}
/**
* Start the {@link MasterServer}.
*/
public void start() {
if (DEBUG) {
log.info("Starting master server.");
}
super.start(MasterXmlRpcEndpointImpl.class, new MasterXmlRpcEndpointImpl(this));
}
/**
* Register a service with the master.
*
* @param nodeName
* the {@link GraphName} of the {@link Node} offering the service
* @param nodeSlaveUri
* the {@link URI} of the {@link Node}'s {@link SlaveServer}
* @param serviceName
* the {@link GraphName} of the service
* @param serviceUri
* the {@link URI} of the service
*/
public void registerService(GraphName nodeName, URI nodeSlaveUri, GraphName serviceName,
URI serviceUri) {
synchronized (masterRegistrationManager) {
masterRegistrationManager.registerService(nodeName, nodeSlaveUri, serviceName, serviceUri);
}
}
/**
* Unregister a service from the master.
*
* @param nodeName
* the {@link GraphName} of the {@link Node} offering the service
* @param serviceName
* the {@link GraphName} of the service
* @param serviceUri
* the {@link URI} of the service
* @return {@code true} if the service was registered
*/
public boolean unregisterService(GraphName nodeName, GraphName serviceName, URI serviceUri) {
synchronized (masterRegistrationManager) {
return masterRegistrationManager.unregisterService(nodeName, serviceName, serviceUri);
}
}
/**
* Subscribe the caller to the specified topic. In addition to receiving a
* list of current publishers, the subscriber will also receive notifications
* of new publishers via the publisherUpdate API.
*
* @param nodeName
* the {@link GraphName} of the {@link Node} offering the service
* @param nodeSlaveUri
* the {@link URI} of the {@link Node}'s {@link SlaveServer}
* @param topicName
* the {@link GraphName} of the subscribed {@link TopicParticipant}
* @param topicMessageType
* the message type of the topic
* @return A {@link List} of XMLRPC API {@link URI}s for nodes currently
* publishing the specified topic
*/
public List<URI> registerSubscriber(GraphName nodeName, URI nodeSlaveUri, GraphName topicName,
String topicMessageType) {
if (DEBUG) {
log.info(String.format(
"Registering subscriber %s with message type %s on node %s with URI %s", topicName,
topicMessageType, nodeName, nodeSlaveUri));
}
synchronized (masterRegistrationManager) {
TopicRegistrationInfo topicInfo =
masterRegistrationManager.registerSubscriber(nodeName, nodeSlaveUri, topicName,
topicMessageType);
List<URI> publisherUris = Lists.newArrayList();
for (NodeRegistrationInfo publisherNodeInfo : topicInfo.getPublishers()) {
publisherUris.add(publisherNodeInfo.getNodeSlaveUri());
}
return publisherUris;
}
}
/**
* Unregister a {@link Subscriber}.
*
* @param nodeName
* the {@link GraphName} of the {@link Node} offering the service
* @param topicName
* the {@link GraphName} of the subscribed {@link TopicParticipant}
* @return {@code true} if the {@link Subscriber} was registered
*/
public boolean unregisterSubscriber(GraphName nodeName, GraphName topicName) {
if (DEBUG) {
log.info(String.format("Unregistering subscriber for %s on node %s.", topicName, nodeName));
}
synchronized (masterRegistrationManager) {
return masterRegistrationManager.unregisterSubscriber(nodeName, topicName);
}
}
/**
* Register the caller as a {@link Publisher} of the specified topic.
*
* @param nodeName
* the {@link GraphName} of the {@link Node} offering the service
* @param nodeSlaveUri
* the {@link URI} of the {@link Node}'s {@link SlaveServer}
* @param topicName
* the {@link GraphName} of the subscribed {@link TopicParticipant}
* @param topicMessageType
* the message type of the topic
* @return a {@link List} of the current {@link Subscriber}s to the
* {@link Publisher}'s {@link TopicSystemState} in the form of XML-RPC
* {@link URI}s for each {@link Subscriber}'s {@link SlaveServer}
*/
public List<URI> registerPublisher(GraphName nodeName, URI nodeSlaveUri, GraphName topicName,
String topicMessageType) {
if (DEBUG) {
log.info(String.format(
"Registering publisher %s with message type %s on node %s with URI %s.", topicName,
topicMessageType, nodeName, nodeSlaveUri));
}
synchronized (masterRegistrationManager) {
TopicRegistrationInfo topicInfo =
masterRegistrationManager.registerPublisher(nodeName, nodeSlaveUri, topicName,
topicMessageType);
List<URI> subscriberSlaveUris = Lists.newArrayList();
for (NodeRegistrationInfo publisherNodeInfo : topicInfo.getSubscribers()) {
subscriberSlaveUris.add(publisherNodeInfo.getNodeSlaveUri());
}
publisherUpdate(topicInfo, subscriberSlaveUris);
return subscriberSlaveUris;
}
}
/**
* Something has happened to the publishers for a topic. Tell every subscriber
* about the current set of publishers.
*
* @param topicInfo
* the topic information for the update
* @param subscriberSlaveUris
* IRIs for all subscribers
*/
private void publisherUpdate(TopicRegistrationInfo topicInfo, List<URI> subscriberSlaveUris) {
if (DEBUG) {
log.info("Publisher update: " + topicInfo.getTopicName());
}
List<URI> publisherUris = Lists.newArrayList();
for (NodeRegistrationInfo publisherNodeInfo : topicInfo.getPublishers()) {
publisherUris.add(publisherNodeInfo.getNodeSlaveUri());
}
GraphName topicName = topicInfo.getTopicName();
for (URI subscriberSlaveUri : subscriberSlaveUris) {
contactSubscriberForPublisherUpdate(subscriberSlaveUri, topicName, publisherUris);
}
}
/**
* Contact a subscriber and send it a publisher update.
*
* @param subscriberSlaveUri
* the slave URI of the subscriber to contact
* @param topicName
* the name of the topic whose publisher URIs are being updated
* @param publisherUris
* the new list of publisher URIs to be sent to the subscriber
*/
@VisibleForTesting
protected void contactSubscriberForPublisherUpdate(URI subscriberSlaveUri, GraphName topicName,
List<URI> publisherUris) {
SlaveClient client = new SlaveClient(MASTER_NODE_NAME, subscriberSlaveUri);
client.publisherUpdate(topicName, publisherUris);
}
/**
* Unregister a {@link Publisher}.
*
* @param nodeName
* the {@link GraphName} of the {@link Node} offering the service
* @param topicName
* the {@link GraphName} of the subscribed {@link TopicParticipant}
* @return {@code true} if the {@link Publisher} was unregistered
*/
public boolean unregisterPublisher(GraphName nodeName, GraphName topicName) {
if (DEBUG) {
log.info(String.format("Unregistering publisher for %s on %s.", topicName, nodeName));
}
synchronized (masterRegistrationManager) {
return masterRegistrationManager.unregisterPublisher(nodeName, topicName);
}
}
/**
* Returns a {@link NodeIdentifier} for the {@link Node} with the given name.
* This API is for looking information about {@link Publisher}s and
* {@link Subscriber}s. Use {@link #lookupService(GraphName)} instead to
* lookup ROS-RPC {@link URI}s for {@link ServiceServer}s.
*
* @param nodeName
* name of {@link Node} to lookup
* @return the {@link URI} for the {@link Node} slave server with the given
* name, or {@code null} if there is no {@link Node} with the given
* name
*/
public URI lookupNode(GraphName nodeName) {
synchronized (masterRegistrationManager) {
NodeRegistrationInfo node = masterRegistrationManager.getNodeRegistrationInfo(nodeName);
if (node != null) {
return node.getNodeSlaveUri();
} else {
return null;
}
}
}
/**
* Get a {@link List} of all {@link TopicSystemState} message types.
*
* @param calledId
* the {@link Node} name of the caller
* @return a list of the form [[topic 1 name, topic 1 message type], [topic 2
* name, topic 2 message type], ...]
*/
public List<List<String>> getTopicTypes(GraphName calledId) {
synchronized (masterRegistrationManager) {
List<List<String>> result = Lists.newArrayList();
for (TopicRegistrationInfo topic : masterRegistrationManager.getAllTopics()) {
result.add(Lists.newArrayList(topic.getTopicName().toString(), topic.getMessageType()));
}
return result;
}
}
/**
* Get the state of the ROS graph.
*
* <p>
* This includes information about publishers, subscribers, and services.
*
* @return TODO(keith): Fill in.
*/
public List<Object> getSystemState() {
synchronized (masterRegistrationManager) {
List<Object> result = Lists.newArrayList();
Collection<TopicRegistrationInfo> topics = masterRegistrationManager.getAllTopics();
result.add(getSystemStatePublishers(topics));
result.add(getSystemStateSubscribers(topics));
result.add(getSystemStateServices());
return result;
}
}
/**
* Get the system state for {@link Publisher}s.
*
* @param topics
* all topics known by the master
*
* @return a {@link List} of the form [ [topic1,
* [topic1Publisher1...topic1PublisherN]] ... ] where the
* topicPublisherI instances are {@link Node} names
*/
private List<Object> getSystemStatePublishers(Collection<TopicRegistrationInfo> topics) {
List<Object> result = Lists.newArrayList();
for (TopicRegistrationInfo topic : topics) {
if (topic.hasPublishers()) {
List<Object> topicInfo = Lists.newArrayList();
topicInfo.add(topic.getTopicName().toString());
List<String> publist = Lists.newArrayList();
for (NodeRegistrationInfo node : topic.getPublishers()) {
publist.add(node.getNodeName().toString());
}
topicInfo.add(publist);
result.add(topicInfo);
}
}
return result;
}
/**
* Get the system state for {@link Subscriber}s.
*
* @param topics
* all topics known by the master
*
* @return a {@link List} of the form [ [topic1,
* [topic1Subscriber1...topic1SubscriberN]] ... ] where the
* topicSubscriberI instances are {@link Node} names
*/
private List<Object> getSystemStateSubscribers(Collection<TopicRegistrationInfo> topics) {
List<Object> result = Lists.newArrayList();
for (TopicRegistrationInfo topic : topics) {
if (topic.hasSubscribers()) {
List<Object> topicInfo = Lists.newArrayList();
topicInfo.add(topic.getTopicName().toString());
List<Object> sublist = Lists.newArrayList();
for (NodeRegistrationInfo node : topic.getSubscribers()) {
sublist.add(node.getNodeName().toString());
}
topicInfo.add(sublist);
result.add(topicInfo);
}
}
return result;
}
/**
* Get the system state for {@link ServiceServer}s.
*
* @return a {@link List} of the form [ [service1,
* [serviceProvider1...serviceProviderN]] ... ] where the
* serviceProviderI instances are {@link Node} names
*/
private List<Object> getSystemStateServices() {
List<Object> result = Lists.newArrayList();
for (ServiceRegistrationInfo service : masterRegistrationManager.getAllServices()) {
List<Object> topicInfo = Lists.newArrayList();
topicInfo.add(service.getServiceName().toString());
topicInfo.add(Lists.newArrayList(service.getServiceName().toString()));
result.add(topicInfo);
}
return result;
}
/**
* Lookup the provider of a particular service.
*
* @param serviceName
* name of service
* @return {@link URI} of the {@link SlaveServer} with the provided name, or
* {@code null} if there is no such service.
*/
public URI lookupService(GraphName serviceName) {
synchronized (masterRegistrationManager) {
ServiceRegistrationInfo service =
masterRegistrationManager.getServiceRegistrationInfo(serviceName);
if (service != null) {
return service.getServiceUri();
} else {
return null;
}
}
}
/**
* Get a list of all topics published for the give subgraph.
*
* @param caller
* name of the caller
* @param subgraph
* subgraph containing the requested {@link TopicSystemState}s,
* relative to caller
* @return a {@link List} of {@link List}s where the nested {@link List}s
* contain, in order, the {@link TopicSystemState} name and
* {@link TopicSystemState} message type
*/
public List<Object> getPublishedTopics(GraphName caller, GraphName subgraph) {
synchronized (masterRegistrationManager) {
// TODO(keith): Filter topics according to subgraph.
List<Object> result = Lists.newArrayList();
for (TopicRegistrationInfo topic : masterRegistrationManager.getAllTopics()) {
if (topic.hasPublishers()) {
result.add(Lists.newArrayList(topic.getTopicName().toString(), topic.getMessageType()));
}
}
return result;
}
}
@Override
public void onNodeReplacement(NodeRegistrationInfo nodeInfo) {
// A node in the registration manager is being replaced. Contact the node
// and tell it to shut down.
if (log.isWarnEnabled()) {
log.warn(String.format("Existing node %s with slave URI %s will be shutdown.",
nodeInfo.getNodeName(), nodeInfo.getNodeSlaveUri()));
}
SlaveClient client = new SlaveClient(MASTER_NODE_NAME, nodeInfo.getNodeSlaveUri());
client.shutdown("Replaced by new slave");
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server.master;
import org.ros.namespace.GraphName;
import java.net.URI;
/**
* Information a master needs about a service.
*
* @author khughes@google.com (Keith M. Hughes)
*/
public class ServiceRegistrationInfo {
/**
* Name of the service.
*/
private final GraphName serviceName;
/**
* The URI for the service server.
*/
private final URI serviceUri;
/**
* Node which is serving up the service.
*/
private final NodeRegistrationInfo node;
public ServiceRegistrationInfo(GraphName serviceName, URI serviceUri, NodeRegistrationInfo node) {
this.serviceName = serviceName;
this.serviceUri = serviceUri;
this.node = node;
}
/**
* Get the name of the service.
*
* @return the serviceName
*/
public GraphName getServiceName() {
return serviceName;
}
/**
* Get the URI of the service server.
*
* @return the service URI
*/
public URI getServiceUri() {
return serviceUri;
}
/**
* Get the information about the node which contains the service.
*
* @return The implementing node's information.
*/
public NodeRegistrationInfo getNode() {
return node;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + serviceName.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ServiceRegistrationInfo other = (ServiceRegistrationInfo) obj;
if (!serviceName.equals(other.serviceName))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server.master;
/**
* Listen for master registration events from the
* {@link MasterRegistrationManagerImpl}.
*
* @author khughes@google.com (Keith M. Hughes)
*/
public interface MasterRegistrationListener {
/**
* A node is being replaced.
*
* <p>
* The information object is about to be trashed, so it should not be hung
* onto.
*
* @param nodeInfo
* the node being replaced
*/
void onNodeReplacement(NodeRegistrationInfo nodeInfo);
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server.master;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ros.internal.node.service.ServiceIdentifier;
import org.ros.master.client.TopicSystemState;
import org.ros.namespace.GraphName;
import org.ros.node.service.ServiceServer;
import com.google.common.collect.Maps;
/**
* Manages all registration logic for the {@link MasterServer}.
*
* <p>
* This class is not thread-safe.
*
* @author khughes@google.com (Keith M. Hughes)
*/
public class MasterRegistrationManagerImpl {
private static final Log log = LogFactory.getLog(MasterRegistrationManagerImpl.class);
/**
* A map from node names to the information about the mode.
*/
private final Map<GraphName, NodeRegistrationInfo> nodes;
/**
* A {@link Map} from the name of the {@link ServiceServer} to the
* {@link ServiceIdentifier}.
*/
private final Map<GraphName, ServiceRegistrationInfo> services;
/**
* A {@link Map} from {@link TopicSystemState} name to the {@link TopicRegistrationInfo}
* about the topic.
*/
private final Map<GraphName, TopicRegistrationInfo> topics;
/**
* A listener for master registration events.
*/
private final MasterRegistrationListener listener;
public MasterRegistrationManagerImpl(MasterRegistrationListener listener) {
this.listener = listener;
nodes = Maps.newHashMap();
services = Maps.newConcurrentMap();
topics = Maps.newHashMap();
}
/**
* Register a publisher.
*
* @param nodeName
* name of the node with the publisher
* @param nodeSlaveUri
* URI of the slave server on the node
* @param topicName
* then name of the topic
* @param topicMessageType
* message type of the topic
*
* @return The registration information for the topic.
*/
public TopicRegistrationInfo registerPublisher(GraphName nodeName, URI nodeSlaveUri,
GraphName topicName, String topicMessageType) {
if (log.isDebugEnabled()) {
log.debug(String.format(
"Registering publisher topic %s with message type %s on node %s with slave URI %s",
topicName, topicMessageType, nodeName, nodeSlaveUri));
}
TopicRegistrationInfo topic = obtainTopicRegistrationInfo(topicName, true);
NodeRegistrationInfo node = obtainNodeRegistrationInfo(nodeName, nodeSlaveUri);
topic.addPublisher(node, topicMessageType);
node.addPublisher(topic);
return topic;
}
/**
* Unregister a publisher.
*
* @param nodeName
* name of the node which has the publisher
* @param topicName
* name of the publisher's topic
*
* @return {@code true} if the publisher was actually registered before the
* call.
*/
public boolean unregisterPublisher(GraphName nodeName, GraphName topicName) {
if (log.isDebugEnabled()) {
log.debug(String.format("Unregistering publisher of topic %s from node %s",
topicName, nodeName));
}
TopicRegistrationInfo topic = obtainTopicRegistrationInfo(topicName, false);
if (topic != null) {
NodeRegistrationInfo node = nodes.get(nodeName);
if (node != null) {
node.removePublisher(topic);
topic.removePublisher(node);
potentiallyDeleteNode(node);
return true;
} else {
// never was a node with that name
if (log.isWarnEnabled()) {
log.warn(String.format("Received unregister publisher for topic %s on unknown node %s",
topicName, nodeName));
}
return false;
}
} else {
// If no topic, there will be no node registration.
if (log.isWarnEnabled()) {
log.warn(String.format("Received unregister publisher for unknown topic %s on node %s",
topicName, nodeName));
}
return false;
}
}
/**
* Register a subscriber.
*
* @param nodeName
* name of the node with the subscriber
* @param nodeSlaveUri
* URI of the slave server on the node
* @param topicName
* then name of the topic
* @param topicMessageType
* message type of the topic
*
* @return The registration information for the topic.
*/
public TopicRegistrationInfo registerSubscriber(GraphName nodeName, URI nodeSlaveUri,
GraphName topicName, String topicMessageType) {
if (log.isDebugEnabled()) {
log.debug(String.format(
"Registering subscriber topic %s with message type %s on node %s with slave URI %s",
topicName, topicMessageType, nodeName, nodeSlaveUri));
}
TopicRegistrationInfo topic = obtainTopicRegistrationInfo(topicName, true);
NodeRegistrationInfo node = obtainNodeRegistrationInfo(nodeName, nodeSlaveUri);
topic.addSubscriber(node, topicMessageType);
node.addSubscriber(topic);
return topic;
}
/**
* Unregister a subscriber.
*
* @param nodeName
* name of the node which has the subscriber
* @param topicName
* name of the subscriber's topic
*
* @return {@code true} if the subscriber was actually registered before the
* call.
*/
public boolean unregisterSubscriber(GraphName nodeName, GraphName topicName) {
if (log.isDebugEnabled()) {
log.debug(String.format("Unregistering subscriber of topic %s from node %s",
topicName, nodeName));
}
TopicRegistrationInfo topic = obtainTopicRegistrationInfo(topicName, false);
if (topic != null) {
NodeRegistrationInfo node = nodes.get(nodeName);
if (node != null) {
node.removeSubscriber(topic);
topic.removeSubscriber(node);
potentiallyDeleteNode(node);
return true;
} else {
// never was a node with that name
if (log.isWarnEnabled()) {
log.warn(String.format("Received unregister subscriber for topic %s on unknown node %s",
topicName, nodeName));
}
return false;
}
} else {
// If no topic, there will be no node registration.
if (log.isWarnEnabled()) {
log.warn(String.format("Received unregister subscriber for unknown topic %s on node %s",
topicName, nodeName));
}
return false;
}
}
/**
* Register a service.
*
* @param nodeName
* name of the node with the service
* @param nodeSlaveUri
* URI of the slave server on the node
* @param serviceName
* the name of the service
* @param serviceUri
* URI of the service server on the node
*
* @return The registration information for the service.
*/
public ServiceRegistrationInfo registerService(GraphName nodeName, URI nodeSlaveUri,
GraphName serviceName, URI serviceUri) {
if (log.isDebugEnabled()) {
log.debug(String.format(
"Registering service %s with server URI %s on node %s with slave URI %s", serviceName,
serviceUri, nodeName, nodeSlaveUri));
}
NodeRegistrationInfo node = obtainNodeRegistrationInfo(nodeName, nodeSlaveUri);
ServiceRegistrationInfo service = services.get(serviceName);
if (service != null) {
NodeRegistrationInfo previousServiceNode = service.getNode();
if (previousServiceNode == node) {
// If node is the same, no need to do anything
if (log.isWarnEnabled()) {
log.warn(String
.format(
"Registering already known service %s with server URI %s on node %s with slave URI %s",
serviceName, serviceUri, nodeName, nodeSlaveUri));
}
return service;
} else {
// The service's node is changing.
previousServiceNode.removeService(service);
potentiallyDeleteNode(previousServiceNode);
}
}
// Service didn't exist or the node is changing.
service = new ServiceRegistrationInfo(serviceName, serviceUri, node);
node.addService(service);
services.put(serviceName, service);
return service;
}
/**
* Unregister a service.
*
* @param nodeName
* name of the node with the service
* @param serviceName
* the name of the service
* @param serviceUri
* URI of the service server on the node
*
* @return {@code true} if the service was actually registered before the
* call.
*/
public boolean unregisterService(GraphName nodeName, GraphName serviceName, URI serviceUri) {
if (log.isDebugEnabled()) {
log.debug(String.format("Unregistering service %s from node %s", serviceName, nodeName));
}
ServiceRegistrationInfo service = services.get(serviceName);
if (service != null) {
NodeRegistrationInfo node = nodes.get(nodeName);
if (node != null) {
// No need to keep service around.
services.remove(serviceName);
node.removeService(service);
potentiallyDeleteNode(node);
return true;
} else {
// never was a node with that name
if (log.isWarnEnabled()) {
log.warn(String.format("Received unregister for service %s on unknown node %s",
serviceName, nodeName));
}
// TODO(keith): Should the node be removed anyway, or should only its
// real node be able to unregister it?
return false;
}
} else {
// If no service, there will be no node registration.
if (log.isWarnEnabled()) {
log.warn(String.format("Received unregister for unknown service %s on node %s",
serviceName, nodeName));
}
return false;
}
}
/**
* Get all topics registered.
*
* @return An immutable collection of topics.
*/
public Collection<TopicRegistrationInfo> getAllTopics() {
return Collections.unmodifiableCollection(topics.values());
}
/**
* Get the information known about a topic.
*
* @param topicName
* the name of the topic
*
* @return The information about the topic. Can be {@code null} if the topic
* was never registered.
*/
public TopicRegistrationInfo getTopicRegistrationInfo(GraphName topicName) {
return topics.get(topicName);
}
/**
* Get the information known about a node.
*
* @param nodeName
* the name of the node
*
* @return The information about the node. Can be {@code null} if no topic was
* ever registered for the node.
*/
public NodeRegistrationInfo getNodeRegistrationInfo(GraphName nodeName) {
return nodes.get(nodeName);
}
/**
* Get all services registered.
*
* @return An immutable collection of services.
*/
public Collection<ServiceRegistrationInfo> getAllServices() {
return Collections.unmodifiableCollection(services.values());
}
/**
* Get the information known about a service.
*
* @param serviceName
* the name of the service
*
* @return The information about the service. Can be {@code null} if there is
* no service registered with the given name.
*/
public ServiceRegistrationInfo getServiceRegistrationInfo(GraphName serviceName) {
return services.get(serviceName);
}
/**
* Get the {@link TopicRegistrationInfo} for the given topic name.
*
* @param topicName
* the name of the topic
* @param shouldCreate
* {@code true} if a new one should be created if it isn't found
*
* @return The registration info for the topic. A new one will be created if
* none exists and on.
*/
private TopicRegistrationInfo obtainTopicRegistrationInfo(GraphName topicName,
boolean shouldCreate) {
TopicRegistrationInfo info = topics.get(topicName);
if (info == null && shouldCreate) {
info = new TopicRegistrationInfo(topicName);
topics.put(topicName, info);
}
return info;
}
/**
* Get the {@link NodeRegistrationInfo} for the given node slave identifier.
*
* @param nodeName
* the name of the node
* @param nodeSlaveUri
* the URI for the node's slave server
*
* @return The registration info for the node. A new one will be created if
* none exists.
*/
private NodeRegistrationInfo obtainNodeRegistrationInfo(GraphName nodeName, URI nodeSlaveUri) {
NodeRegistrationInfo node = nodes.get(nodeName);
if (node != null) {
// The node exists. Any need to shut it down?
if (node.getNodeSlaveUri().equals(nodeSlaveUri)) {
// OK, same URI so can just return it.
return node;
}
// The node is switching slave URIs, so we need a new one.
potentiallyDeleteNode(node);
cleanupNode(node);
try {
listener.onNodeReplacement(node);
} catch (Exception e) {
// No matter what, we want to keep going
log.error("Error during onNodeReplacement call", e);
}
}
// Either no existing node, or the old node needs to go away
node = new NodeRegistrationInfo(nodeName, nodeSlaveUri);
nodes.put(nodeName, node);
return node;
}
/**
* A node is being replaced. Clean it up. This includes unregistering from
* topic objects.
*
* @param node
* the node being replaced
*/
private void cleanupNode(NodeRegistrationInfo node) {
for (TopicRegistrationInfo topic : node.getPublishers()) {
topic.removePublisher(node);
}
for (TopicRegistrationInfo topic : node.getSubscribers()) {
topic.removeSubscriber(node);
}
for (ServiceRegistrationInfo service : node.getServices()) {
services.remove(service.getServiceName());
}
}
/**
* Remove a node from registration if it no longer has any registrations.
*
* @param node
* the node to possibly remove
*/
private void potentiallyDeleteNode(NodeRegistrationInfo node) {
if (!node.hasRegistrations()) {
nodes.remove(node.getNodeName());
}
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server.master;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.ros.namespace.GraphName;
import java.net.URI;
import java.util.Set;
/**
* Information a master needs about a node.
*
* @author khughes@google.com (Keith M. Hughes)
*/
public class NodeRegistrationInfo {
/**
* The name of the node.
*/
private final GraphName nodeName;
/**
* The URI for the node's slave server.
*/
private final URI nodeSlaveUri;
/**
* All subscribers associated with the node.
*/
private final Set<TopicRegistrationInfo> publishers;
/**
* All publishers associated with the node.
*/
private final Set<TopicRegistrationInfo> subscribers;
/**
* All services associated with the node.
*/
private final Set<ServiceRegistrationInfo> services;
public NodeRegistrationInfo(GraphName nodeName, URI nodeSlaveUri) {
this.nodeName = nodeName;
this.nodeSlaveUri = nodeSlaveUri;
this.publishers = Sets.newHashSet();
this.subscribers = Sets.newHashSet();
this.services = Sets.newHashSet();
}
/**
* @return the nodeName
*/
public GraphName getNodeName() {
return nodeName;
}
/**
* @return the nodeSlaveUri
*/
public URI getNodeSlaveUri() {
return nodeSlaveUri;
}
/**
* Does the node have any registrations of any sort.
*
* @return {code true} if there are still registrations for the node.
*/
public boolean hasRegistrations() {
return !publishers.isEmpty() || !subscribers.isEmpty() || !services.isEmpty();
}
/**
* Get all known topics published by the node.
*
* @return an immutable copy of the published topics
*/
public Set<TopicRegistrationInfo> getPublishers() {
return ImmutableSet.copyOf(publishers);
}
/**
* Add a new publisher to the node.
*
* @param publisherTopic
* the topic information about the publisher to add
*/
public void addPublisher(TopicRegistrationInfo publisherTopic) {
publishers.add(publisherTopic);
}
/**
* Remove a publisher from the node.
*
* @param publisherTopic
* the topic information about the publisher to remove
*
* @return {@code true} if the publisher had been there
*/
public boolean removePublisher(TopicRegistrationInfo publisherTopic) {
return publishers.remove(publisherTopic);
}
/**
* Get all known topics subscribed to by the node.
*
* @return an immutable copy of the topics subscribed to
*/
public Set<TopicRegistrationInfo> getSubscribers() {
return ImmutableSet.copyOf(subscribers);
}
/**
* Add a new subscriber to the node.
*
* @param subscriberTopic
* the topic information about the subscriber to add
*/
public void addSubscriber(TopicRegistrationInfo subscriberTopic) {
subscribers.add(subscriberTopic);
}
/**
* Remove a subscriber from the node.
*
* @param subscriberTopic
* the topic information about the subscriber to remove
*
* @return {@code true} if the subscriber had been there
*/
public boolean removeSubscriber(TopicRegistrationInfo subscriberTopic) {
return subscribers.remove(subscriberTopic);
}
/**
* Get all known services provided by the node.
*
* @return an immutable copy of the topics subscribed to
*/
public Set<ServiceRegistrationInfo> getServices() {
return ImmutableSet.copyOf(services);
}
/**
* Add a new service to the node.
*
* @param service
* the service to add
*/
public void addService(ServiceRegistrationInfo service) {
services.add(service);
}
/**
* Remove a service from the node.
*
* @param service
* the service to remove
*
* @return {@code true} if the subscriber had been there
*/
public boolean removeService(ServiceRegistrationInfo service) {
return services.remove(service);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + nodeName.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NodeRegistrationInfo other = (NodeRegistrationInfo) obj;
if (!nodeName.equals(other.nodeName))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server.master;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.ros.master.client.TopicSystemState;
import org.ros.namespace.GraphName;
import org.ros.node.topic.Subscriber;
import java.util.Set;
/**
* All information known to the manager about a topic.
*
* @author khughes@google.com (Keith M. Hughes)
*/
public class TopicRegistrationInfo {
/**
* The name of the topic.
*/
private final GraphName topicName;
/**
* The type of the topic's message.
*
* <p>
* Can be {@code null} if no publisher has registered the type.
*/
private String messageType;
/**
* {@code true} if the message type was defined by a publisher.
*/
private boolean isPublisherDefinedMessageType;
/**
* A publishers for the topic.
*/
private final Set<NodeRegistrationInfo> publishers;
/**
* All subscribers for the topic.
*/
private final Set<NodeRegistrationInfo> subscribers;
public TopicRegistrationInfo(GraphName topicName) {
this.topicName = topicName;
publishers = Sets.newHashSet();
subscribers = Sets.newHashSet();
isPublisherDefinedMessageType = false;
}
/**
* @return the topicName
*/
public GraphName getTopicName() {
return topicName;
}
/**
* Get the currently known message type of the topic.
*
* @return The message type. Can be {@code null} if unknown.
*/
public String getMessageType() {
return messageType;
}
/**
* Does the topic have any publishers?
*
* @return {@code true} if the topic has any publishers.
*/
public boolean hasPublishers() {
return !publishers.isEmpty();
}
/**
* Does the topic have any subscribers?
*
* @return {@code true} if the topic has any publishers or subscribers.
*/
public boolean hasSubscribers() {
return !subscribers.isEmpty();
}
/**
* Does the topic have any registrations?
*
* @return {@code true} if the topic has any publishers or subscribers.
*/
public boolean hasRegistrations() {
return hasPublishers() || hasSubscribers();
}
/**
* Get a list of all known publishers for the topic.
*
* @return an immutable list of publishers
*/
public Set<NodeRegistrationInfo> getPublishers() {
return ImmutableSet.copyOf(publishers);
}
/**
* Add a new publisher to the topic.
*
* @param publisher
* the publisher to add
* @param messageType
* the type of the message
*/
public void addPublisher(NodeRegistrationInfo publisher, String messageType) {
Preconditions.checkNotNull(publisher);
publishers.add(publisher);
setMessageType(messageType, true);
}
/**
* Remove a publisher to the topic.
*
* @param publisher
* the publisher to add
*
* @return {@code true} if the publisher was registered in the first place
*/
public boolean removePublisher(NodeRegistrationInfo publisher) {
return publishers.remove(publisher);
}
/**
* Get a list of all known subscribers for the topic.
*
* @return an immutable list of publishers
*/
public Set<NodeRegistrationInfo> getSubscribers() {
return ImmutableSet.copyOf(subscribers);
}
/**
* Add a new subscriber to the topic.
*
* @param subscriber
* the subscriber to add
* @param messageType
* the type of the message
*/
public void addSubscriber(NodeRegistrationInfo subscriber, String messageType) {
Preconditions.checkNotNull(subscriber);
subscribers.add(subscriber);
setMessageType(messageType, false);
}
/**
* Remove a subscriber to the topic.
*
* @param subscriber
* the subscriber to add
*
* @return {@code true} if the subscriber was registered in the first place
*/
public boolean removeSubscriber(NodeRegistrationInfo subscriber) {
return subscribers.remove(subscriber);
}
/**
* Register the message type of a {@link TopicSystemState}.
*
* @param topicMessageType
* the message type of the {@link TopicSystemState},
* {@link Subscriber}s can give a message type of
* {@value Subscriber#TOPIC_MESSAGE_TYPE_WILDCARD}
* @param isPublisher
* {code true} is a publisher is doing the registration,
* {@code false} if a subscriber is doing the registration
*/
private void setMessageType(String topicMessageType, boolean isPublisher) {
// The most recent association of topic name to message type wins.
// However, subscription associations are always trumped by publisher
// associations.
if (isPublisher) {
// Publishers always trump.
messageType = topicMessageType;
isPublisherDefinedMessageType = true;
} else {
// Is a subscriber.
if (!Subscriber.TOPIC_MESSAGE_TYPE_WILDCARD.equals(topicMessageType)) {
if (messageType != null) {
// if has only been subscribers giving the type, register it.
if (!isPublisherDefinedMessageType) {
messageType = topicMessageType;
}
} else {
// Not registered yet, so no worry about trumping.
messageType = topicMessageType;
}
}
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + topicName.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TopicRegistrationInfo other = (TopicRegistrationInfo) obj;
if (!topicName.equals(other.topicName))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node.server;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ros.internal.node.client.SlaveClient;
import org.ros.namespace.GraphName;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
/**
* A ROS parameter server.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class ParameterServer {
private static final Log log = LogFactory.getLog(ParameterServer.class);
private final Map<String, Object> tree;
private final Multimap<GraphName, NodeIdentifier> subscribers;
private final GraphName masterName;
public ParameterServer() {
tree = Maps.newConcurrentMap();
subscribers = Multimaps.synchronizedMultimap(HashMultimap.<GraphName, NodeIdentifier>create());
masterName = GraphName.of("/master");
}
public void subscribe(GraphName name, NodeIdentifier nodeIdentifier) {
subscribers.put(name, nodeIdentifier);
}
private Stack<String> getGraphNameParts(GraphName name) {
Stack<String> parts = new Stack<String>();
GraphName tip = name;
while (!tip.isRoot()) {
parts.add(tip.getBasename().toString());
tip = tip.getParent();
}
return parts;
}
@SuppressWarnings("unchecked")
public Object get(GraphName name) {
Preconditions.checkArgument(name.isGlobal());
Stack<String> parts = getGraphNameParts(name);
Object possibleSubtree = tree;
while (!parts.empty() && possibleSubtree != null) {
if (!(possibleSubtree instanceof Map)) {
return null;
}
possibleSubtree = ((Map<String, Object>) possibleSubtree).get(parts.pop());
}
return possibleSubtree;
}
@SuppressWarnings("unchecked")
private void setValue(GraphName name, Object value) {
Preconditions.checkArgument(name.isGlobal());
Stack<String> parts = getGraphNameParts(name);
Map<String, Object> subtree = tree;
while (!parts.empty()) {
String part = parts.pop();
if (parts.empty()) {
subtree.put(part, value);
} else if (subtree.containsKey(part) && subtree.get(part) instanceof Map) {
subtree = (Map<String, Object>) subtree.get(part);
} else {
Map<String, Object> newSubtree = Maps.newHashMap();
subtree.put(part, newSubtree);
subtree = newSubtree;
}
}
}
private interface Updater {
void update(SlaveClient client);
}
private <T> void update(GraphName name, T value, Updater updater) {
setValue(name, value);
synchronized (subscribers) {
for (NodeIdentifier nodeIdentifier : subscribers.get(name)) {
SlaveClient client = new SlaveClient(masterName, nodeIdentifier.getUri());
try {
updater.update(client);
} catch (Exception e) {
log.error(e);
}
}
}
}
public void set(final GraphName name, final boolean value) {
update(name, value, new Updater() {
@Override
public void update(SlaveClient client) {
client.paramUpdate(name, value);
}
});
}
public void set(final GraphName name, final int value) {
update(name, value, new Updater() {
@Override
public void update(SlaveClient client) {
client.paramUpdate(name, value);
}
});
}
public void set(final GraphName name, final double value) {
update(name, value, new Updater() {
@Override
public void update(SlaveClient client) {
client.paramUpdate(name, value);
}
});
}
public void set(final GraphName name, final String value) {
update(name, value, new Updater() {
@Override
public void update(SlaveClient client) {
client.paramUpdate(name, value);
}
});
}
public void set(final GraphName name, final List<?> value) {
update(name, value, new Updater() {
@Override
public void update(SlaveClient client) {
client.paramUpdate(name, value);
}
});
}
public void set(final GraphName name, final Map<?, ?> value) {
update(name, value, new Updater() {
@Override
public void update(SlaveClient client) {
client.paramUpdate(name, value);
}
});
}
@SuppressWarnings("unchecked")
public void delete(GraphName name) {
Preconditions.checkArgument(name.isGlobal());
Stack<String> parts = getGraphNameParts(name);
Map<String, Object> subtree = tree;
while (!parts.empty() && subtree.containsKey(parts.peek())) {
String part = parts.pop();
if (parts.empty()) {
subtree.remove(part);
} else {
subtree = (Map<String, Object>) subtree.get(part);
}
}
}
public Object search(GraphName name) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
public boolean has(GraphName name) {
Preconditions.checkArgument(name.isGlobal());
Stack<String> parts = getGraphNameParts(name);
Map<String, Object> subtree = tree;
while (!parts.empty() && subtree.containsKey(parts.peek())) {
String part = parts.pop();
if (!parts.empty()) {
subtree = (Map<String, Object>) subtree.get(part);
}
}
return parts.empty();
}
@SuppressWarnings("unchecked")
private Set<GraphName> getSubtreeNames(GraphName parent, Map<String, Object> subtree,
Set<GraphName> names) {
for (String name : subtree.keySet()) {
Object possibleSubtree = subtree.get(name);
if (possibleSubtree instanceof Map) {
names.addAll(getSubtreeNames(parent.join(GraphName.of(name)),
(Map<String, Object>) possibleSubtree, names));
} else {
names.add(parent.join(GraphName.of(name)));
}
}
return names;
}
public Collection<GraphName> getNames() {
Set<GraphName> names = Sets.newHashSet();
return getSubtreeNames(GraphName.root(), tree, names);
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.logging.Log;
import org.ros.Parameters;
import org.ros.concurrent.CancellableLoop;
import org.ros.concurrent.ListenerGroup;
import org.ros.concurrent.SignalRunnable;
import org.ros.exception.RemoteException;
import org.ros.exception.ServiceNotFoundException;
import org.ros.internal.message.service.ServiceDescription;
import org.ros.internal.message.topic.TopicDescription;
import org.ros.internal.node.client.MasterClient;
import org.ros.internal.node.client.Registrar;
import org.ros.internal.node.parameter.DefaultParameterTree;
import org.ros.internal.node.parameter.ParameterManager;
import org.ros.internal.node.response.Response;
import org.ros.internal.node.response.StatusCode;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.internal.node.server.SlaveServer;
import org.ros.internal.node.service.ServiceDeclaration;
import org.ros.internal.node.service.ServiceFactory;
import org.ros.internal.node.service.ServiceIdentifier;
import org.ros.internal.node.service.ServiceManager;
import org.ros.internal.node.topic.PublisherFactory;
import org.ros.internal.node.topic.SubscriberFactory;
import org.ros.internal.node.topic.TopicDeclaration;
import org.ros.internal.node.topic.TopicParticipantManager;
import org.ros.internal.node.xmlrpc.XmlRpcTimeoutException;
import org.ros.message.MessageDeserializer;
import org.ros.message.MessageFactory;
import org.ros.message.MessageSerializationFactory;
import org.ros.message.MessageSerializer;
import org.ros.message.Time;
import org.ros.namespace.GraphName;
import org.ros.namespace.NameResolver;
import org.ros.namespace.NodeNameResolver;
import org.ros.node.ConnectedNode;
import org.ros.node.DefaultNodeFactory;
import org.ros.node.Node;
import org.ros.node.NodeConfiguration;
import org.ros.node.NodeListener;
import org.ros.node.parameter.ParameterTree;
import org.ros.node.service.ServiceClient;
import org.ros.node.service.ServiceResponseBuilder;
import org.ros.node.service.ServiceServer;
import org.ros.node.topic.DefaultPublisherListener;
import org.ros.node.topic.DefaultSubscriberListener;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
import org.ros.time.ClockTopicTimeProvider;
import org.ros.time.TimeProvider;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* The default implementation of a {@link Node}.
*
* @author ethan.rublee@gmail.com (Ethan Rublee)
* @author kwc@willowgarage.com (Ken Conley)
* @author damonkohler@google.com (Damon Kohler)
*/
public class DefaultNode implements ConnectedNode {
private static final boolean DEBUG = false;
// TODO(damonkohler): Move to NodeConfiguration.
/**
* The maximum delay before shutdown will begin even if all
* {@link NodeListener}s have not yet returned from their
* {@link NodeListener#onShutdown(Node)} callback.
*/
private static final int MAX_SHUTDOWN_DELAY_DURATION = 5;
private static final TimeUnit MAX_SHUTDOWN_DELAY_UNITS = TimeUnit.SECONDS;
private final NodeConfiguration nodeConfiguration;
private final ListenerGroup<NodeListener> nodeListeners;
private final ScheduledExecutorService scheduledExecutorService;
private final URI masterUri;
private final MasterClient masterClient;
private final TopicParticipantManager topicParticipantManager;
private final ServiceManager serviceManager;
private final ParameterManager parameterManager;
private final GraphName nodeName;
private final NodeNameResolver resolver;
private final SlaveServer slaveServer;
private final ParameterTree parameterTree;
private final PublisherFactory publisherFactory;
private final SubscriberFactory subscriberFactory;
private final ServiceFactory serviceFactory;
private final Registrar registrar;
private RosoutLogger log;
private TimeProvider timeProvider;
/**
* {@link DefaultNode}s should only be constructed using the
* {@link DefaultNodeFactory}.
*
* @param nodeConfiguration
* the {@link NodeConfiguration} for this {@link Node}
* @param nodeListeners
* a {@link Collection} of {@link NodeListener}s that will be added
* to this {@link Node} before it starts
*/
public DefaultNode(NodeConfiguration nodeConfiguration, Collection<NodeListener> nodeListeners,
ScheduledExecutorService scheduledExecutorService) {
this.nodeConfiguration = NodeConfiguration.copyOf(nodeConfiguration);
this.nodeListeners = new ListenerGroup<NodeListener>(scheduledExecutorService);
this.nodeListeners.addAll(nodeListeners);
this.scheduledExecutorService = scheduledExecutorService;
masterUri = nodeConfiguration.getMasterUri();
masterClient = new MasterClient(masterUri);
topicParticipantManager = new TopicParticipantManager();
serviceManager = new ServiceManager();
parameterManager = new ParameterManager(scheduledExecutorService);
GraphName basename = nodeConfiguration.getNodeName();
NameResolver parentResolver = nodeConfiguration.getParentResolver();
nodeName = parentResolver.getNamespace().join(basename);
resolver = new NodeNameResolver(nodeName, parentResolver);
slaveServer =
new SlaveServer(nodeName, nodeConfiguration.getTcpRosBindAddress(),
nodeConfiguration.getTcpRosAdvertiseAddress(),
nodeConfiguration.getXmlRpcBindAddress(),
nodeConfiguration.getXmlRpcAdvertiseAddress(), masterClient, topicParticipantManager,
serviceManager, parameterManager, scheduledExecutorService);
slaveServer.start();
NodeIdentifier nodeIdentifier = slaveServer.toNodeIdentifier();
parameterTree =
DefaultParameterTree.newFromNodeIdentifier(nodeIdentifier, masterClient.getRemoteUri(),
resolver, parameterManager);
publisherFactory =
new PublisherFactory(nodeIdentifier, topicParticipantManager,
nodeConfiguration.getTopicMessageFactory(), scheduledExecutorService);
subscriberFactory =
new SubscriberFactory(nodeIdentifier, topicParticipantManager, scheduledExecutorService);
serviceFactory =
new ServiceFactory(nodeName, slaveServer, serviceManager, scheduledExecutorService);
registrar = new Registrar(masterClient, scheduledExecutorService);
topicParticipantManager.setListener(registrar);
serviceManager.setListener(registrar);
scheduledExecutorService.execute(new Runnable() {
@Override
public void run() {
start();
}
});
}
private void start() {
// The Registrar must be started first so that master registration is
// possible during startup.
registrar.start(slaveServer.toNodeIdentifier());
// During startup, we wait for 1) the RosoutLogger and 2) the TimeProvider.
final CountDownLatch latch = new CountDownLatch(2);
log = new RosoutLogger(this);
log.getPublisher().addListener(new DefaultPublisherListener<rosgraph_msgs.Log>() {
@Override
public void onMasterRegistrationSuccess(Publisher<rosgraph_msgs.Log> registrant) {
latch.countDown();
}
});
boolean useSimTime = false;
try {
useSimTime =
parameterTree.has(Parameters.USE_SIM_TIME)
&& parameterTree.getBoolean(Parameters.USE_SIM_TIME);
} catch (Exception e) {
signalOnError(e);
}
if (useSimTime) {
ClockTopicTimeProvider clockTopicTimeProvider = new ClockTopicTimeProvider(this);
clockTopicTimeProvider.getSubscriber().addSubscriberListener(
new DefaultSubscriberListener<rosgraph_msgs.Clock>() {
@Override
public void onMasterRegistrationSuccess(Subscriber<rosgraph_msgs.Clock> subscriber) {
latch.countDown();
}
});
timeProvider = clockTopicTimeProvider;
} else {
timeProvider = nodeConfiguration.getTimeProvider();
latch.countDown();
}
try {
latch.await();
} catch (InterruptedException e) {
signalOnError(e);
shutdown();
return;
}
signalOnStart();
}
@VisibleForTesting
Registrar getRegistrar() {
return registrar;
}
private <T> org.ros.message.MessageSerializer<T> newMessageSerializer(String messageType) {
return nodeConfiguration.getMessageSerializationFactory().newMessageSerializer(messageType);
}
@SuppressWarnings("unchecked")
private <T> MessageDeserializer<T> newMessageDeserializer(String messageType) {
return (MessageDeserializer<T>) nodeConfiguration.getMessageSerializationFactory()
.newMessageDeserializer(messageType);
}
@SuppressWarnings("unchecked")
private <T> MessageSerializer<T> newServiceResponseSerializer(String serviceType) {
return (MessageSerializer<T>) nodeConfiguration.getMessageSerializationFactory()
.newServiceResponseSerializer(serviceType);
}
@SuppressWarnings("unchecked")
private <T> MessageDeserializer<T> newServiceResponseDeserializer(String serviceType) {
return (MessageDeserializer<T>) nodeConfiguration.getMessageSerializationFactory()
.newServiceResponseDeserializer(serviceType);
}
@SuppressWarnings("unchecked")
private <T> MessageSerializer<T> newServiceRequestSerializer(String serviceType) {
return (MessageSerializer<T>) nodeConfiguration.getMessageSerializationFactory()
.newServiceRequestSerializer(serviceType);
}
@SuppressWarnings("unchecked")
private <T> MessageDeserializer<T> newServiceRequestDeserializer(String serviceType) {
return (MessageDeserializer<T>) nodeConfiguration.getMessageSerializationFactory()
.newServiceRequestDeserializer(serviceType);
}
@Override
public <T> Publisher<T> newPublisher(GraphName topicName, String messageType) {
GraphName resolvedTopicName = resolveName(topicName);
TopicDescription topicDescription =
nodeConfiguration.getTopicDescriptionFactory().newFromType(messageType);
TopicDeclaration topicDeclaration =
TopicDeclaration.newFromTopicName(resolvedTopicName, topicDescription);
org.ros.message.MessageSerializer<T> serializer = newMessageSerializer(messageType);
return publisherFactory.newOrExisting(topicDeclaration, serializer);
}
@Override
public <T> Publisher<T> newPublisher(String topicName, String messageType) {
return newPublisher(GraphName.of(topicName), messageType);
}
@Override
public <T> Subscriber<T> newSubscriber(GraphName topicName, String messageType) {
GraphName resolvedTopicName = resolveName(topicName);
TopicDescription topicDescription =
nodeConfiguration.getTopicDescriptionFactory().newFromType(messageType);
TopicDeclaration topicDeclaration =
TopicDeclaration.newFromTopicName(resolvedTopicName, topicDescription);
MessageDeserializer<T> deserializer = newMessageDeserializer(messageType);
Subscriber<T> subscriber = subscriberFactory.newOrExisting(topicDeclaration, deserializer);
return subscriber;
}
@Override
public <T> Subscriber<T> newSubscriber(String topicName, String messageType) {
return newSubscriber(GraphName.of(topicName), messageType);
}
@Override
public <T, S> ServiceServer<T, S> newServiceServer(GraphName serviceName, String serviceType,
ServiceResponseBuilder<T, S> responseBuilder) {
GraphName resolvedServiceName = resolveName(serviceName);
// TODO(damonkohler): It's rather non-obvious that the URI will be
// created later on the fly.
ServiceIdentifier identifier = new ServiceIdentifier(resolvedServiceName, null);
ServiceDescription serviceDescription =
nodeConfiguration.getServiceDescriptionFactory().newFromType(serviceType);
ServiceDeclaration definition = new ServiceDeclaration(identifier, serviceDescription);
MessageDeserializer<T> requestDeserializer = newServiceRequestDeserializer(serviceType);
MessageSerializer<S> responseSerializer = newServiceResponseSerializer(serviceType);
return serviceFactory.newServer(definition, responseBuilder, requestDeserializer,
responseSerializer, nodeConfiguration.getServiceResponseMessageFactory());
}
@Override
public <T, S> ServiceServer<T, S> newServiceServer(String serviceName, String serviceType,
ServiceResponseBuilder<T, S> responseBuilder) {
return newServiceServer(GraphName.of(serviceName), serviceType, responseBuilder);
}
@SuppressWarnings("unchecked")
@Override
public <T, S> ServiceServer<T, S> getServiceServer(GraphName serviceName) {
return (ServiceServer<T, S>) serviceManager.getServer(serviceName);
}
@Override
public <T, S> ServiceServer<T, S> getServiceServer(String serviceName) {
return getServiceServer(GraphName.of(serviceName));
}
@Override
public URI lookupServiceUri(GraphName serviceName) {
Response<URI> response =
masterClient.lookupService(slaveServer.toNodeIdentifier().getName(),
resolveName(serviceName).toString());
if (response.getStatusCode() == StatusCode.SUCCESS) {
return response.getResult();
} else {
return null;
}
}
@Override
public URI lookupServiceUri(String serviceName) {
return lookupServiceUri(GraphName.of(serviceName));
}
@Override
public <T, S> ServiceClient<T, S> newServiceClient(GraphName serviceName, String serviceType)
throws ServiceNotFoundException {
GraphName resolvedServiceName = resolveName(serviceName);
URI uri = lookupServiceUri(resolvedServiceName);
if (uri == null) {
throw new ServiceNotFoundException("No such service " + resolvedServiceName + " of type "
+ serviceType);
}
ServiceDescription serviceDescription =
nodeConfiguration.getServiceDescriptionFactory().newFromType(serviceType);
ServiceIdentifier serviceIdentifier = new ServiceIdentifier(resolvedServiceName, uri);
ServiceDeclaration definition = new ServiceDeclaration(serviceIdentifier, serviceDescription);
MessageSerializer<T> requestSerializer = newServiceRequestSerializer(serviceType);
MessageDeserializer<S> responseDeserializer = newServiceResponseDeserializer(serviceType);
return serviceFactory.newClient(definition, requestSerializer, responseDeserializer,
nodeConfiguration.getServiceRequestMessageFactory());
}
@Override
public <T, S> ServiceClient<T, S> newServiceClient(String serviceName, String serviceType)
throws ServiceNotFoundException {
return newServiceClient(GraphName.of(serviceName), serviceType);
}
@Override
public Time getCurrentTime() {
return timeProvider.getCurrentTime();
}
@Override
public GraphName getName() {
return nodeName;
}
@Override
public Log getLog() {
return log;
}
@Override
public GraphName resolveName(GraphName name) {
return resolver.resolve(name);
}
@Override
public GraphName resolveName(String name) {
return resolver.resolve(GraphName.of(name));
}
@Override
public void shutdown() {
signalOnShutdown();
// NOTE(damonkohler): We don't want to raise potentially spurious
// exceptions during shutdown that would interrupt the process. This is
// simply best effort cleanup.
for (Publisher<?> publisher : topicParticipantManager.getPublishers()) {
publisher.shutdown();
}
for (Subscriber<?> subscriber : topicParticipantManager.getSubscribers()) {
subscriber.shutdown();
}
for (ServiceServer<?, ?> serviceServer : serviceManager.getServers()) {
try {
Response<Integer> response =
masterClient.unregisterService(slaveServer.toNodeIdentifier(), serviceServer);
if (DEBUG) {
if (response.getResult() == 0) {
System.err.println("Failed to unregister service: " + serviceServer.getName());
}
}
} catch (XmlRpcTimeoutException e) {
log.error(e);
} catch (RemoteException e) {
log.error(e);
}
}
for (ServiceClient<?, ?> serviceClient : serviceManager.getClients()) {
serviceClient.shutdown();
}
registrar.shutdown();
slaveServer.shutdown();
signalOnShutdownComplete();
}
@Override
public URI getMasterUri() {
return masterUri;
}
@Override
public NodeNameResolver getResolver() {
return resolver;
}
@Override
public ParameterTree getParameterTree() {
return parameterTree;
}
@Override
public URI getUri() {
return slaveServer.getUri();
}
@Override
public MessageSerializationFactory getMessageSerializationFactory() {
return nodeConfiguration.getMessageSerializationFactory();
}
@Override
public MessageFactory getTopicMessageFactory() {
return nodeConfiguration.getTopicMessageFactory();
}
@Override
public MessageFactory getServiceRequestMessageFactory() {
return nodeConfiguration.getServiceRequestMessageFactory();
}
@Override
public MessageFactory getServiceResponseMessageFactory() {
return nodeConfiguration.getServiceResponseMessageFactory();
}
@Override
public void addListener(NodeListener listener) {
nodeListeners.add(listener);
}
/**
* SignalRunnable all {@link NodeListener}s that the {@link Node} has
* experienced an error.
* <p>
* Each listener is called in a separate thread.
*/
private void signalOnError(final Throwable throwable) {
final Node node = this;
nodeListeners.signal(new SignalRunnable<NodeListener>() {
@Override
public void run(NodeListener listener) {
listener.onError(node, throwable);
}
});
}
/**
* SignalRunnable all {@link NodeListener}s that the {@link Node} has started.
* <p>
* Each listener is called in a separate thread.
*/
private void signalOnStart() {
final ConnectedNode connectedNode = this;
nodeListeners.signal(new SignalRunnable<NodeListener>() {
@Override
public void run(NodeListener listener) {
listener.onStart(connectedNode);
}
});
}
/**
* SignalRunnable all {@link NodeListener}s that the {@link Node} has started
* shutting down.
* <p>
* Each listener is called in a separate thread.
*/
private void signalOnShutdown() {
final Node node = this;
try {
nodeListeners.signal(new SignalRunnable<NodeListener>() {
@Override
public void run(NodeListener listener) {
listener.onShutdown(node);
}
}, MAX_SHUTDOWN_DELAY_DURATION, MAX_SHUTDOWN_DELAY_UNITS);
} catch (InterruptedException e) {
// Ignored since we do not guarantee that all listeners will finish
// before
// shutdown begins.
}
}
/**
* SignalRunnable all {@link NodeListener}s that the {@link Node} has shut
* down.
* <p>
* Each listener is called in a separate thread.
*/
private void signalOnShutdownComplete() {
final Node node = this;
nodeListeners.signal(new SignalRunnable<NodeListener>() {
@Override
public void run(NodeListener listener) {
try {
listener.onShutdownComplete(node);
} catch (Throwable e) {
System.out.println(listener);
}
}
});
}
@VisibleForTesting
InetSocketAddress getAddress() {
return slaveServer.getAddress();
}
@Override
public ScheduledExecutorService getScheduledExecutorService() {
return scheduledExecutorService;
}
@Override
public void executeCancellableLoop(final CancellableLoop cancellableLoop) {
scheduledExecutorService.execute(cancellableLoop);
addListener(new NodeListener() {
@Override
public void onStart(ConnectedNode connectedNode) {
}
@Override
public void onShutdown(Node node) {
cancellableLoop.cancel();
}
@Override
public void onShutdownComplete(Node node) {
}
@Override
public void onError(Node node, Throwable throwable) {
cancellableLoop.cancel();
}
});
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.node;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public interface RegistrantListener<T> {
/**
* The registrant has been registered with the master.
*
* @param registrant
* the registrant which has been registered
*/
void onMasterRegistrationSuccess(T registrant);
/**
* The registrant has failed to register with the master.
*
* <p>
* This may be called multiple times per registrant since master registration
* will be retried until success.
*
* @param registrant
* the registrant which has been registered
*/
void onMasterRegistrationFailure(T registrant);
/**
* The registrant has been unregistered with the master.
*
* @param registrant
* the registrant which has been unregistered
*/
void onMasterUnregistrationSuccess(T registrant);
/**
* The registrant has failed to unregister with the master.
*
* <p>
* This may be called multiple times per registrant since master
* unregistration will be retried until success.
*
* @param registrant
* the registrant which has been unregistered
*/
void onMasterUnregistrationFailure(T registrant);
} | Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides internal utility classes for system operations.
* <p>
* These classes should _not_ be used directly outside of the org.ros package.
*/
package org.ros.internal.system; | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.system;
import java.lang.management.ManagementFactory;
/**
* Process-related utility methods.
*
* @author khughes@google.com (Keith M. Hughes)
*/
public class Process {
private Process() {
// Utility class.
}
/**
* @return PID of node process if available, throws
* {@link UnsupportedOperationException} otherwise.
*/
public static int getPid() {
// NOTE(kwc): Java has no standard way of getting PID. MF.getName()
// returns '1234@localhost'.
try {
String mxName = ManagementFactory.getRuntimeMXBean().getName();
int idx = mxName.indexOf('@');
if (idx > 0) {
try {
return Integer.parseInt(mxName.substring(0, idx));
} catch (NumberFormatException e) {
return 0;
}
}
} catch (NoClassDefFoundError unused) {
// Android does not support ManagementFactory. Try to get the PID on
// Android.
try {
return (Integer) Class.forName("android.os.Process").getMethod("myPid").invoke(null);
} catch (Exception unused1) {
// Ignore this exception and fall through to the
// UnsupportedOperationException.
}
}
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides internal classes for loading node configurations.
* <p>
* These classes should _not_ be used directly outside of the org.ros package.
*/
package org.ros.internal.loader; | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.loader;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.ros.CommandLineVariables;
import org.ros.EnvironmentVariables;
import org.ros.address.InetAddressFactory;
import org.ros.exception.RosRuntimeException;
import org.ros.namespace.GraphName;
import org.ros.namespace.NameResolver;
import org.ros.node.NodeConfiguration;
import org.ros.node.NodeMain;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Create {@link NodeConfiguration} instances using a ROS command-line and
* environment specification.
*
* @author kwc@willowgarage.com (Ken Conley)
* @author damonkohler@google.com (Damon Kohler)
*/
public class CommandLineLoader {
private final List<String> argv;
private final List<String> nodeArguments;
private final List<String> remappingArguments;
private final Map<String, String> environment;
private final Map<String, String> specialRemappings;
private final Map<GraphName, GraphName> remappings;
private String nodeClassName;
/**
* Create new {@link CommandLineLoader} with specified command-line arguments.
* Environment variables will be pulled from default {@link System}
* environment variables.
*
* @param argv
* command-line arguments
*/
public CommandLineLoader(List<String> argv) {
this(argv, System.getenv());
}
/**
* Create new {@link CommandLineLoader} with specified command-line arguments
* and environment variables.
*
* @param argv
* command-line arguments
* @param environment
* environment variables
*/
public CommandLineLoader(List<String> argv, Map<String, String> environment) {
Preconditions.checkArgument(argv.size() > 0);
this.argv = argv;
this.environment = environment;
nodeArguments = Lists.newArrayList();
remappingArguments = Lists.newArrayList();
remappings = Maps.newHashMap();
specialRemappings = Maps.newHashMap();
parseArgv();
}
private void parseArgv() {
nodeClassName = argv.get(0);
for (String argument : argv.subList(1, argv.size())) {
if (argument.contains(":=")) {
remappingArguments.add(argument);
} else {
nodeArguments.add(argument);
}
}
}
public String getNodeClassName() {
return nodeClassName;
}
public List<String> getNodeArguments() {
return Collections.unmodifiableList(nodeArguments);
}
/**
* Create NodeConfiguration according to ROS command-line and environment
* specification.
*/
public NodeConfiguration build() {
parseRemappingArguments();
// TODO(damonkohler): Add support for starting up a private node.
NodeConfiguration nodeConfiguration = NodeConfiguration.newPublic(getHost());
nodeConfiguration.setParentResolver(buildParentResolver());
nodeConfiguration.setRosRoot(getRosRoot());
nodeConfiguration.setRosPackagePath(getRosPackagePath());
nodeConfiguration.setMasterUri(getMasterUri());
if (specialRemappings.containsKey(CommandLineVariables.NODE_NAME)) {
nodeConfiguration.setNodeName(specialRemappings.get(CommandLineVariables.NODE_NAME));
}
return nodeConfiguration;
}
private void parseRemappingArguments() {
for (String remapping : remappingArguments) {
Preconditions.checkState(remapping.contains(":="));
String[] remap = remapping.split(":=");
if (remap.length > 2) {
throw new IllegalArgumentException("Invalid remapping argument: " + remapping);
}
if (remapping.startsWith("__")) {
specialRemappings.put(remap[0], remap[1]);
} else {
remappings.put(GraphName.of(remap[0]), GraphName.of(remap[1]));
}
}
}
/**
* Precedence:
*
* <ol>
* <li>The __ns:= command line argument.</li>
* <li>The ROS_NAMESPACE environment variable.</li>
* </ol>
*/
private NameResolver buildParentResolver() {
GraphName namespace = GraphName.root();
if (specialRemappings.containsKey(CommandLineVariables.ROS_NAMESPACE)) {
namespace =
GraphName.of(specialRemappings.get(CommandLineVariables.ROS_NAMESPACE)).toGlobal();
} else if (environment.containsKey(EnvironmentVariables.ROS_NAMESPACE)) {
namespace = GraphName.of(environment.get(EnvironmentVariables.ROS_NAMESPACE)).toGlobal();
}
return new NameResolver(namespace, remappings);
}
/**
* Precedence (default: null):
*
* <ol>
* <li>The __ip:= command line argument.</li>
* <li>The ROS_IP environment variable.</li>
* <li>The ROS_HOSTNAME environment variable.</li>
* <li>The default host as specified in {@link NodeConfiguration}.</li>
* </ol>
*/
private String getHost() {
String host = InetAddressFactory.newLoopback().getHostAddress();
if (specialRemappings.containsKey(CommandLineVariables.ROS_IP)) {
host = specialRemappings.get(CommandLineVariables.ROS_IP);
} else if (environment.containsKey(EnvironmentVariables.ROS_IP)) {
host = environment.get(EnvironmentVariables.ROS_IP);
} else if (environment.containsKey(EnvironmentVariables.ROS_HOSTNAME)) {
host = environment.get(EnvironmentVariables.ROS_HOSTNAME);
}
return host;
}
/**
* Precedence:
*
* <ol>
* <li>The __master:= command line argument. This is not required but easy to
* support.</li>
* <li>The ROS_MASTER_URI environment variable.</li>
* <li>The default master URI as defined in {@link NodeConfiguration}.</li>
* </ol>
*/
private URI getMasterUri() {
URI uri = NodeConfiguration.DEFAULT_MASTER_URI;
try {
if (specialRemappings.containsKey(CommandLineVariables.ROS_MASTER_URI)) {
uri = new URI(specialRemappings.get(CommandLineVariables.ROS_MASTER_URI));
} else if (environment.containsKey(EnvironmentVariables.ROS_MASTER_URI)) {
uri = new URI(environment.get(EnvironmentVariables.ROS_MASTER_URI));
}
return uri;
} catch (URISyntaxException e) {
throw new RosRuntimeException("Invalid master URI: " + uri);
}
}
private File getRosRoot() {
if (environment.containsKey(EnvironmentVariables.ROS_ROOT)) {
return new File(environment.get(EnvironmentVariables.ROS_ROOT));
} else {
// For now, this is not required as we are not doing anything (e.g.
// ClassLoader) that requires it. In the future, this may become required.
return null;
}
}
private List<File> getRosPackagePath() {
if (environment.containsKey(EnvironmentVariables.ROS_PACKAGE_PATH)) {
String rosPackagePath = environment.get(EnvironmentVariables.ROS_PACKAGE_PATH);
List<File> paths = Lists.newArrayList();
for (String path : rosPackagePath.split(File.pathSeparator)) {
paths.add(new File(path));
}
return paths;
} else {
return Lists.newArrayList();
}
}
/**
* @param name
* the name of the class
* @return an instance of {@link NodeMain}
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public NodeMain loadClass(String name) throws ClassNotFoundException, InstantiationException,
IllegalAccessException {
Class<?> clazz = getClass().getClassLoader().loadClass(name);
return NodeMain.class.cast(clazz.newInstance());
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.ros.concurrent.ListenerGroup;
import org.ros.concurrent.SignalRunnable;
import org.ros.internal.transport.tcp.AbstractNamedChannelHandler;
import java.util.concurrent.ExecutorService;
/**
* Common functionality for {@link ClientHandshake} handlers.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public abstract class BaseClientHandshakeHandler extends AbstractNamedChannelHandler {
private final ClientHandshake clientHandshake;
private final ListenerGroup<ClientHandshakeListener> clientHandshakeListeners;
public BaseClientHandshakeHandler(ClientHandshake clientHandshake, ExecutorService executorService) {
this.clientHandshake = clientHandshake;
clientHandshakeListeners = new ListenerGroup<ClientHandshakeListener>(executorService);
}
public void addListener(ClientHandshakeListener clientHandshakeListener) {
clientHandshakeListeners.add(clientHandshakeListener);
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelConnected(ctx, e);
e.getChannel().write(clientHandshake.getOutgoingConnectionHeader().encode());
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
ConnectionHeader connectionHeader = ConnectionHeader.decode(buffer);
if (clientHandshake.handshake(connectionHeader)) {
onSuccess(connectionHeader, ctx, e);
signalOnSuccess(connectionHeader);
} else {
onFailure(clientHandshake.getErrorMessage(), ctx, e);
signalOnFailure(clientHandshake.getErrorMessage());
}
}
/**
* Called when the {@link ClientHandshake} succeeds and will block the network
* thread until it returns.
* <p>
* This must block in order to allow changes to the pipeline to be made before
* further messages arrive.
*
* @param incommingConnectionHeader
* @param ctx
* @param e
*/
protected abstract void onSuccess(ConnectionHeader incommingConnectionHeader,
ChannelHandlerContext ctx, MessageEvent e);
private void signalOnSuccess(final ConnectionHeader incommingConnectionHeader) {
clientHandshakeListeners.signal(new SignalRunnable<ClientHandshakeListener>() {
@Override
public void run(ClientHandshakeListener listener) {
listener.onSuccess(clientHandshake.getOutgoingConnectionHeader(), incommingConnectionHeader);
}
});
}
protected abstract void onFailure(String errorMessage, ChannelHandlerContext ctx, MessageEvent e);
private void signalOnFailure(final String errorMessage) {
clientHandshakeListeners.signal(new SignalRunnable<ClientHandshakeListener>() {
@Override
public void run(ClientHandshakeListener listener) {
listener.onFailure(clientHandshake.getOutgoingConnectionHeader(), errorMessage);
}
});
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.queue;
import com.google.common.annotations.VisibleForTesting;
import org.jboss.netty.buffer.ChannelBuffer;
import org.ros.message.MessageDeserializer;
/**
* Lazily deserializes a message on the first call to {@link #get()} and caches
* the result.
* <p>
* This class is thread-safe.
*
* @author damonkohler@google.com (Damon Kohler)
*
* @param <T>
* the message type
*/
public class LazyMessage<T> {
private final ChannelBuffer buffer;
private final MessageDeserializer<T> deserializer;
private final Object mutex;
private T message;
/**
* @param buffer
* the {@link ChannelBuffer} to be lazily deserialized
* @param deserializer
* the {@link MessageDeserializer} to use
*/
public LazyMessage(ChannelBuffer buffer, MessageDeserializer<T> deserializer) {
this.buffer = buffer;
this.deserializer = deserializer;
mutex = new Object();
}
@VisibleForTesting
LazyMessage(T message) {
this(null, null);
this.message = message;
}
/**
* @return the deserialized message
*/
public T get() {
synchronized (mutex) {
if (message != null) {
return message;
}
message = deserializer.deserialize(buffer);
}
return message;
}
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.queue;
import org.ros.concurrent.CircularBlockingDeque;
import org.ros.internal.transport.tcp.NamedChannelHandler;
import org.ros.message.MessageDeserializer;
import org.ros.message.MessageListener;
import java.util.concurrent.ExecutorService;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class IncomingMessageQueue<T> {
/**
* The maximum number of incoming messages that will be queued.
* <p>
* This limit applies to dispatching {@link LazyMessage}s as they arrive over
* the network. It is independent of {@link MessageDispatcher} queue
* capacities specified by
* {@link IncomingMessageQueue#addListener(MessageListener, int)} which are
* consumed by user provided {@link MessageListener}s.
*/
private static final int DEQUE_CAPACITY = 16;
private final MessageReceiver<T> messageReceiver;
private final MessageDispatcher<T> messageDispatcher;
public IncomingMessageQueue(MessageDeserializer<T> deserializer, ExecutorService executorService) {
CircularBlockingDeque<LazyMessage<T>> lazyMessages =
new CircularBlockingDeque<LazyMessage<T>>(DEQUE_CAPACITY);
messageReceiver = new MessageReceiver<T>(lazyMessages, deserializer);
messageDispatcher = new MessageDispatcher<T>(lazyMessages, executorService);
executorService.execute(messageDispatcher);
}
/**
* @see MessageDispatcher#setLatchMode(boolean)
*/
public void setLatchMode(boolean enabled) {
messageDispatcher.setLatchMode(enabled);
}
/**
* @see MessageDispatcher#getLatchMode()
*/
public boolean getLatchMode() {
return messageDispatcher.getLatchMode();
}
/**
* @see MessageDispatcher#addListener(MessageListener, int)
*/
public void addListener(final MessageListener<T> messageListener, int queueCapacity) {
messageDispatcher.addListener(messageListener, queueCapacity);
}
public void shutdown() {
messageDispatcher.cancel();
}
/**
* @return a {@link NamedChannelHandler} that will receive messages and add
* them to the queue
*/
public NamedChannelHandler getMessageReceiver() {
return messageReceiver;
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.queue;
import org.ros.concurrent.CircularBlockingDeque;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.ros.internal.transport.tcp.AbstractNamedChannelHandler;
import org.ros.message.MessageDeserializer;
/**
* @author damonkohler@google.com (Damon Kohler)
*
* @param <T>
* the message type
*/
public class MessageReceiver<T> extends AbstractNamedChannelHandler {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(MessageReceiver.class);
private final CircularBlockingDeque<LazyMessage<T>> lazyMessages;
private final MessageDeserializer<T> deserializer;
public MessageReceiver(CircularBlockingDeque<LazyMessage<T>> lazyMessages,
MessageDeserializer<T> deserializer) {
this.lazyMessages = lazyMessages;
this.deserializer = deserializer;
}
@Override
public String getName() {
return "IncomingMessageQueueChannelHandler";
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
if (DEBUG) {
log.info(String.format("Received %d byte message.", buffer.readableBytes()));
}
// We have to make a defensive copy of the buffer here because Netty does
// not guarantee that the returned ChannelBuffer will not be reused.
lazyMessages.addLast(new LazyMessage<T>(buffer.copy(), deserializer));
super.messageReceived(ctx, e);
}
} | Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.queue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ros.concurrent.CancellableLoop;
import org.ros.concurrent.CircularBlockingDeque;
import org.ros.concurrent.EventDispatcher;
import org.ros.concurrent.ListenerGroup;
import org.ros.concurrent.SignalRunnable;
import org.ros.message.MessageListener;
import java.util.concurrent.ExecutorService;
/**
* @author damonkohler@google.com (Damon Kohler)
*
* @param <T>
* the message type
*/
public class MessageDispatcher<T> extends CancellableLoop {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(MessageDispatcher.class);
private final CircularBlockingDeque<LazyMessage<T>> lazyMessages;
private final ListenerGroup<MessageListener<T>> messageListeners;
/**
* Ensures that a messages are not dispatched twice when adding a listener
* while latch mode is enabled.
*/
private final Object mutex;
private boolean latchMode;
private LazyMessage<T> latchedMessage;
public MessageDispatcher(CircularBlockingDeque<LazyMessage<T>> lazyMessages,
ExecutorService executorService) {
this.lazyMessages = lazyMessages;
messageListeners = new ListenerGroup<MessageListener<T>>(executorService);
mutex = new Object();
latchMode = false;
}
/**
* Adds the specified {@link MessageListener} to the internal
* {@link ListenerGroup}. If {@link #latchMode} is {@code true}, the
* {@link #latchedMessage} will be immediately dispatched to the specified
* {@link MessageListener}.
*
* @see ListenerGroup#add(Object, int)
*/
public void addListener(MessageListener<T> messageListener, int limit) {
if (DEBUG) {
log.info("Adding listener.");
}
synchronized (mutex) {
EventDispatcher<MessageListener<T>> eventDispatcher =
messageListeners.add(messageListener, limit);
if (latchMode && latchedMessage != null) {
eventDispatcher.signal(newSignalRunnable(latchedMessage));
}
}
}
/**
* Returns a newly allocated {@link SignalRunnable} for the specified
* {@link LazyMessage}.
*
* @param lazyMessage
* the {@link LazyMessage} to signal {@link MessageListener}s with
* @return the newly allocated {@link SignalRunnable}
*/
private SignalRunnable<MessageListener<T>> newSignalRunnable(final LazyMessage<T> lazyMessage) {
return new SignalRunnable<MessageListener<T>>() {
@Override
public void run(MessageListener<T> messageListener) {
messageListener.onNewMessage(lazyMessage.get());
}
};
}
/**
* @param enabled
* {@code true} if latch mode should be enabled, {@code false}
* otherwise
*/
public void setLatchMode(boolean enabled) {
latchMode = enabled;
}
/**
* @return {@code true} if latch mode is enabled, {@code false} otherwise
*/
public boolean getLatchMode() {
return latchMode;
}
@Override
public void loop() throws InterruptedException {
LazyMessage<T> lazyMessage = lazyMessages.takeFirst();
synchronized (mutex) {
latchedMessage = lazyMessage;
if (DEBUG) {
log.info("Dispatching message: " + latchedMessage.get());
}
messageListeners.signal(newSignalRunnable(latchedMessage));
}
}
@Override
protected void handleInterruptedException(InterruptedException e) {
messageListeners.shutdown();
}
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.queue;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.ChannelGroupFuture;
import org.jboss.netty.channel.group.ChannelGroupFutureListener;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.ros.concurrent.CancellableLoop;
import org.ros.concurrent.CircularBlockingDeque;
import org.ros.internal.message.MessageBufferPool;
import org.ros.internal.message.MessageBuffers;
import org.ros.message.MessageSerializer;
import java.util.concurrent.ExecutorService;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class OutgoingMessageQueue<T> {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(OutgoingMessageQueue.class);
private static final int DEQUE_CAPACITY = 16;
private final MessageSerializer<T> serializer;
private final CircularBlockingDeque<T> deque;
private final ChannelGroup channelGroup;
private final Writer writer;
private final MessageBufferPool messageBufferPool;
private final ChannelBuffer latchedBuffer;
private final Object mutex;
private boolean latchMode;
private T latchedMessage;
private final class Writer extends CancellableLoop {
@Override
public void loop() throws InterruptedException {
T message = deque.takeFirst();
final ChannelBuffer buffer = messageBufferPool.acquire();
serializer.serialize(message, buffer);
if (DEBUG) {
log.info(String.format("Writing %d bytes to %d channels.", buffer.readableBytes(),
channelGroup.size()));
}
// Note that the buffer is automatically "duplicated" by Netty to avoid
// race conditions. However, the duplicated buffer and the original buffer
// share the same backing array. So, we have to wait until the write
// operation is complete before returning the buffer to the pool.
channelGroup.write(buffer).addListener(new ChannelGroupFutureListener() {
@Override
public void operationComplete(ChannelGroupFuture future) throws Exception {
messageBufferPool.release(buffer);
}
});
}
}
public OutgoingMessageQueue(MessageSerializer<T> serializer, ExecutorService executorService) {
this.serializer = serializer;
deque = new CircularBlockingDeque<T>(DEQUE_CAPACITY);
channelGroup = new DefaultChannelGroup();
writer = new Writer();
messageBufferPool = new MessageBufferPool();
latchedBuffer = MessageBuffers.dynamicBuffer();
mutex = new Object();
latchMode = false;
executorService.execute(writer);
}
public void setLatchMode(boolean enabled) {
latchMode = enabled;
}
public boolean getLatchMode() {
return latchMode;
}
/**
* @param message
* the message to add to the queue
*/
public void add(T message) {
deque.addLast(message);
setLatchedMessage(message);
}
private void setLatchedMessage(T message) {
synchronized (mutex) {
latchedMessage = message;
}
}
/**
* Stop writing messages and close all outgoing connections.
*/
public void shutdown() {
writer.cancel();
channelGroup.close().awaitUninterruptibly();
}
/**
* @param channel
* added to this {@link OutgoingMessageQueue}'s {@link ChannelGroup}
*/
public void addChannel(Channel channel) {
if (!writer.isRunning()) {
log.warn("Failed to add channel. Cannot add channels after shutdown.");
return;
}
if (latchMode && latchedMessage != null) {
writeLatchedMessage(channel);
}
channelGroup.add(channel);
}
// TODO(damonkohler): Avoid re-serializing the latched message if it hasn't
// changed.
private void writeLatchedMessage(Channel channel) {
synchronized (mutex) {
latchedBuffer.clear();
serializer.serialize(latchedMessage, latchedBuffer);
channel.write(latchedBuffer);
}
}
/**
* @return the number of {@link Channel}s which have been added to this queue
*/
public int getNumberOfChannels() {
return channelGroup.size();
}
@VisibleForTesting
public ChannelGroup getChannelGroup() {
return channelGroup;
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides internal classes that are core to the implementation of rosjava.
* <p>
* These classes should _not_ be used directly outside of the org.ros package.
*/
package org.ros.internal.transport; | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport;
import java.util.Collection;
import com.google.common.collect.Sets;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public interface ProtocolNames {
public static final String TCPROS = "TCPROS";
public static final String UDPROS = "UDPROS";
public static final Collection<String> SUPPORTED = Sets.newHashSet(TCPROS);
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.ros.exception.RosRuntimeException;
import java.io.IOException;
import java.nio.channels.Channels;
/**
* Adds new {@link Channels} to the provided {@link ChannelGroup}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class ConnectionTrackingHandler extends SimpleChannelHandler {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(ConnectionTrackingHandler.class);
/**
* The channel group the connection is to be part of.
*/
private final ChannelGroup channelGroup;
public ConnectionTrackingHandler(ChannelGroup channelGroup) {
this.channelGroup = channelGroup;
}
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
if (DEBUG) {
log.info("Channel opened: " + e.getChannel());
}
channelGroup.add(e.getChannel());
super.channelOpen(ctx, e);
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
if (DEBUG) {
log.info("Channel closed: " + e.getChannel());
}
super.channelClosed(ctx, e);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
ctx.getChannel().close();
if (e.getCause() instanceof IOException) {
// NOTE(damonkohler): We ignore exceptions here because they are common
// (e.g. network failure, connection reset by peer, shutting down, etc.)
// and should not be fatal. However, in all cases the channel should be
// closed.
if (DEBUG) {
log.error("Channel exception: " + ctx.getChannel(), e.getCause());
} else {
log.error("Channel exception: " + e.getCause());
}
} else {
throw new RosRuntimeException(e.getCause());
}
}
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.tcp;
import org.ros.address.AdvertiseAddress;
import org.ros.internal.transport.ProtocolDescription;
import org.ros.internal.transport.ProtocolNames;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class TcpRosProtocolDescription extends ProtocolDescription {
public TcpRosProtocolDescription(AdvertiseAddress address) {
super(ProtocolNames.TCPROS, address);
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.tcp;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
import org.ros.internal.node.service.ServiceManager;
import org.ros.internal.node.topic.TopicParticipantManager;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class TcpServerPipelineFactory extends ConnectionTrackingChannelPipelineFactory {
public static final String LENGTH_FIELD_BASED_FRAME_DECODER = "LengthFieldBasedFrameDecoder";
public static final String LENGTH_FIELD_PREPENDER = "LengthFieldPrepender";
public static final String HANDSHAKE_HANDLER = "HandshakeHandler";
private final TopicParticipantManager topicParticipantManager;
private final ServiceManager serviceManager;
public TcpServerPipelineFactory(ChannelGroup channelGroup,
TopicParticipantManager topicParticipantManager, ServiceManager serviceManager) {
super(channelGroup);
this.topicParticipantManager = topicParticipantManager;
this.serviceManager = serviceManager;
}
@Override
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = super.getPipeline();
pipeline.addLast(LENGTH_FIELD_PREPENDER, new LengthFieldPrepender(4));
pipeline.addLast(LENGTH_FIELD_BASED_FRAME_DECODER, new LengthFieldBasedFrameDecoder(
Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast(HANDSHAKE_HANDLER, new TcpServerHandshakeHandler(topicParticipantManager,
serviceManager));
return pipeline;
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides internal classes for implementing TCPROS.
* <p>
* These classes should _not_ be used directly outside of the org.ros package.
*
* @see <a href="http://www.ros.org/wiki/ROS/TCPROS">TCPROS documentation</a>
*/
package org.ros.internal.transport.tcp; | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.tcp;
import com.google.common.base.Preconditions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.HeapChannelBufferFactory;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.ros.address.AdvertiseAddress;
import org.ros.address.BindAddress;
import org.ros.internal.node.service.ServiceManager;
import org.ros.internal.node.topic.TopicParticipantManager;
import java.net.InetSocketAddress;
import java.nio.ByteOrder;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
/**
* The TCP server which is used for data communication between publishers and
* subscribers or between a service and a service client.
*
* <p>
* This server is used after publishers, subscribers, services and service
* clients have been told about each other by the master.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class TcpRosServer {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(TcpRosServer.class);
private final BindAddress bindAddress;
private final AdvertiseAddress advertiseAddress;
private final TopicParticipantManager topicParticipantManager;
private final ServiceManager serviceManager;
private final ScheduledExecutorService executorService;
private ChannelFactory channelFactory;
private ServerBootstrap bootstrap;
private Channel outgoingChannel;
private ChannelGroup incomingChannelGroup;
public TcpRosServer(BindAddress bindAddress, AdvertiseAddress advertiseAddress,
TopicParticipantManager topicParticipantManager, ServiceManager serviceManager,
ScheduledExecutorService executorService) {
this.bindAddress = bindAddress;
this.advertiseAddress = advertiseAddress;
this.topicParticipantManager = topicParticipantManager;
this.serviceManager = serviceManager;
this.executorService = executorService;
}
public void start() {
Preconditions.checkState(outgoingChannel == null);
channelFactory = new NioServerSocketChannelFactory(executorService, executorService);
bootstrap = new ServerBootstrap(channelFactory);
bootstrap.setOption("child.bufferFactory",
new HeapChannelBufferFactory(ByteOrder.LITTLE_ENDIAN));
bootstrap.setOption("child.keepAlive", true);
incomingChannelGroup = new DefaultChannelGroup();
bootstrap.setPipelineFactory(new TcpServerPipelineFactory(incomingChannelGroup,
topicParticipantManager, serviceManager));
outgoingChannel = bootstrap.bind(bindAddress.toInetSocketAddress());
advertiseAddress.setPortCallable(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return ((InetSocketAddress) outgoingChannel.getLocalAddress()).getPort();
}
});
if (DEBUG) {
log.info("Bound to: " + bindAddress);
log.info("Advertising: " + advertiseAddress);
}
}
/**
* Close all incoming connections and the server socket.
*
* <p>
* Calling this method more than once has no effect.
*/
public void shutdown() {
if (DEBUG) {
log.info("Shutting down: " + getAddress());
}
if (outgoingChannel != null) {
outgoingChannel.close().awaitUninterruptibly();
}
incomingChannelGroup.close().awaitUninterruptibly();
// NOTE(damonkohler): We are purposely not calling
// channelFactory.releaseExternalResources() or
// bootstrap.releaseExternalResources() since only external resources are
// the ExecutorService and control of that must remain with the overall
// application.
outgoingChannel = null;
}
/**
* @return the advertise-able {@link InetSocketAddress} of this
* {@link TcpRosServer}
*/
public InetSocketAddress getAddress() {
return advertiseAddress.toInetSocketAddress();
}
/**
* @return the {@link AdvertiseAddress} of this {@link TcpRosServer}
*/
public AdvertiseAddress getAdvertiseAddress() {
return advertiseAddress;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.tcp;
import com.google.common.collect.Lists;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import java.net.SocketAddress;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Executor;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class TcpClientManager {
private final ChannelGroup channelGroup;
private final Collection<TcpClient> tcpClients;
private final List<NamedChannelHandler> namedChannelHandlers;
private final Executor executor;
public TcpClientManager(Executor executor) {
this.executor = executor;
channelGroup = new DefaultChannelGroup();
tcpClients = Lists.newArrayList();
namedChannelHandlers = Lists.newArrayList();
}
public void addNamedChannelHandler(NamedChannelHandler namedChannelHandler) {
namedChannelHandlers.add(namedChannelHandler);
}
public void addAllNamedChannelHandlers(List<NamedChannelHandler> namedChannelHandlers) {
this.namedChannelHandlers.addAll(namedChannelHandlers);
}
/**
* Connects to a server.
* <p>
* This call blocks until the connection is established or fails.
*
* @param connectionName
* the name of the new connection
* @param socketAddress
* the {@link SocketAddress} to connect to
* @return a new {@link TcpClient}
*/
public TcpClient connect(String connectionName, SocketAddress socketAddress) {
TcpClient tcpClient = new TcpClient(channelGroup, executor);
tcpClient.addAllNamedChannelHandlers(namedChannelHandlers);
tcpClient.connect(connectionName, socketAddress);
tcpClients.add(tcpClient);
return tcpClient;
}
/**
* Sets all {@link TcpClientConnection}s as non-persistent and closes all open
* {@link Channel}s.
*/
public void shutdown() {
channelGroup.close().awaitUninterruptibly();
tcpClients.clear();
// We don't call channelFactory.releaseExternalResources() or
// bootstrap.releaseExternalResources() since the only external resource is
// the ExecutorService which must remain in the control of the overall
// application.
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.tcp;
import org.jboss.netty.channel.SimpleChannelHandler;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public abstract class AbstractNamedChannelHandler extends SimpleChannelHandler implements
NamedChannelHandler {
@Override
public String toString() {
return String.format("NamedChannelHandler<%s, %s>", getName(), super.toString());
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.tcp;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class TcpClientPipelineFactory extends ConnectionTrackingChannelPipelineFactory {
public static final String LENGTH_FIELD_BASED_FRAME_DECODER = "LengthFieldBasedFrameDecoder";
public static final String LENGTH_FIELD_PREPENDER = "LengthFieldPrepender";
public TcpClientPipelineFactory(ChannelGroup channelGroup) {
super(channelGroup);
}
@Override
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = super.getPipeline();
pipeline.addLast(LENGTH_FIELD_PREPENDER, new LengthFieldPrepender(4));
pipeline.addLast(LENGTH_FIELD_BASED_FRAME_DECODER, new LengthFieldBasedFrameDecoder(
Integer.MAX_VALUE, 0, 4, 0, 4));
return pipeline;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.tcp;
import com.google.common.base.Preconditions;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.ros.exception.RosRuntimeException;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.internal.node.service.DefaultServiceServer;
import org.ros.internal.node.service.ServiceManager;
import org.ros.internal.node.service.ServiceResponseEncoder;
import org.ros.internal.node.topic.DefaultPublisher;
import org.ros.internal.node.topic.SubscriberIdentifier;
import org.ros.internal.node.topic.TopicIdentifier;
import org.ros.internal.node.topic.TopicParticipantManager;
import org.ros.internal.transport.ConnectionHeader;
import org.ros.internal.transport.ConnectionHeaderFields;
import org.ros.namespace.GraphName;
/**
* A {@link ChannelHandler} which will process the TCP server handshake.
*
* @author damonkohler@google.com (Damon Kohler)
* @author kwc@willowgarage.com (Ken Conley)
*/
public class TcpServerHandshakeHandler extends SimpleChannelHandler {
private final TopicParticipantManager topicParticipantManager;
private final ServiceManager serviceManager;
public TcpServerHandshakeHandler(TopicParticipantManager topicParticipantManager,
ServiceManager serviceManager) {
this.topicParticipantManager = topicParticipantManager;
this.serviceManager = serviceManager;
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
ChannelBuffer incomingBuffer = (ChannelBuffer) e.getMessage();
ChannelPipeline pipeline = e.getChannel().getPipeline();
ConnectionHeader incomingHeader = ConnectionHeader.decode(incomingBuffer);
if (incomingHeader.hasField(ConnectionHeaderFields.SERVICE)) {
handleServiceHandshake(e, pipeline, incomingHeader);
} else {
handleSubscriberHandshake(ctx, e, pipeline, incomingHeader);
}
}
private void handleServiceHandshake(MessageEvent e, ChannelPipeline pipeline,
ConnectionHeader incomingHeader) {
GraphName serviceName = GraphName.of(incomingHeader.getField(ConnectionHeaderFields.SERVICE));
Preconditions.checkState(serviceManager.hasServer(serviceName));
DefaultServiceServer<?, ?> serviceServer = serviceManager.getServer(serviceName);
e.getChannel().write(serviceServer.finishHandshake(incomingHeader));
String probe = incomingHeader.getField(ConnectionHeaderFields.PROBE);
if (probe != null && probe.equals("1")) {
e.getChannel().close();
} else {
pipeline.replace(TcpServerPipelineFactory.LENGTH_FIELD_PREPENDER, "ServiceResponseEncoder",
new ServiceResponseEncoder());
pipeline.replace(this, "ServiceRequestHandler", serviceServer.newRequestHandler());
}
}
private void handleSubscriberHandshake(ChannelHandlerContext ctx, MessageEvent e,
ChannelPipeline pipeline, ConnectionHeader incomingConnectionHeader)
throws InterruptedException, Exception {
Preconditions.checkState(incomingConnectionHeader.hasField(ConnectionHeaderFields.TOPIC),
"Handshake header missing field: " + ConnectionHeaderFields.TOPIC);
GraphName topicName =
GraphName.of(incomingConnectionHeader.getField(ConnectionHeaderFields.TOPIC));
Preconditions.checkState(topicParticipantManager.hasPublisher(topicName),
"No publisher for topic: " + topicName);
DefaultPublisher<?> publisher = topicParticipantManager.getPublisher(topicName);
ChannelBuffer outgoingBuffer = publisher.finishHandshake(incomingConnectionHeader);
Channel channel = ctx.getChannel();
ChannelFuture future = channel.write(outgoingBuffer).await();
if (!future.isSuccess()) {
throw new RosRuntimeException(future.getCause());
}
String nodeName = incomingConnectionHeader.getField(ConnectionHeaderFields.CALLER_ID);
publisher.addSubscriber(new SubscriberIdentifier(NodeIdentifier.forName(nodeName),
new TopicIdentifier(topicName)), channel);
// Once the handshake is complete, there will be nothing incoming on the
// channel. So, we replace the handshake handler with a handler which will
// drop everything.
pipeline.replace(this, "DiscardHandler", new SimpleChannelHandler());
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.tcp;
import org.jboss.netty.channel.ChannelDownstreamHandler;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelUpstreamHandler;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public interface NamedChannelHandler extends ChannelUpstreamHandler, ChannelDownstreamHandler {
/**
* @return the name of this {@link ChannelHandler}
*/
String getName();
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.tcp;
import static org.jboss.netty.channel.Channels.pipeline;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.ros.internal.transport.ConnectionTrackingHandler;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ConnectionTrackingChannelPipelineFactory implements ChannelPipelineFactory {
public static final String CONNECTION_TRACKING_HANDLER = "ConnectionTrackingHandler";
private final ConnectionTrackingHandler connectionTrackingHandler;
public ConnectionTrackingChannelPipelineFactory(ChannelGroup channelGroup){
this.connectionTrackingHandler = new ConnectionTrackingHandler(channelGroup);
}
@Override
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = pipeline();
pipeline.addLast(CONNECTION_TRACKING_HANDLER, connectionTrackingHandler);
return pipeline;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport.tcp;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferFactory;
import org.jboss.netty.buffer.HeapChannelBufferFactory;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.ros.exception.RosRuntimeException;
import java.net.SocketAddress;
import java.nio.ByteOrder;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class TcpClient {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(TcpClient.class);
private static final int DEFAULT_CONNECTION_TIMEOUT_DURATION = 5;
private static final TimeUnit DEFAULT_CONNECTION_TIMEOUT_UNIT = TimeUnit.SECONDS;
private static final boolean DEFAULT_KEEP_ALIVE = true;
private final ChannelGroup channelGroup;
private final ChannelFactory channelFactory;
private final ChannelBufferFactory channelBufferFactory;
private final ClientBootstrap bootstrap;
private final List<NamedChannelHandler> namedChannelHandlers;
private Channel channel;
public TcpClient(ChannelGroup channelGroup, Executor executor) {
this.channelGroup = channelGroup;
channelFactory = new NioClientSocketChannelFactory(executor, executor);
channelBufferFactory = new HeapChannelBufferFactory(ByteOrder.LITTLE_ENDIAN);
bootstrap = new ClientBootstrap(channelFactory);
bootstrap.setOption("bufferFactory", channelBufferFactory);
setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT_DURATION, DEFAULT_CONNECTION_TIMEOUT_UNIT);
setKeepAlive(DEFAULT_KEEP_ALIVE);
namedChannelHandlers = Lists.newArrayList();
}
public void setConnectionTimeout(long duration, TimeUnit unit) {
bootstrap.setOption("connectionTimeoutMillis", TimeUnit.MILLISECONDS.convert(duration, unit));
}
public void setKeepAlive(boolean value) {
bootstrap.setOption("keepAlive", value);
}
public void addNamedChannelHandler(NamedChannelHandler namedChannelHandler) {
namedChannelHandlers.add(namedChannelHandler);
}
public void addAllNamedChannelHandlers(List<NamedChannelHandler> namedChannelHandlers) {
this.namedChannelHandlers.addAll(namedChannelHandlers);
}
public Channel connect(String connectionName, SocketAddress socketAddress) {
TcpClientPipelineFactory tcpClientPipelineFactory = new TcpClientPipelineFactory(channelGroup) {
@Override
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = super.getPipeline();
for (NamedChannelHandler namedChannelHandler : namedChannelHandlers) {
pipeline.addLast(namedChannelHandler.getName(), namedChannelHandler);
}
return pipeline;
}
};
bootstrap.setPipelineFactory(tcpClientPipelineFactory);
ChannelFuture future = bootstrap.connect(socketAddress).awaitUninterruptibly();
if (future.isSuccess()) {
channel = future.getChannel();
if (DEBUG) {
log.info("Connected to: " + socketAddress);
}
} else {
// We expect the first connection to succeed. If not, fail fast.
throw new RosRuntimeException("Connection exception: " + socketAddress, future.getCause());
}
return channel;
}
public ChannelFuture write(ChannelBuffer buffer) {
Preconditions.checkNotNull(channel);
Preconditions.checkNotNull(buffer);
return channel.write(buffer);
}
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport;
import java.net.InetSocketAddress;
import java.util.List;
import org.ros.address.AdvertiseAddress;
import com.google.common.collect.Lists;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ProtocolDescription {
private final String name;
private final AdvertiseAddress address;
public ProtocolDescription(String name, AdvertiseAddress address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public AdvertiseAddress getAdverstiseAddress() {
return address;
}
public InetSocketAddress getAddress() {
return address.toInetSocketAddress();
}
public List<Object> toList() {
return Lists.newArrayList((Object) name, address.getHost(), address.getPort());
}
@Override
public String toString() {
return "Protocol<" + name + ", " + getAdverstiseAddress() + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProtocolDescription other = (ProtocolDescription) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport;
/**
* Fields found inside the header for node to node communication.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public interface ConnectionHeaderFields {
public static final String CALLER_ID = "callerid";
public static final String TOPIC = "topic";
public static final String MD5_CHECKSUM = "md5sum";
public static final String TYPE = "type";
public static final String SERVICE = "service";
public static final String TCP_NODELAY = "tcp_nodelay";
public static final String LATCHING = "latching";
public static final String PERSISTENT = "persistent";
public static final String MESSAGE_DEFINITION = "message_definition";
public static final String ERROR = "error";
public static final String PROBE = "probe";
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport;
/**
* Encapsulates client-side transport handshake logic.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public interface ClientHandshake {
/**
* @param incommingConnectionHeader
* the {@link ConnectionHeader} sent by the server
* @return {@code true} if the handshake is successful, {@code false}
* otherwise
*/
boolean handshake(ConnectionHeader incommingConnectionHeader);
/**
* @return the outgoing {@link ConnectionHeader}
*/
ConnectionHeader getOutgoingConnectionHeader();
/**
* @return the error {@link String} returned by the server if an error occurs,
* {@code null} otherwise
*/
String getErrorMessage();
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.buffer.ChannelBuffer;
import org.ros.exception.RosRuntimeException;
import org.ros.internal.message.MessageBuffers;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ConnectionHeader {
private static final boolean DEBUG = false;
private static final Log log = LogFactory.getLog(ConnectionHeader.class);
private final Map<String, String> fields;
/**
* Decodes a header that came over the wire into a {@link Map} of fields and
* values.
*
* @param buffer
* the incoming {@link ChannelBuffer} containing the header
* @return a {@link Map} of header fields and values
*/
public static ConnectionHeader decode(ChannelBuffer buffer) {
Map<String, String> fields = Maps.newHashMap();
int position = 0;
int readableBytes = buffer.readableBytes();
while (position < readableBytes) {
int fieldSize = buffer.readInt();
position += 4;
if (fieldSize == 0) {
throw new IllegalStateException("Invalid 0 length handshake header field.");
}
if (position + fieldSize > readableBytes) {
throw new IllegalStateException("Invalid line length handshake header field.");
}
String field = decodeAsciiString(buffer, fieldSize);
position += field.length();
Preconditions.checkState(field.indexOf("=") > 0,
String.format("Invalid field in handshake header: \"%s\"", field));
String[] keyAndValue = field.split("=");
if (keyAndValue.length == 1) {
fields.put(keyAndValue[0], "");
} else {
fields.put(keyAndValue[0], keyAndValue[1]);
}
}
if (DEBUG) {
log.info("Decoded header: " + fields);
}
ConnectionHeader connectionHeader = new ConnectionHeader();
connectionHeader.mergeFields(fields);
return connectionHeader;
}
private static String decodeAsciiString(ChannelBuffer buffer, int length) {
return buffer.readBytes(length).toString(Charset.forName("US-ASCII"));
}
public ConnectionHeader() {
this.fields = Maps.newConcurrentMap();
}
/**
* Encodes this {@link ConnectionHeader} for transmission over the wire.
*
* @return a {@link ChannelBuffer} containing the encoded header for wire
* transmission
*/
public ChannelBuffer encode() {
ChannelBuffer buffer = MessageBuffers.dynamicBuffer();
for (Entry<String, String> entry : fields.entrySet()) {
String field = entry.getKey() + "=" + entry.getValue();
buffer.writeInt(field.length());
buffer.writeBytes(field.getBytes(Charset.forName("US-ASCII")));
}
return buffer;
}
public void merge(ConnectionHeader other) {
Map<String, String> otherFields = other.getFields();
mergeFields(otherFields);
}
public void mergeFields(Map<String, String> other) {
for (Entry<String, String> field : other.entrySet()) {
String name = field.getKey();
String value = field.getValue();
addField(name, value);
}
}
public void addField(String name, String value) {
if (!fields.containsKey(name) || fields.get(name).equals(value)) {
fields.put(name, value);
} else {
throw new RosRuntimeException(String.format("Unable to merge field %s: %s != %s", name,
value, fields.get(name)));
}
}
public Map<String, String> getFields() {
return Collections.unmodifiableMap(fields);
}
public boolean hasField(String name) {
return fields.containsKey(name);
}
public String getField(String name) {
return fields.get(name);
}
@Override
public String toString() {
return String.format("ConnectionHeader <%s>", fields.toString());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((fields == null) ? 0 : fields.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ConnectionHeader other = (ConnectionHeader) obj;
if (fields == null) {
if (other.fields != null)
return false;
} else if (!fields.equals(other.fields))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.transport;
/**
* A listener for handshake events.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public interface ClientHandshakeListener {
/**
* Called when the {@link ClientHandshake} completes successfully.
*
* @param outgoingConnectionHeader
* @param incomingConnectionHeader
*/
void onSuccess(ConnectionHeader outgoingConnectionHeader,
ConnectionHeader incomingConnectionHeader);
/**
* Called when the {@link ClientHandshake} fails.
*
* @param outgoingConnectionHeader
* @param errorMessage
*/
void onFailure(ConnectionHeader outgoingConnectionHeader, String errorMessage);
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.exception;
/**
* Thrown when a requested parameter does not match the requested parameter
* type.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class ParameterClassCastException extends RosRuntimeException {
public ParameterClassCastException(String message) {
super(message);
}
public ParameterClassCastException(String message, Throwable throwable) {
super(message, throwable);
}
public ParameterClassCastException(Throwable throwable) {
super(throwable);
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.exception;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class DuplicateServiceException extends RosRuntimeException {
public DuplicateServiceException(final String message) {
super(message);
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.exception;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceException extends Exception {
public ServiceException(final Throwable throwable) {
super(throwable);
}
public ServiceException(final String message, final Throwable throwable) {
super(message, throwable);
}
public ServiceException(final String message) {
super(message);
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.exception;
import org.ros.internal.node.response.StatusCode;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class RemoteException extends RosRuntimeException {
private final StatusCode statusCode;
public RemoteException(StatusCode statusCode, String message) {
super(message);
this.statusCode = statusCode;
}
/**
* @return the status code
*/
public StatusCode getStatusCode() {
return statusCode;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.exception;
/**
* Thrown when a requested parameter is not found.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class ParameterNotFoundException extends RosRuntimeException {
public ParameterNotFoundException(String message) {
super(message);
}
public ParameterNotFoundException(String message, Throwable throwable) {
super(message, throwable);
}
public ParameterNotFoundException(Throwable throwable) {
super(throwable);
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.exception;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceNotFoundException extends RosException {
public ServiceNotFoundException(final Throwable throwable) {
super(throwable);
}
public ServiceNotFoundException(final String message, final Throwable throwable) {
super(message, throwable);
}
public ServiceNotFoundException(final String message) {
super(message);
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.concurrent;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class WallTimeRate implements Rate {
private final long delay;
private long time;
public WallTimeRate(int hz) {
delay = 1000 / hz;
time = 0;
}
@Override
public void sleep() {
long delta = System.currentTimeMillis() - time;
while (delta < delay) {
try {
Thread.sleep(delay - delta);
} catch (InterruptedException e) {
break;
}
delta = System.currentTimeMillis() - time;
}
time = System.currentTimeMillis();
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.concurrent;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class DroppedEntryException extends Exception {
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides utility classes for common concurrent programming operations.
*/
package org.ros.concurrent; | Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.concurrent;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A deque that removes head or tail elements when the number of elements
* exceeds the limit and blocks on {@link #takeFirst()} and {@link #takeLast()} when
* there are no elements available.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class CircularBlockingDeque<T> implements Iterable<T> {
private final T[] deque;
private final Object mutex;
/**
* The maximum number of entries in the queue.
*/
private final int limit;
/**
* Points to the next entry that will be returned by {@link #takeFirst()} unless
* {@link #isEmpty()}.
*/
private int start;
/**
* The number of entries in the queue.
*/
private int length;
/**
* @param capacity
* the maximum number of elements allowed in the queue
*/
@SuppressWarnings("unchecked")
public CircularBlockingDeque(int capacity) {
deque = (T[]) new Object[capacity];
mutex = new Object();
limit = capacity;
start = 0;
length = 0;
}
/**
* Adds the specified entry to the tail of the queue, overwriting older
* entries if necessary.
*
* @param entry
* the entry to add
* @return {@code true}
*/
public boolean addLast(T entry) {
synchronized (mutex) {
deque[(start + length) % limit] = entry;
if (length == limit) {
start = (start + 1) % limit;
} else {
length++;
}
mutex.notify();
}
return true;
}
/**
* Adds the specified entry to the tail of the queue, overwriting older
* entries if necessary.
*
* @param entry
* the entry to add
* @return {@code true}
*/
public boolean addFirst(T entry) {
synchronized (mutex) {
if (start - 1 < 0) {
start = limit - 1;
} else {
start--;
}
deque[start] = entry;
if (length < limit) {
length++;
}
mutex.notify();
}
return true;
}
/**
* Retrieves the head of the queue, blocking if necessary until an entry is
* available.
*
* @return the head of the queue
* @throws InterruptedException
*/
public T takeFirst() throws InterruptedException {
T entry;
synchronized (mutex) {
while (true) {
if (length > 0) {
entry = deque[start];
start = (start + 1) % limit;
length--;
break;
}
mutex.wait();
}
}
return entry;
}
/**
* Retrieves, but does not remove, the head of this queue, returning
* {@code null} if this queue is empty.
*
* @return the head of this queue, or {@code null} if this queue is empty
*/
public T peekFirst() {
synchronized (mutex) {
if (length > 0) {
return deque[start];
}
return null;
}
}
/**
* Retrieves the tail of the queue, blocking if necessary until an entry is
* available.
*
* @return the tail of the queue
* @throws InterruptedException
*/
public T takeLast() throws InterruptedException {
T entry;
synchronized (mutex) {
while (true) {
if (length > 0) {
entry = deque[(start + length - 1) % limit];
length--;
break;
}
mutex.wait();
}
}
return entry;
}
/**
* Retrieves, but does not remove, the tail of this queue, returning
* {@code null} if this queue is empty.
*
* @return the tail of this queue, or {@code null} if this queue is empty
*/
public T peekLast() {
synchronized (mutex) {
if (length > 0) {
return deque[(start + length - 1) % limit];
}
return null;
}
}
public boolean isEmpty() {
return length == 0;
}
/**
* Returns an iterator over the queue.
* <p>
* Note that this is not thread-safe and that {@link Iterator#remove()} is
* unsupported.
*
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
int offset = 0;
@Override
public boolean hasNext() {
return offset < length;
}
@Override
public T next() {
if (offset == length) {
throw new NoSuchElementException();
}
T entry = deque[(start + offset) % limit];
offset++;
return entry;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.concurrent;
import com.google.common.base.Preconditions;
import java.util.concurrent.ExecutorService;
/**
* An interruptable loop that can be run by an {@link ExecutorService}.
*
* @author khughes@google.com (Keith M. Hughes)
*/
public abstract class CancellableLoop implements Runnable {
private final Object mutex;
/**
* {@code true} if the code has been run once, {@code false} otherwise.
*/
private boolean ranOnce = false;
/**
* The {@link Thread} the code will be running in.
*/
private Thread thread;
public CancellableLoop() {
mutex = new Object();
}
@Override
public void run() {
synchronized (mutex) {
Preconditions.checkState(!ranOnce, "CancellableLoops cannot be restarted.");
ranOnce = true;
thread = Thread.currentThread();
}
try {
setup();
while (!thread.isInterrupted()) {
loop();
}
} catch (InterruptedException e) {
handleInterruptedException(e);
} finally {
thread = null;
}
}
/**
* The setup block for the loop. This will be called exactly once before
* the first call to {@link #loop()}.
*/
protected void setup() {
}
/**
* The body of the loop. This will run continuously until the
* {@link CancellableLoop} has been interrupted externally or by calling
* {@link #cancel()}.
*/
protected abstract void loop() throws InterruptedException;
/**
* An {@link InterruptedException} was thrown.
*/
protected void handleInterruptedException(InterruptedException e) {
}
/**
* Interrupts the loop.
*/
public void cancel() {
if (thread != null) {
thread.interrupt();
}
}
/**
* @return {@code true} if the loop is running
*/
public boolean isRunning() {
return thread != null && !thread.isInterrupted();
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.