code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.xmlrpc.client; import org.apache.xmlrpc.common.XmlRpcStreamRequestProcessor; /** Another local transport factory for debugging and testing. This one is * similar to the {@link org.apache.xmlrpc.client.XmlRpcLocalTransportFactory}, * except that it adds request serialization. In other words, it is * particularly well suited for development and testing of XML serialization * and parsing. */ public class XmlRpcLocalStreamTransportFactory extends XmlRpcStreamTransportFactory { private final XmlRpcStreamRequestProcessor server; /** Creates a new instance. * @param pClient The client controlling the factory. * @param pServer An instance of {@link XmlRpcStreamRequestProcessor}. */ public XmlRpcLocalStreamTransportFactory(XmlRpcClient pClient, XmlRpcStreamRequestProcessor pServer) { super(pClient); server = pServer; } public XmlRpcTransport getTransport() { return new XmlRpcLocalStreamTransport(getClient(), server); } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.xmlrpc.client; /** <p>A transport factory being used for local XML-RPC calls. Local XML-RPC * calls are mainly useful for development and unit testing: Both client * and server are runing within the same JVM and communication is implemented * in simple method invokcations.</p> * <p>This class is thread safe and the returned instance of * {@link org.apache.xmlrpc.client.XmlRpcTransport} will always return the * same object, an instance of {@link XmlRpcLocalTransport}</p> */ public class XmlRpcLocalTransportFactory extends XmlRpcTransportFactoryImpl { /** Creates a new instance, operated by the given client. * @param pClient The client, which will invoke the factory. */ public XmlRpcLocalTransportFactory(XmlRpcClient pClient) { super(pClient); } private final XmlRpcTransport LOCAL_TRANSPORT = new XmlRpcLocalTransport(getClient()); public XmlRpcTransport getTransport() { return LOCAL_TRANSPORT; } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.xmlrpc.client; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.XmlRpcRequest; import org.apache.xmlrpc.common.XmlRpcController; import org.apache.xmlrpc.common.XmlRpcWorker; /** Object, which performs a request on the clients behalf. * The client maintains a pool of workers. The main purpose of the * pool is limitation of the maximum number of concurrent requests. * @since 3.0 */ public class XmlRpcClientWorker implements XmlRpcWorker { private final XmlRpcClientWorkerFactory factory; /** Creates a new instance. * @param pFactory The factory, which is being notified, if * the worker's ready. */ public XmlRpcClientWorker(XmlRpcClientWorkerFactory pFactory) { factory = pFactory; } public XmlRpcController getController() { return factory.getController(); } /** Performs a synchronous request. * @param pRequest The request being performed. * @return The requests result. * @throws XmlRpcException Performing the request failed. */ public Object execute(XmlRpcRequest pRequest) throws XmlRpcException { try { XmlRpcClient client = (XmlRpcClient) getController(); return client.getTransportFactory().getTransport().sendRequest(pRequest); } finally { factory.releaseWorker(this); } } protected Thread newThread(Runnable pRunnable) { Thread result = new Thread(pRunnable); result.setDaemon(true); return result; } /** Performs an synchronous request. * @param pRequest The request being performed. * @param pCallback The callback being invoked, when the request is finished. */ public void execute(final XmlRpcRequest pRequest, final AsyncCallback pCallback) { Runnable runnable = new Runnable(){ public void run(){ Object result = null; Throwable th = null; try { XmlRpcClient client = (XmlRpcClient) getController(); result = client.getTransportFactory().getTransport().sendRequest(pRequest); } catch (Throwable t) { th = t; } factory.releaseWorker(XmlRpcClientWorker.this); if (th == null) { pCallback.handleResult(pRequest, result); } else { pCallback.handleError(pRequest, th); } } }; newThread(runnable).start(); } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.xmlrpc.client; import java.io.Serializable; import java.net.URL; import org.apache.xmlrpc.common.XmlRpcHttpRequestConfigImpl; import org.apache.xmlrpc.common.XmlRpcRequestProcessor; /** Default implementation of a clients request configuration. */ public class XmlRpcClientConfigImpl extends XmlRpcHttpRequestConfigImpl implements XmlRpcHttpClientConfig, XmlRpcLocalClientConfig, Cloneable, Serializable { private static final long serialVersionUID = 4121131450507800889L; private URL serverURL; private XmlRpcRequestProcessor xmlRpcServer; private String userAgent; /** Creates a new client configuration with default settings. */ public XmlRpcClientConfigImpl() { } /** Creates a clone of this client configuration. * @return A clone of this configuration. */ public XmlRpcClientConfigImpl cloneMe() { try { return (XmlRpcClientConfigImpl) clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Unable to create my clone"); } } /** Sets the servers URL. * @param pURL Servers URL */ public void setServerURL(URL pURL) { serverURL = pURL; } public URL getServerURL() { return serverURL; } /** Returns the {@link XmlRpcRequestProcessor} being invoked. * @param pServer Server object being invoked. This will typically * be a singleton instance, but could as well create a new * instance with any call. */ public void setXmlRpcServer(XmlRpcRequestProcessor pServer) { xmlRpcServer = pServer; } public XmlRpcRequestProcessor getXmlRpcServer() { return xmlRpcServer; } /** * Returns the user agent header to use * @return the http user agent header to set when doing xmlrpc requests */ public String getUserAgent() { return userAgent; } /** * @param pUserAgent the http user agent header to set when doing xmlrpc requests */ public void setUserAgent(String pUserAgent) { userAgent = pUserAgent; } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.xmlrpc.client; /** Abstract base implementation of an {@link XmlRpcTransportFactory}. */ public abstract class XmlRpcTransportFactoryImpl implements XmlRpcTransportFactory { private final XmlRpcClient client; /** Creates a new instance. * @param pClient The client, which will invoke the factory. */ protected XmlRpcTransportFactoryImpl(XmlRpcClient pClient) { client = pClient; } /** Returns the client operating this factory. * @return The client. */ public XmlRpcClient getClient() { return client; } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.xmlrpc.client; import org.apache.xmlrpc.common.XmlRpcWorker; import org.apache.xmlrpc.common.XmlRpcWorkerFactory; /** A worker factory for the client, creating instances of * {@link org.apache.xmlrpc.client.XmlRpcClientWorker}. */ public class XmlRpcClientWorkerFactory extends XmlRpcWorkerFactory { /** Creates a new instance. * @param pClient The factory controller. */ public XmlRpcClientWorkerFactory(XmlRpcClient pClient) { super(pClient); } /** Creates a new worker instance. * @return New instance of {@link XmlRpcClientWorker}. */ protected XmlRpcWorker newWorker() { return new XmlRpcClientWorker(this); } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.xmlrpc.client; import org.apache.commons.httpclient.HttpClient; /** An HTTP transport factory, which is based on the Jakarta Commons * HTTP Client. */ public class XmlRpcCommonsTransportFactory extends XmlRpcTransportFactoryImpl { private HttpClient httpClient; /** Creates a new instance. * @param pClient The client, which is controlling the factory. */ public XmlRpcCommonsTransportFactory(XmlRpcClient pClient) { super(pClient); } public XmlRpcTransport getTransport() { return new XmlRpcCommonsTransport(this); } /** * <p>Sets the factories {@link HttpClient}. By default, a new instance * of {@link HttpClient} is created for any request.</p> * <p>Reusing the {@link HttpClient} is required, if you want to preserve * some state between requests. This applies, in particular, if you want * to use cookies: In that case, create an instance of {@link HttpClient}, * give it to the factory, and use {@link HttpClient#getState()} to * read or set cookies. */ public void setHttpClient(HttpClient pHttpClient) { httpClient = pHttpClient; } /** * <p>Returns the factories {@link HttpClient}. By default, a new instance * of {@link HttpClient} is created for any request.</p> * <p>Reusing the {@link HttpClient} is required, if you want to preserve * some state between requests. This applies, in particular, if you want * to use cookies: In that case, create an instance of {@link HttpClient}, * give it to the factory, and use {@link HttpClient#getState()} to * read or set cookies. */ public HttpClient getHttpClient() { return httpClient; } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.xmlrpc.client; import java.util.List; import org.apache.xmlrpc.XmlRpcConfig; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.XmlRpcRequest; import org.apache.xmlrpc.common.XmlRpcController; import org.apache.xmlrpc.common.XmlRpcWorkerFactory; import org.apache.xmlrpc.serializer.XmlWriterFactory; /** <p>The main access point of an XML-RPC client. This object serves mainly * as an object factory. It is designed with singletons in mind: Basically, * an application should be able to hold a single instance of * <code>XmlRpcClient</code> in a static variable, unless you would be * working with different factories.</p> * <p>Until Apache XML-RPC 2.0, this object was used both as an object * factory and as a place, where configuration details (server URL, * suggested encoding, user credentials and the like) have been stored. * In Apache XML-RPC 3.0, the configuration details has been moved to * the {@link org.apache.xmlrpc.client.XmlRpcClientConfig} object. * The configuration object is designed for being passed through the * actual worker methods.</p> * <p>A configured XmlRpcClient object is thread safe: In other words, * the suggested use is, that you configure the client using * {@link #setTransportFactory(XmlRpcTransportFactory)} and similar * methods, store it in a field and never modify it again. Without * modifications, the client may be used for an arbitrary number * of concurrent requests.</p> * @since 3.0 */ public class XmlRpcClient extends XmlRpcController { private XmlRpcTransportFactory transportFactory = XmlRpcClientDefaults.newTransportFactory(this); private XmlRpcClientConfig config = XmlRpcClientDefaults.newXmlRpcClientConfig(); private XmlWriterFactory xmlWriterFactory = XmlRpcClientDefaults.newXmlWriterFactory(); protected XmlRpcWorkerFactory getDefaultXmlRpcWorkerFactory() { return new XmlRpcClientWorkerFactory(this); } /** Sets the clients default configuration. This configuration * is used by the methods * {@link #execute(String, List)}, * {@link #execute(String, Object[])}, and * {@link #execute(XmlRpcRequest)}. * You may overwrite this per request by using * {@link #execute(XmlRpcClientConfig, String, List)}, * or {@link #execute(XmlRpcClientConfig, String, Object[])}. * @param pConfig The default request configuration. */ public void setConfig(XmlRpcClientConfig pConfig) { config = pConfig; } /** Returns the clients default configuration. This configuration * is used by the methods * {@link #execute(String, List)}, * {@link #execute(String, Object[])}. * You may overwrite this per request by using * {@link #execute(XmlRpcClientConfig, String, List)}, * or {@link #execute(XmlRpcClientConfig, String, Object[])}. * @return The default request configuration. */ public XmlRpcConfig getConfig() { return config; } /** Returns the clients default configuration. Shortcut for * <code>(XmlRpcClientConfig) getConfig()</code>. * This configuration is used by the methods * {@link #execute(String, List)}, * {@link #execute(String, Object[])}. * You may overwrite this per request by using * {@link #execute(XmlRpcClientConfig, String, List)}, or * {@link #execute(XmlRpcClientConfig, String, Object[])} * @return The default request configuration. */ public XmlRpcClientConfig getClientConfig() { return config; } /** Sets the clients transport factory. The client will invoke the * factory method {@link XmlRpcTransportFactory#getTransport()} * for any request. * @param pFactory The clients transport factory. */ public void setTransportFactory(XmlRpcTransportFactory pFactory) { transportFactory = pFactory; } /** Returns the clients transport factory. The client will use this factory * for invocation of {@link XmlRpcTransportFactory#getTransport()} * for any request. * @return The clients transport factory. */ public XmlRpcTransportFactory getTransportFactory() { return transportFactory; } /** Performs a request with the clients default configuration. * @param pMethodName The method being performed. * @param pParams The parameters. * @return The result object. * @throws XmlRpcException Performing the request failed. */ public Object execute(String pMethodName, Object[] pParams) throws XmlRpcException { return execute(getClientConfig(), pMethodName, pParams); } /** Performs a request with the given configuration. * @param pConfig The request configuration. * @param pMethodName The method being performed. * @param pParams The parameters. * @return The result object. * @throws XmlRpcException Performing the request failed. */ public Object execute(XmlRpcClientConfig pConfig, String pMethodName, Object[] pParams) throws XmlRpcException { return execute(new XmlRpcClientRequestImpl(pConfig, pMethodName, pParams)); } /** Performs a request with the clients default configuration. * @param pMethodName The method being performed. * @param pParams The parameters. * @return The result object. * @throws XmlRpcException Performing the request failed. */ public Object execute(String pMethodName, List pParams) throws XmlRpcException { return execute(getClientConfig(), pMethodName, pParams); } /** Performs a request with the given configuration. * @param pConfig The request configuration. * @param pMethodName The method being performed. * @param pParams The parameters. * @return The result object. * @throws XmlRpcException Performing the request failed. */ public Object execute(XmlRpcClientConfig pConfig, String pMethodName, List pParams) throws XmlRpcException { return execute(new XmlRpcClientRequestImpl(pConfig, pMethodName, pParams)); } /** Performs a request with the clients default configuration. * @param pRequest The request being performed. * @return The result object. * @throws XmlRpcException Performing the request failed. */ public Object execute(XmlRpcRequest pRequest) throws XmlRpcException { return getWorkerFactory().getWorker().execute(pRequest); } /** Performs an asynchronous request with the clients default configuration. * @param pMethodName The method being performed. * @param pParams The parameters. * @param pCallback The callback being notified when the request is finished. * @throws XmlRpcException Performing the request failed. */ public void executeAsync(String pMethodName, Object[] pParams, AsyncCallback pCallback) throws XmlRpcException { executeAsync(getClientConfig(), pMethodName, pParams, pCallback); } /** Performs an asynchronous request with the given configuration. * @param pConfig The request configuration. * @param pMethodName The method being performed. * @param pParams The parameters. * @param pCallback The callback being notified when the request is finished. * @throws XmlRpcException Performing the request failed. */ public void executeAsync(XmlRpcClientConfig pConfig, String pMethodName, Object[] pParams, AsyncCallback pCallback) throws XmlRpcException { executeAsync(new XmlRpcClientRequestImpl(pConfig, pMethodName, pParams), pCallback); } /** Performs an asynchronous request with the clients default configuration. * @param pMethodName The method being performed. * @param pParams The parameters. * @param pCallback The callback being notified when the request is finished. * @throws XmlRpcException Performing the request failed. */ public void executeAsync(String pMethodName, List pParams, AsyncCallback pCallback) throws XmlRpcException { executeAsync(getClientConfig(), pMethodName, pParams, pCallback); } /** Performs an asynchronous request with the given configuration. * @param pConfig The request configuration. * @param pMethodName The method being performed. * @param pParams The parameters. * @param pCallback The callback being notified when the request is finished. * @throws XmlRpcException Performing the request failed. */ public void executeAsync(XmlRpcClientConfig pConfig, String pMethodName, List pParams, AsyncCallback pCallback) throws XmlRpcException { executeAsync(new XmlRpcClientRequestImpl(pConfig, pMethodName, pParams), pCallback); } /** Performs a request with the clients default configuration. * @param pRequest The request being performed. * @param pCallback The callback being notified when the request is finished. * @throws XmlRpcException Performing the request failed. */ public void executeAsync(XmlRpcRequest pRequest, AsyncCallback pCallback) throws XmlRpcException { XmlRpcClientWorker w = (XmlRpcClientWorker) getWorkerFactory().getWorker(); w.execute(pRequest, pCallback); } /** Returns the clients instance of * {@link org.apache.xmlrpc.serializer.XmlWriterFactory}. * @return A factory for creating instances of * {@link org.apache.ws.commons.serialize.XMLWriter}. */ public XmlWriterFactory getXmlWriterFactory() { return xmlWriterFactory; } /** Sets the clients instance of * {@link org.apache.xmlrpc.serializer.XmlWriterFactory}. * @param pFactory A factory for creating instances of * {@link org.apache.ws.commons.serialize.XMLWriter}. */ public void setXmlWriterFactory(XmlWriterFactory pFactory) { xmlWriterFactory = pFactory; } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.xmlrpc.client; /** Factory for the lite HTTP transport, * {@link org.apache.xmlrpc.client.XmlRpcLiteHttpTransport}. */ public class XmlRpcLiteHttpTransportFactory extends XmlRpcTransportFactoryImpl { /** * Creates a new instance. * @param pClient The client, which will invoke the factory. */ public XmlRpcLiteHttpTransportFactory(XmlRpcClient pClient) { super(pClient); } public XmlRpcTransport getTransport() { return new XmlRpcLiteHttpTransport(getClient()); } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.xmlrpc.client; /** Abstract base implementation of an {@link org.apache.xmlrpc.client.XmlRpcTransport}. */ public abstract class XmlRpcTransportImpl implements XmlRpcTransport { private final XmlRpcClient client; /** Creates a new instance. * @param pClient The client, which creates the transport. */ protected XmlRpcTransportImpl(XmlRpcClient pClient) { client = pClient; } /** Returns the client, which created this transport. * @return The client. */ public XmlRpcClient getClient() { return client; } }
Java
package org.apache.xmlrpc.client; import org.apache.xmlrpc.XmlRpcException; /** * Exception thrown if the HTTP status code sent by the server * indicates that the request could not be processed. In * general, the 400 and 500 level HTTP status codes will * result in an XmlRpcHttpTransportException being thrown. */ public class XmlRpcHttpTransportException extends XmlRpcException { private static final long serialVersionUID = -6933992871198450027L; private final int status; private final String statusMessage; /** * Creates a new instance with the specified HTTP status code * and HTTP status message. * @param pCode The HTTP status code * @param pMessage The HTTP status message returned by the HTTP server */ public XmlRpcHttpTransportException(int pCode, String pMessage) { this(pCode, pMessage, "HTTP server returned unexpected status: " + pMessage); } /** * Construct a new XmlRpcHttpTransportException with the specified HTTP status code, * HTTP status message, and exception message. * @param httpStatusCode the HTTP status code * @param httpStatusMessage the HTTP status message returned by the HTTP server * @param message the exception message. */ public XmlRpcHttpTransportException(int httpStatusCode, String httpStatusMessage, String message) { super( message ); this.status = httpStatusCode; this.statusMessage = httpStatusMessage; } /** * Get the HTTP status code that resulted in this exception. * @return the HTTP status code that resulted in this exception. */ public int getStatusCode() { return status; } /** * Get the status message returned by the HTTP server. * @return the status message returned by the HTTP server. */ public String getStatusMessage() { return statusMessage; } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.xmlrpc.client; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.ConnectException; import java.net.Socket; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.XmlRpcRequest; import org.apache.xmlrpc.common.XmlRpcStreamRequestConfig; import org.apache.xmlrpc.util.HttpUtil; import org.apache.xmlrpc.util.LimitedInputStream; import org.xml.sax.SAXException; /** * A "light" HTTP transport implementation. */ public class XmlRpcLiteHttpTransport extends XmlRpcHttpTransport { private static final String userAgent = USER_AGENT + " (Lite HTTP Transport)"; private boolean ssl; private String hostname; private String host; private int port; private String uri; private Socket socket; private OutputStream output; private InputStream input; private final Map headers = new HashMap(); private boolean responseGzipCompressed = false; private XmlRpcHttpClientConfig config; /** * Creates a new instance. * @param pClient The client controlling this instance. */ public XmlRpcLiteHttpTransport(XmlRpcClient pClient) { super(pClient, userAgent); } public Object sendRequest(XmlRpcRequest pRequest) throws XmlRpcException { config = (XmlRpcHttpClientConfig) pRequest.getConfig(); URL url = config.getServerURL(); ssl = "https".equals(url.getProtocol()); hostname = url.getHost(); int p = url.getPort(); port = p < 1 ? 80 : p; String u = url.getFile(); uri = (u == null || "".equals(u)) ? "/" : u; host = port == 80 ? hostname : hostname + ":" + port; headers.put("Host", host); return super.sendRequest(pRequest); } protected void setRequestHeader(String pHeader, String pValue) { Object value = headers.get(pHeader); if (value == null) { headers.put(pHeader, pValue); } else { List list; if (value instanceof String) { list = new ArrayList(); list.add(value); headers.put(pHeader, list); } else { list = (List) value; } list.add(pValue); } } protected void close() throws XmlRpcClientException { IOException e = null; if (input != null) { try { input.close(); } catch (IOException ex) { e = ex; } } if (output != null) { try { output.close(); } catch (IOException ex) { if (e != null) { e = ex; } } } if (socket != null) { try { socket.close(); } catch (IOException ex) { if (e != null) { e = ex; } } } if (e != null) { throw new XmlRpcClientException("Failed to close connection: " + e.getMessage(), e); } } private OutputStream getOutputStream() throws XmlRpcException { try { final int retries = 3; final int delayMillis = 100; for (int tries = 0; ; tries++) { try { socket = newSocket(ssl, hostname, port); output = new BufferedOutputStream(socket.getOutputStream()){ /** Closing the output stream would close the whole socket, which we don't want, * because the don't want until the request is processed completely. * A close will later occur within * {@link XmlRpcLiteHttpTransport#close()}. */ public void close() throws IOException { flush(); socket.shutdownOutput(); } }; break; } catch (ConnectException e) { if (tries >= retries) { throw new XmlRpcException("Failed to connect to " + hostname + ":" + port + ": " + e.getMessage(), e); } else { try { Thread.sleep(delayMillis); } catch (InterruptedException ignore) { } } } } sendRequestHeaders(output); return output; } catch (IOException e) { throw new XmlRpcException("Failed to open connection to " + hostname + ":" + port + ": " + e.getMessage(), e); } } protected Socket newSocket(boolean pSSL, String pHostName, int pPort) throws UnknownHostException, IOException { if (pSSL) { throw new IOException("Unable to create SSL connections, use the XmlRpcLite14HttpTransportFactory."); } return new Socket(pHostName, pPort); } private byte[] toHTTPBytes(String pValue) throws UnsupportedEncodingException { return pValue.getBytes("US-ASCII"); } private void sendHeader(OutputStream pOut, String pKey, String pValue) throws IOException { pOut.write(toHTTPBytes(pKey + ": " + pValue + "\r\n")); } private void sendRequestHeaders(OutputStream pOut) throws IOException { pOut.write(("POST " + uri + " HTTP/1.0\r\n").getBytes("US-ASCII")); for (Iterator iter = headers.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); if (value instanceof String) { sendHeader(pOut, key, (String) value); } else { List list = (List) value; for (int i = 0; i < list.size(); i++) { sendHeader(pOut, key, (String) list.get(i)); } } } pOut.write(toHTTPBytes("\r\n")); } protected boolean isResponseGzipCompressed(XmlRpcStreamRequestConfig pConfig) { return responseGzipCompressed; } protected InputStream getInputStream() throws XmlRpcException { final byte[] buffer = new byte[2048]; try { // If reply timeout specified, set the socket timeout accordingly if (config.getReplyTimeout() != 0) socket.setSoTimeout(config.getReplyTimeout()); input = new BufferedInputStream(socket.getInputStream()); // start reading server response headers String line = HttpUtil.readLine(input, buffer); StringTokenizer tokens = new StringTokenizer(line); tokens.nextToken(); // Skip HTTP version String statusCode = tokens.nextToken(); String statusMsg = tokens.nextToken("\n\r"); final int code; try { code = Integer.parseInt(statusCode); } catch (NumberFormatException e) { throw new XmlRpcClientException("Server returned invalid status code: " + statusCode + " " + statusMsg, null); } if (code < 200 || code > 299) { throw new XmlRpcHttpTransportException(code, statusMsg); } int contentLength = -1; for (;;) { line = HttpUtil.readLine(input, buffer); if (line == null || "".equals(line)) { break; } line = line.toLowerCase(); if (line.startsWith("content-length:")) { contentLength = Integer.parseInt(line.substring("content-length:".length()).trim()); } else if (line.startsWith("content-encoding:")) { responseGzipCompressed = HttpUtil.isUsingGzipEncoding(line.substring("content-encoding:".length())); } } InputStream result; if (contentLength == -1) { result = input; } else { result = new LimitedInputStream(input, contentLength); } return result; } catch (IOException e) { throw new XmlRpcClientException("Failed to read server response: " + e.getMessage(), e); } } protected boolean isUsingByteArrayOutput(XmlRpcHttpClientConfig pConfig) { boolean result = super.isUsingByteArrayOutput(pConfig); if (!result) { throw new IllegalStateException("The Content-Length header is required with HTTP/1.0, and HTTP/1.1 is unsupported by the Lite HTTP Transport."); } return result; } protected void writeRequest(ReqWriter pWriter) throws XmlRpcException, IOException, SAXException { pWriter.write(getOutputStream()); } }
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; import static org.junit.Assert.assertEquals; import org.ros.namespace.GraphName; /** * @author damonkohler@google.com (Damon Kohler) */ public class Assert { public static void assertGraphNameEquals(String name, GraphName graphName) { assertEquals(name, graphName.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.address; /** * An {@link AdvertiseAddressFactory} which creates public (non-loopback) addresses. * * @author damonkohler@google.com (Damon Kohler) */ public class PublicAdvertiseAddressFactory implements AdvertiseAddressFactory { private final String host; public PublicAdvertiseAddressFactory() { this(InetAddressFactory.newNonLoopback().getCanonicalHostName()); } public PublicAdvertiseAddressFactory(String host) { this.host = host; } @Override public AdvertiseAddress newDefault() { return new AdvertiseAddress(host); } }
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.address; /** * @author damonkohler@google.com (Damon Kohler) */ public interface AdvertiseAddressFactory { AdvertiseAddress newDefault(); }
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 the classes for acquiring and representing network addresses. */ package org.ros.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.address; import com.google.common.base.Preconditions; import org.ros.exception.RosRuntimeException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; import java.util.concurrent.Callable; /** * A wrapper for {@link InetSocketAddress} that emphasizes the difference * between an address that should be used for binding a server port and one that * should be advertised to external entities. * * An {@link AdvertiseAddress} encourages lazy lookups of port information to * prevent accidentally storing a bind port (e.g. 0 for OS picked) instead of * the advertised port. * * @author damonkohler@google.com (Damon Kohler) */ public class AdvertiseAddress { private final String host; private Callable<Integer> portCallable; public static AdvertiseAddress newPrivate() { return new PrivateAdvertiseAddressFactory().newDefault(); } /** * Best effort method, returns a new {@link AdvertiseAddress} where the host * is determined automatically. * * @return a suitable {@link AdvertiseAddress} for a publicly accessible * {@link BindAddress} */ public static AdvertiseAddress newPublic() { return new PublicAdvertiseAddressFactory().newDefault(); } public AdvertiseAddress(String host) { Preconditions.checkNotNull(host); this.host = host; } public String getHost() { return host; } public void setStaticPort(final int port) { portCallable = new Callable<Integer>() { @Override public Integer call() throws Exception { return port; } }; } public int getPort() { try { return portCallable.call(); } catch (Exception e) { throw new RosRuntimeException(e); } } public void setPortCallable(Callable<Integer> portCallable) { this.portCallable = portCallable; } public InetAddress toInetAddress() { return InetAddressFactory.newFromHostString(host); } public InetSocketAddress toInetSocketAddress() { Preconditions.checkNotNull(portCallable); try { InetAddress address = toInetAddress(); return new InetSocketAddress(address, portCallable.call()); } catch (Exception e) { throw new RosRuntimeException(e); } } public URI toUri(String scheme) { Preconditions.checkNotNull(portCallable); try { return new URI(scheme, null, host, portCallable.call(), "/", null, null); } catch (Exception e) { throw new RosRuntimeException("Failed to create URI: " + this, e); } } public boolean isLoopbackAddress() { return toInetAddress().isLoopbackAddress(); } @Override public String toString() { Preconditions.checkNotNull(portCallable); try { return "AdvertiseAddress<" + host + ", " + portCallable.call() + ">"; } catch (Exception e) { throw new RosRuntimeException(e); } } @Override public int hashCode() { Preconditions.checkNotNull(portCallable); final int prime = 31; int result = 1; result = prime * result + ((host == null) ? 0 : host.hashCode()); try { result = prime * result + portCallable.call(); } catch (Exception e) { throw new RosRuntimeException(e); } return result; } @Override public boolean equals(Object obj) { Preconditions.checkNotNull(portCallable); if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AdvertiseAddress other = (AdvertiseAddress) obj; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; try { if (portCallable.call() != other.portCallable.call()) return false; } catch (Exception e) { throw new RosRuntimeException(e); } 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.address; import com.google.common.collect.Lists; import com.google.common.net.InetAddresses; import org.ros.exception.RosRuntimeException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * @author damonkohler@google.com (Damon Kohler) */ public class InetAddressFactory { private InetAddressFactory() { // Utility class } private static boolean isIpv4(InetAddress address) { return address.getAddress().length == 4; } private static Collection<InetAddress> getAllInetAddresses() { List<NetworkInterface> networkInterfaces; try { networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); } catch (SocketException e) { throw new RosRuntimeException(e); } List<InetAddress> inetAddresses = Lists.newArrayList(); for (NetworkInterface networkInterface : networkInterfaces) { inetAddresses.addAll(Collections.list(networkInterface.getInetAddresses())); } return inetAddresses; } public static InetAddress newNonLoopback() { for (InetAddress address : getAllInetAddresses()) { // IPv4 only for now. if (!address.isLoopbackAddress() && isIpv4(address)) { return address; } } throw new RosRuntimeException("No non-loopback interface found."); } private static Collection<InetAddress> getAllInetAddressByName(String host) { InetAddress[] allAddressesByName; try { allAddressesByName = org.xbill.DNS.Address.getAllByName(host); } catch (UnknownHostException unused) { try { allAddressesByName = InetAddress.getAllByName(host); } catch (UnknownHostException e) { throw new RosRuntimeException(e); } } return Arrays.asList(allAddressesByName); } /** * Creates an {@link InetAddress} with both an IP and a host set so that no * further resolving will take place. * * If an IP address string is specified, this method ensures that it will be * used in place of a host name. * * If a host name other than {@code Address.LOCALHOST} is specified, this * method trys to find a non-loopback IP associated with the supplied host * name. * * If the specified host name is {@code Address.LOCALHOST}, this method * returns a loopback address. * * @param host * @return an {@link InetAddress} with both an IP and a host set (no further * resolving will take place) */ public static InetAddress newFromHostString(String host) { try { if (InetAddresses.isInetAddress(host)) { return InetAddress.getByAddress(host, InetAddresses.forString(host).getAddress()); } if (host.equals(Address.LOCALHOST)) { return InetAddress.getByAddress(Address.LOCALHOST, InetAddresses .forString(Address.LOOPBACK).getAddress()); } } catch (UnknownHostException e) { throw new RosRuntimeException(e); } Collection<InetAddress> allAddressesByName = getAllInetAddressByName(host); // First, try to find a non-loopback IPv4 address. for (InetAddress address : allAddressesByName) { if (!address.isLoopbackAddress() && isIpv4(address)) { return address; } } // Return a loopback IPv4 address as a last resort. for (InetAddress address : allAddressesByName) { if (isIpv4(address)) { return address; } } throw new RosRuntimeException("Unable to construct InetAddress for host: " + host); } public static InetAddress newLoopback() { return newFromHostString(Address.LOOPBACK); } }
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.address; /** * @author damonkohler@google.com (Damon Kohler) */ public interface Address { public static final String LOOPBACK = "127.0.0.1"; public static final String LOCALHOST = "localhost"; }
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.address; import java.net.InetSocketAddress; /** * A wrapper for {@link InetSocketAddress} that emphasizes the difference * between an address that should be used for binding a server port and one that * should be advertised to external entities. * * @author kwc@willowgarage.com (Ken Conley) */ public class BindAddress { private final InetSocketAddress address; private BindAddress(InetSocketAddress address) { this.address = address; } /** * @param port the port to bind to * @return a {@link BindAddress} instance with specified port that will bind * to all network interfaces on the host */ public static BindAddress newPublic(int port) { return new BindAddress(new InetSocketAddress(port)); } public static BindAddress newPublic() { return newPublic(0); } /** * @param port the port to bind to * @return a {@link BindAddress} instance with specified port that will bind * to the loopback interface on the host */ public static BindAddress newPrivate(int port) { return new BindAddress(new InetSocketAddress(InetAddressFactory.newLoopback(), port)); } public static BindAddress newPrivate() { return newPrivate(0); } @Override public String toString() { return "BindAddress<" + address + ">"; } public InetSocketAddress toInetSocketAddress() { return address; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.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; BindAddress other = (BindAddress) obj; if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) 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.address; /** * @author damonkohler@google.com (Damon Kohler) */ public class PrivateAdvertiseAddressFactory implements AdvertiseAddressFactory { @Override public AdvertiseAddress newDefault() { return new AdvertiseAddress(Address.LOOPBACK); } }
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 the classes for dealing with time and clock synchronization. */ package org.ros.time;
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.time; import com.google.common.base.Preconditions; import org.ros.Topics; import org.ros.internal.node.DefaultNode; import org.ros.message.MessageListener; import org.ros.message.Time; import org.ros.node.topic.Subscriber; import rosgraph_msgs.Clock; /** * A {@link TimeProvider} for use when the ROS graph is configured for * simulation. * * @author damonkohler@google.com (Damon Kohler) */ public class ClockTopicTimeProvider implements TimeProvider { private final Subscriber<rosgraph_msgs.Clock> subscriber; private Object mutex; private rosgraph_msgs.Clock clock; public ClockTopicTimeProvider(DefaultNode defaultNode) { subscriber = defaultNode.newSubscriber(Topics.CLOCK, rosgraph_msgs.Clock._TYPE); mutex = new Object(); subscriber.addMessageListener(new MessageListener<Clock>() { @Override public void onNewMessage(Clock message) { synchronized (mutex) { clock = message; } } }); } public Subscriber<rosgraph_msgs.Clock> getSubscriber() { return subscriber; } @Override public Time getCurrentTime() { Preconditions.checkNotNull(clock); synchronized (mutex) { return new Time(clock.getClock()); } } }
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.time; import org.ros.message.Time; /** * Provide time. * * @author kwc@willowgarage.com (Ken Conley) */ public interface TimeProvider { /** * @return the current time of the system using rostime */ Time getCurrentTime(); }
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.time; 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.apache.commons.net.ntp.NTPUDPClient; import org.apache.commons.net.ntp.TimeInfo; import org.ros.math.CollectionMath; import org.ros.message.Duration; import org.ros.message.Time; import java.io.IOException; import java.net.InetAddress; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * Provides NTP synchronized wallclock (actual) time. * * @author damonkohler@google.com (Damon Kohler) */ public class NtpTimeProvider implements TimeProvider { private static final boolean DEBUG = false; private static final Log log = LogFactory.getLog(NtpTimeProvider.class); private static final int SAMPLE_SIZE = 11; private final InetAddress host; private final ScheduledExecutorService scheduledExecutorService; private final WallTimeProvider wallTimeProvider; private final NTPUDPClient ntpClient; private long offset; private ScheduledFuture<?> scheduledFuture; /** * @param host * the NTP host to use */ public NtpTimeProvider(InetAddress host, ScheduledExecutorService scheduledExecutorService) { this.host = host; this.scheduledExecutorService = scheduledExecutorService; wallTimeProvider = new WallTimeProvider(); ntpClient = new NTPUDPClient(); offset = 0; scheduledFuture = null; } /** * Update the current time offset from the configured NTP host. * * @throws IOException */ public void updateTime() throws IOException { List<Long> offsets = Lists.newArrayList(); for (int i = 0; i < SAMPLE_SIZE; i++) { offsets.add(computeOffset()); } offset = CollectionMath.median(offsets); log.info(String.format("NTP time offset: %d ms", offset)); } private long computeOffset() throws IOException { if (DEBUG) { log.info("Updating time offset from NTP server: " + host.getHostName()); } TimeInfo time; try { time = ntpClient.getTime(host); } catch (IOException e) { log.error("Failed to read time from NTP server: " + host.getHostName(), e); throw e; } time.computeDetails(); return time.getOffset(); } /** * Starts periodically updating the current time offset periodically. * * <p> * The first time update happens immediately. * * <p> * Note that errors thrown while periodically updating time will be logged but * not rethrown. * * @param period * time between updates * @param unit * unit of period */ public void startPeriodicUpdates(long period, TimeUnit unit) { scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { updateTime(); } catch (IOException e) { log.error("Periodic NTP update failed.", e); } } }, 0, period, unit); } /** * Stops periodically updating the current time offset. */ public void stopPeriodicUpdates() { Preconditions.checkNotNull(scheduledFuture); scheduledFuture.cancel(true); scheduledFuture = null; } @Override public Time getCurrentTime() { Time currentTime = wallTimeProvider.getCurrentTime(); return currentTime.add(Duration.fromMillis(offset)); } }
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.time; import com.google.common.annotations.VisibleForTesting; 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.ros.exception.RosRuntimeException; import java.util.Collections; import java.util.List; import java.util.Queue; import java.util.concurrent.Callable; /** * @author damonkohler@google.com (Damon Kohler) */ public class RemoteUptimeClock { private static final boolean DEBUG = false; private static final Log log = LogFactory.getLog(RemoteUptimeClock.class); private final LocalUptimeProvider localUptimeProvider; private final Callable<Double> callable; private final LatencyOutlierFilter latencyOutlierFilter; /** * Sensitivity values are used to sampleSize the effect of jitter. The value * should be in the range [0, 1] where 0 indicates that the current estimate * will never change (i.e. new measurements have no effect on estimates) and 1 * indicates that previous estimates have no effect on changes to the current * estimate. */ private final double driftSensitivity; /** * @see #driftSensitivity */ private final double errorReductionCoefficientSensitivity; private double localUptime; /** * Remote uptime is tracked as a pair of values: our previous measurement and * our prediction based on estimated drift. */ private double measuredRemoteUptime; /** * @see #measuredRemoteUptime */ private double predictedRemoteUptime; /** * Drift is measured in local uptime ticks per remote uptime tick. * * @see #calculateDrift(double, double) */ private double drift; /** * With {@link #drift} alone, it is possible to accumulate a constant error * that will never be corrected for. The {@link #errorReductionCoefficient} is * an additional term for removing this error. */ private double errorReductionCoefficient; /** * Represents a tuple of measurement values that represent a single point in * time. */ private final class UptimeCalculationResult { final double newLocalUptime; final double newRemoteUptime; final double latency; public UptimeCalculationResult(double newLocalUptime, double newRemoteUptime, double latency) { this.newLocalUptime = newLocalUptime; this.newRemoteUptime = newRemoteUptime; this.latency = latency; } } /** * Uses a sliding window and percentile range to detect latency outliers. * * <p> * When receiving remote uptime measurements, the latency of the measurement * is used to estimate the local uptime at the point when the remote uptime * was measured. This calculation assumes that any measurement latency is * symmetrical. The larger the latency, the larger the potential error in our * estimate of local uptime at the measured remote uptime. * * <p> * To reduce the effect of measurements with higher uncertainty, we filter out * measurements with latencies that exceed the specified percentile within our * sliding window. */ private final class LatencyOutlierFilter { private final int sampleSize; private final double threshold; private final Queue<Double> latencies; public LatencyOutlierFilter(int sampleSize, double threshold) { Preconditions.checkArgument(sampleSize > 0); Preconditions.checkArgument(threshold > 1); this.threshold = threshold; this.sampleSize = sampleSize; latencies = Lists.newLinkedList(); } /** * @param latency * @return {@code true} if the provided latency is outside the configured * percentile, {@code false} otherwise */ public boolean add(double latency) { latencies.add(latency); if (latencies.size() > sampleSize) { latencies.remove(); } else { // Until the sliding window is full, we cannot reliably detect outliers. return false; } double medianLatency = getMedian(); if (latency < medianLatency * threshold) { return false; } return true; } public double getMedian() { List<Double> ordered = Lists.newArrayList(latencies); Collections.sort(ordered); return ordered.get(latencies.size() / 2); } } @VisibleForTesting interface LocalUptimeProvider { double getSeconds(); } /** * The provided {@link Callable} should return the current * measuredRemoteUptime of the remote clock with minimal overhead since the * run time of this call will be used to further improve the estimation of * measuredRemoteUptime. * * @param timeProvider * the local time provider * @param callable * returns the current remote uptime in arbitrary units * @param driftSensitivity * the sensitivity to drift adjustments, must be in the range [0, 1] * @param errorReductionCoefficientSensitivity * the sensitivity to error reduction coefficient adjustments, must * be in the range [0, 1] * @return a new {@link RemoteUptimeClock} */ public static RemoteUptimeClock newDefault(final TimeProvider timeProvider, Callable<Double> callable, double driftSensitivity, double errorReductionCoefficientSensitivity, int latencyOutlierFilterSampleSize, double latencyOutlierFilterThreshold) { return new RemoteUptimeClock(new LocalUptimeProvider() { @Override public double getSeconds() { return timeProvider.getCurrentTime().toSeconds(); } }, callable, driftSensitivity, errorReductionCoefficientSensitivity, latencyOutlierFilterSampleSize, latencyOutlierFilterThreshold); } @VisibleForTesting RemoteUptimeClock(LocalUptimeProvider localUptimeProvider, Callable<Double> callable, double driftSensitivity, double errorReductionCoefficientSensitivity, int latencyOutlierFilterSampleSize, double latencyOutlierFilterThreshold) { Preconditions.checkArgument(driftSensitivity >= 0 && driftSensitivity <= 1); Preconditions.checkArgument(errorReductionCoefficientSensitivity >= 0 && errorReductionCoefficientSensitivity <= 1); this.localUptimeProvider = localUptimeProvider; this.callable = callable; this.driftSensitivity = driftSensitivity; this.errorReductionCoefficientSensitivity = errorReductionCoefficientSensitivity; latencyOutlierFilter = new LatencyOutlierFilter(latencyOutlierFilterSampleSize, latencyOutlierFilterThreshold); errorReductionCoefficient = 0; } /** * Good calibration settings will depend on the remote uptime provider. In * general, choosing a sample size around 10 and a delay that is large enough * to include more than 100 uptime ticks will give reasonable results. * * @param sampleSize * the number of samples to use for calibration * @param samplingDelayMillis * the delay in milliseconds between collecting each sample */ public void calibrate(int sampleSize, double samplingDelayMillis) { log.info("Starting calibration..."); double remoteUptimeSum = 0; double localUptimeSum = 0; double driftSum = 0; for (int i = 0; i < sampleSize; i++) { UptimeCalculationResult result = calculateNewUptime(callable); latencyOutlierFilter.add(result.latency); if (i > 0) { double localUptimeDelta = result.newLocalUptime - localUptime; double remoteUptimeDelta = result.newRemoteUptime - measuredRemoteUptime; driftSum += calculateDrift(localUptimeDelta, remoteUptimeDelta); } measuredRemoteUptime = result.newRemoteUptime; localUptime = result.newLocalUptime; remoteUptimeSum += measuredRemoteUptime; localUptimeSum += localUptime; try { Thread.sleep((long) samplingDelayMillis); } catch (InterruptedException e) { throw new RosRuntimeException(e); } } // We have n samples, but n - 1 intervals. errorReductionCoefficient is the // average interval magnitude. drift = driftSum / (sampleSize - 1); // If localUptime == -offset then measuredRemoteUptime == 0 (e.g. if // localUptime is 10s and measuredRemoteUptime is 5s, then offset should be // -5s since the localUptime started 5s earlier than measuredRemoteUptime). double offset = (drift * remoteUptimeSum - localUptimeSum) / sampleSize; predictedRemoteUptime = (localUptime + offset) / drift; log.info(String.format("Calibration complete. Drift: %.4g, Offset: %.4f s", drift, offset)); } /** * @see #drift * * @param localUptimeDelta * the delta between the two local uptimes that correspond to the two * remote uptimes used to determine {@code remoteUptimeDelta} * @param remoteUptimeDelta * the delta between the two remote uptimes that correspond to the * two local uptimes used to determine {@code localUptimeDelta} * @return the calculated drift */ private double calculateDrift(double localUptimeDelta, double remoteUptimeDelta) { Preconditions.checkState(remoteUptimeDelta > 1e-9); return localUptimeDelta / remoteUptimeDelta; } /** * Update this {@link RemoteUptimeClock} with the latest uptime from the * remote clock. * * <p> * This will update internal estimates of drift and error. Ideally, it should * be called periodically with a consistent time interval between updates * (e.g. 10 seconds). */ public void update() { UptimeCalculationResult result = calculateNewUptime(callable); double newLocalUptime = result.newLocalUptime; double newRemoteUptime = result.newRemoteUptime; double latency = result.latency; if (latencyOutlierFilter.add(latency)) { log.warn(String.format( "Measurement latency marked as outlier. Latency: %.4f s, Median: %.4f s", latency, latencyOutlierFilter.getMedian())); return; } double localUptimeDelta = newLocalUptime - localUptime; double remoteUptimeDelta = newRemoteUptime - measuredRemoteUptime; Preconditions.checkState(localUptimeDelta > 1e-9); Preconditions.checkState(remoteUptimeDelta > 1e-9); if (DEBUG) { log.info(String.format("localUptimeDelta: %.4g, remoteUptimeDelta: %.4g", localUptimeDelta, remoteUptimeDelta)); } double newDrift = driftSensitivity * (localUptimeDelta / remoteUptimeDelta) + (1 - driftSensitivity) * drift; // Non-jumping behavior from (localUptime, predictedRemoteUptime) to // (newLocalUptime, newAdjustedRemoteUptime). Note that it does not depend // directly on measuredRemoteUptime or newRemoteUptime. double newPredictedRemoteUptime = predictedRemoteUptime + (localUptimeDelta / (drift + errorReductionCoefficient)); double nextPredictedRemoteUptime = newRemoteUptime + remoteUptimeDelta; double newCombinedDriftAndError = localUptimeDelta / (nextPredictedRemoteUptime - newPredictedRemoteUptime); double newErrorReductionCoefficient = errorReductionCoefficientSensitivity * (newCombinedDriftAndError - newDrift); double deltaRatio = remoteUptimeDelta / localUptimeDelta; double error = newLocalUptime - toLocalUptime(newRemoteUptime); log.info(String.format("Latency: %.4f s, Delta ratio: %.4f, Drift: %.4g, " + "Error reduction coefficient: %.4g, Error: %.4f s", latency, deltaRatio, newDrift, newErrorReductionCoefficient, error)); measuredRemoteUptime = newRemoteUptime; predictedRemoteUptime = newPredictedRemoteUptime; localUptime = newLocalUptime; drift = newDrift; errorReductionCoefficient = newErrorReductionCoefficient; } /** * Creates a new {@link UptimeCalculationResult} where the local uptime has * been adjusted to compensate for latency while retrieving the remote uptime. * * @param callable * returns the remote uptime as quickly as possible * @return a new {@link UptimeCalculationResult} */ private UptimeCalculationResult calculateNewUptime(Callable<Double> callable) { double newLocalUptime = localUptimeProvider.getSeconds(); double newRemoteUptime; try { newRemoteUptime = callable.call(); } catch (Exception e) { log.error(e); throw new RosRuntimeException(e); } double latency = localUptimeProvider.getSeconds() - newLocalUptime; double latencyOffset = latency / 2; newLocalUptime += latencyOffset; return new UptimeCalculationResult(newLocalUptime, newRemoteUptime, latency); } /** * Returns the estimated local uptime in seconds for the given remote uptime. * * @param remoteUptime * the remote uptime to convert to local uptime * @return the estimated local uptime in seconds at the provided remote uptime */ public double toLocalUptime(double remoteUptime) { double localOffset = (drift + errorReductionCoefficient) * (remoteUptime - predictedRemoteUptime); return localUptime + localOffset; } @VisibleForTesting double getDrift() { return drift; } @VisibleForTesting double getErrorReductionCoefficient() { return errorReductionCoefficient; } }
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.time; import org.ros.message.Time; /** * Provides wallclock (actual) time. * * @author kwc@willowgarage.com (Ken Conley) */ public class WallTimeProvider implements TimeProvider { @Override public Time getCurrentTime() { return Time.fromMillis(System.currentTimeMillis()); } }
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; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import org.ros.exception.RosRuntimeException; import org.ros.internal.loader.CommandLineLoader; import org.ros.node.DefaultNodeMainExecutor; import org.ros.node.NodeConfiguration; import org.ros.node.NodeMain; import org.ros.node.NodeMainExecutor; /** * This is a main class entry point for executing {@link NodeMain}s. * * @author kwc@willowgarage.com (Ken Conley) * @author damonkohler@google.com (Damon Kohler) */ public class RosRun { public static void printUsage() { System.err.println("Usage: java -jar my_package.jar com.example.MyNodeMain [args]"); } public static void main(String[] argv) throws Exception { if (argv.length == 0) { printUsage(); System.exit(1); } CommandLineLoader loader = new CommandLineLoader(Lists.newArrayList(argv)); String nodeClassName = loader.getNodeClassName(); System.out.println("Loading node class: " + loader.getNodeClassName()); NodeConfiguration nodeConfiguration = loader.build(); NodeMain nodeMain = null; try { nodeMain = loader.loadClass(nodeClassName); } catch (ClassNotFoundException e) { throw new RosRuntimeException("Unable to locate node: " + nodeClassName, e); } catch (InstantiationException e) { throw new RosRuntimeException("Unable to instantiate node: " + nodeClassName, e); } catch (IllegalAccessException e) { throw new RosRuntimeException("Unable to instantiate node: " + nodeClassName, e); } Preconditions.checkState(nodeMain != null); NodeMainExecutor nodeMainExecutor = DefaultNodeMainExecutor.newDefault(); nodeMainExecutor.execute(nodeMain, nodeConfiguration); } }
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.node; /** * A {@link NodeMain} which provides empty defaults for all signals. * * @author damonkohler@google.com (Damon Kohler) */ public abstract class AbstractNodeMain implements NodeMain { @Override public void onStart(ConnectedNode connectedNode) { } @Override public void onShutdown(Node node) { } @Override public void onShutdownComplete(Node node) { } @Override public void onError(Node node, Throwable 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.node; import org.ros.namespace.GraphName; import org.ros.node.topic.Publisher; import org.ros.node.topic.Subscriber; /** * Encapsulates a {@link Node} with its associated program logic. * * <p> * {@link NodeMain} is the one required {@link NodeListener} for {@link Node} * creation. {@link NodeListener#onStart(ConnectedNode)} should be used to set up your * program's {@link Publisher}s, {@link Subscriber}s, etc. * * @author ethan.rublee@gmail.com (Ethan Rublee) * @author damonkohler@google.com (Damon Kohler) */ public interface NodeMain extends NodeListener { /** * @return the name of the {@link Node} that will be used if a name was not * specified in the {@link Node}'s associated * {@link NodeConfiguration} */ GraphName getDefaultNodeName(); }
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.node; /** * A {@link NodeListener} which provides empty defaults for all signals. * * @author damonkohler@google.com (Damon Kohler) */ public class DefaultNodeListener implements NodeListener { @Override public void onStart(ConnectedNode connectedNode) { } @Override public void onShutdown(Node node) { } @Override public void onShutdownComplete(Node node) { } @Override public void onError(Node node, Throwable 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.node; import org.apache.commons.logging.Log; import org.ros.concurrent.CancellableLoop; import org.ros.internal.node.xmlrpc.MasterXmlRpcEndpoint; import org.ros.message.MessageFactory; import org.ros.message.MessageSerializationFactory; import org.ros.namespace.GraphName; import org.ros.namespace.NodeNameResolver; import java.net.URI; import java.util.concurrent.ScheduledExecutorService; /** * A node in the ROS graph. * * @author khughes@google.com (Keith M. Hughes) */ public interface Node { /** * @return the fully resolved name of this {@link Node}, e.g. "/foo/bar/boop" */ GraphName getName(); /** * Resolve the given name, using ROS conventions, into a full ROS namespace * name. Will be relative to the current namespace unless the name is global. * * @param name * the name to resolve * @return fully resolved ros namespace name */ GraphName resolveName(GraphName name); /** * @see #resolveName(GraphName) */ GraphName resolveName(String name); /** * @return {@link NodeNameResolver} for this namespace */ NodeNameResolver getResolver(); /** * @return the {@link URI} of this {@link Node} */ URI getUri(); /** * @return {@link URI} of {@link MasterXmlRpcEndpoint} that this node is * attached to. */ URI getMasterUri(); /** * @return Logger for this node, which will also perform logging to /rosout. */ Log getLog(); /** * @return the {@link MessageSerializationFactory} used by this node */ MessageSerializationFactory getMessageSerializationFactory(); /** * @return the {@link MessageFactory} used by this node */ MessageFactory getTopicMessageFactory(); /** * @return the {@link MessageFactory} used by this node for service responses */ MessageFactory getServiceResponseMessageFactory(); /** * @return the {@link MessageFactory} used by this node for service requests */ MessageFactory getServiceRequestMessageFactory(); /** * Add a new {@link NodeListener} to the {@link Node}. * * @param listener * the {@link NodeListener} to add */ void addListener(NodeListener listener); /** * @return the {@link ScheduledExecutorService} that this {@link Node} uses */ ScheduledExecutorService getScheduledExecutorService(); /** * Executes a {@link CancellableLoop} using the {@link Node}'s * {@link ScheduledExecutorService}. The {@link CancellableLoop} will be * canceled when the {@link Node} starts shutting down. * * <p> * Any blocking calls executed in the provided {@link CancellableLoop} can * potentially delay {@link Node} shutdown and should be avoided. * * @param cancellableLoop * the {@link CancellableLoop} to execute */ void executeCancellableLoop(CancellableLoop cancellableLoop); /** * Shut the node down. */ void 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.node; import org.ros.internal.node.parameter.DefaultParameterTree; import org.ros.internal.node.server.NodeIdentifier; import org.ros.namespace.GraphName; import org.ros.namespace.NameResolver; import org.ros.node.parameter.ParameterListener; import org.ros.node.parameter.ParameterTree; import java.net.URI; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author damonkohler@google.com (Damon Kohler) */ public class AnonymousParmeterTree implements ParameterTree { private ParameterTree parameterTree; public AnonymousParmeterTree(URI masterUri) { NodeIdentifier nodeIdentifier = new NodeIdentifier(GraphName.of("invalid"), null); parameterTree = DefaultParameterTree.newFromNodeIdentifier(nodeIdentifier, masterUri, NameResolver.newRoot(), null); } @Override public boolean getBoolean(GraphName name) { return parameterTree.getBoolean(name); } @Override public boolean getBoolean(String name) { return parameterTree.getBoolean(name); } @Override public boolean getBoolean(GraphName name, boolean defaultValue) { return parameterTree.getBoolean(name, defaultValue); } @Override public boolean getBoolean(String name, boolean defaultValue) { return parameterTree.getBoolean(name, defaultValue); } @Override public int getInteger(GraphName name) { return parameterTree.getInteger(name); } @Override public int getInteger(String name) { return parameterTree.getInteger(name); } @Override public int getInteger(GraphName name, int defaultValue) { return parameterTree.getInteger(name, defaultValue); } @Override public int getInteger(String name, int defaultValue) { return parameterTree.getInteger(name, defaultValue); } @Override public double getDouble(GraphName name) { return parameterTree.getDouble(name); } @Override public double getDouble(String name) { return parameterTree.getDouble(name); } @Override public double getDouble(GraphName name, double defaultValue) { return parameterTree.getDouble(name, defaultValue); } @Override public double getDouble(String name, double defaultValue) { return parameterTree.getDouble(name, defaultValue); } @Override public String getString(GraphName name) { return parameterTree.getString(name); } @Override public String getString(String name) { return parameterTree.getString(name); } @Override public String getString(GraphName name, String defaultValue) { return parameterTree.getString(name, defaultValue); } @Override public String getString(String name, String defaultValue) { return parameterTree.getString(name, defaultValue); } @Override public List<?> getList(GraphName name) { return parameterTree.getList(name); } @Override public List<?> getList(String name) { return parameterTree.getList(name); } @Override public List<?> getList(GraphName name, List<?> defaultValue) { return parameterTree.getList(name, defaultValue); } @Override public List<?> getList(String name, List<?> defaultValue) { return parameterTree.getList(name, defaultValue); } @Override public Map<?, ?> getMap(GraphName name) { return parameterTree.getMap(name); } @Override public Map<?, ?> getMap(String name) { return parameterTree.getMap(name); } @Override public Map<?, ?> getMap(GraphName name, Map<?, ?> defaultValue) { return parameterTree.getMap(name, defaultValue); } @Override public Map<?, ?> getMap(String name, Map<?, ?> defaultValue) { return parameterTree.getMap(name, defaultValue); } @Override public void set(GraphName name, boolean value) { parameterTree.set(name, value); } @Override public void set(String name, boolean value) { parameterTree.set(name, value); } @Override public void set(GraphName name, int value) { parameterTree.set(name, value); } @Override public void set(String name, int value) { parameterTree.set(name, value); } @Override public void set(GraphName name, double value) { parameterTree.set(name, value); } @Override public void set(String name, double value) { parameterTree.set(name, value); } @Override public void set(GraphName name, String value) { parameterTree.set(name, value); } @Override public void set(String name, String value) { parameterTree.set(name, value); } @Override public void set(GraphName name, List<?> value) { parameterTree.set(name, value); } @Override public void set(String name, List<?> value) { parameterTree.set(name, value); } @Override public void set(GraphName name, Map<?, ?> value) { parameterTree.set(name, value); } @Override public void set(String name, Map<?, ?> value) { parameterTree.set(name, value); } @Override public boolean has(GraphName name) { return parameterTree.has(name); } @Override public boolean has(String name) { return parameterTree.has(name); } @Override public void delete(GraphName name) { parameterTree.delete(name); } @Override public void delete(String name) { parameterTree.delete(name); } @Override public GraphName search(GraphName name) { return parameterTree.search(name); } @Override public GraphName search(String name) { return parameterTree.search(name); } @Override public Collection<GraphName> getNames() { return parameterTree.getNames(); } /** * @throws UnsupportedOperationException */ @Override public void addParameterListener(GraphName name, ParameterListener listener) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ @Override public void addParameterListener(String name, ParameterListener listener) { 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 the classes for accessing and modifying parameters. * * @see <a href="http://ros.org/wiki/Parameter%20Server">parameter server documentation</a> */ package org.ros.node.parameter;
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.node.parameter; import org.ros.exception.ParameterClassCastException; import org.ros.exception.ParameterNotFoundException; import org.ros.internal.node.server.ParameterServer; import org.ros.namespace.GraphName; import java.util.Collection; import java.util.List; import java.util.Map; /** * Provides access to a {@link ParameterServer}. * * <p> * A parameter server is a shared, multi-variate dictionary that is accessible * via network APIs. Nodes use this server to store and retrieve parameters at * runtime. As it is not designed for high-performance, it is best used for * static, non-binary data such as configuration parameters. It is meant to be * globally viewable so that tools can easily inspect the configuration state of * the system and modify if necessary. * * @see <a href="http://www.ros.org/wiki/Parameter%20Server">Parameter server * documentation</a> * * @author damonkohler@google.com (Damon Kohler) */ public interface ParameterTree { /** * @param name * the parameter name * @return the parameter value * @throws ParameterNotFoundException * if the parameter is not found * @throws ParameterClassCastException * if the parameter is not the expected type */ boolean getBoolean(GraphName name); /** * @see #getBoolean(GraphName) */ boolean getBoolean(String name); /** * @param name * the parameter name * @param defaultValue * the default value * @return the parameter value or the default value if the parameter does not * exist * @throws ParameterClassCastException * if the parameter exists and is not the expected type */ boolean getBoolean(GraphName name, boolean defaultValue); /** * @see #getBoolean(GraphName, boolean) */ boolean getBoolean(String name, boolean defaultValue); /** * @param name * the parameter name * @return the parameter value * @throws ParameterNotFoundException * if the parameter is not found * @throws ParameterClassCastException * if the parameter is not the expected type */ int getInteger(GraphName name); /** * @see #getInteger(GraphName) */ int getInteger(String name); /** * @param name * the parameter name * @param defaultValue * the default value * @return the parameter value or the default value if the parameter does not * exist * @throws ParameterClassCastException * if the parameter exists and is not the expected type */ int getInteger(GraphName name, int defaultValue); /** * @see #getInteger(GraphName, int) */ int getInteger(String name, int defaultValue); /** * @param name * the parameter name * @return the parameter value * @throws ParameterNotFoundException * if the parameter is not found * @throws ParameterClassCastException * if the parameter is not the expected type */ double getDouble(GraphName name); /** * @see #getDouble(GraphName) */ double getDouble(String name); /** * @param name * the parameter name * @param defaultValue * the default value * @return the parameter value or the default value if the parameter does not * exist * @throws ParameterClassCastException * if the parameter exists and is not the expected type */ double getDouble(GraphName name, double defaultValue); /** * @see #getDouble(GraphName, double) */ double getDouble(String name, double defaultValue); /** * @param name * the parameter name * @return the parameter value:w * * @throws ParameterNotFoundException * if the parameter is not found * @throws ParameterClassCastException * if the parameter is not the expected type */ String getString(GraphName name); /** * @see #getString(GraphName) */ String getString(String name); /** * @param name * the parameter name * @param defaultValue * the default value * @return the parameter value or the default value if the parameter does not * exist * @throws ParameterClassCastException * if the parameter exists and is not the expected type */ String getString(GraphName name, String defaultValue); /** * @see #getString(GraphName, String) */ String getString(String name, String defaultValue); /** * @param name * the parameter name * @return the parameter value * @throws ParameterNotFoundException * if the parameter is not found * @throws ParameterClassCastException * if the parameter is not the expected type */ List<?> getList(GraphName name); /** * @see #getList(GraphName) */ List<?> getList(String name); /** * @param name * the parameter name * @param defaultValue * the default value * @return the parameter value or the default value if the parameter does not * exist * @throws ParameterClassCastException * if the parameter exists and is not the expected type */ List<?> getList(GraphName name, List<?> defaultValue); /** * @see #getList(GraphName, List) */ List<?> getList(String name, List<?> defaultValue); /** * @param name * the parameter name * @return the parameter value * @throws ParameterNotFoundException * if the parameter is not found * @throws ParameterClassCastException * if the parameter is not the expected type */ Map<?, ?> getMap(GraphName name); /** * @see #getMap(GraphName) */ Map<?, ?> getMap(String name); /** * @param name * the parameter name * @param defaultValue * the default value * @return the parameter value or the default value if the parameter does not * exist * @throws ParameterClassCastException * if the parameter exists and is not the expected type */ Map<?, ?> getMap(GraphName name, Map<?, ?> defaultValue); /** * @see #getMap(GraphName, Map) */ Map<?, ?> getMap(String name, Map<?, ?> defaultValue); /** * @param name * the parameter name * @param value * the value that the parameter will be set to */ void set(GraphName name, boolean value); /** * @see #set(GraphName, boolean) */ void set(String name, boolean value); /** * @param name * the parameter name * @param value * the value that the parameter will be set to */ void set(GraphName name, int value); /** * @see #set(GraphName, int) */ void set(String name, int value); /** * @param name * the parameter name * @param value * the value that the parameter will be set to */ void set(GraphName name, double value); /** * @see #set(GraphName, double) */ void set(String name, double value); /** * @param name * the parameter name * @param value * the value that the parameter will be set to */ void set(GraphName name, String value); /** * @see #set(GraphName, String) */ void set(String name, String value); /** * @param name * the parameter name * @param value * the value that the parameter will be set to */ void set(GraphName name, List<?> value); /** * @see #set(GraphName, List) */ void set(String name, List<?> value); /** * @param name * the parameter name * @param value * the value that the parameter will be set to */ void set(GraphName name, Map<?, ?> value); /** * @see #set(GraphName, Map) */ void set(String name, Map<?, ?> value); /** * @param name * the parameter name * @return {@code true} if a parameter with the given name exists, * {@code false} otherwise */ boolean has(GraphName name); /** * @see #has(GraphName) */ boolean has(String name); /** * Deletes a specified parameter. * * @param name * the parameter name */ void delete(GraphName name); /** * @see #delete(GraphName) */ void delete(String name); /** * Search for parameter key on the Parameter Server. Search starts in caller's * namespace and proceeds upwards through parent namespaces until the * {@link ParameterServer} finds a matching key. * * @param name * the parameter name to search for * @return the name of the found parameter or {@code null} if no matching * parameter was found */ GraphName search(GraphName name); /** * @see #search(GraphName) */ GraphName search(String name); /** * @return all known parameter names */ Collection<GraphName> getNames(); /** * Subscribes to changes to the specified parameter. * * @param name * the parameter name to subscribe to * @param listener * a {@link ParameterListener} that will be called when the * subscribed parameter changes */ void addParameterListener(GraphName name, ParameterListener listener); /** * @see #addParameterListener(GraphName, ParameterListener) */ void addParameterListener(String name, ParameterListener listener); }
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.node.parameter; /** * Called when a subscribed parameter value changes. * * @author damonkohler@google.com (Damon Kohler) */ public interface ParameterListener { /** * @param value * the new parameter value */ void onNewValue(Object value); }
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 the classes for creating and communicating with nodes in the ROS graph. * * @see <a href="http://ros.org/wiki/Nodes">nodes documentation</a> */ package org.ros.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.node; import org.ros.internal.message.definition.MessageDefinitionReflectionProvider; import org.ros.address.AdvertiseAddress; import org.ros.address.AdvertiseAddressFactory; import org.ros.address.BindAddress; import org.ros.address.PrivateAdvertiseAddressFactory; import org.ros.address.PublicAdvertiseAddressFactory; import org.ros.exception.RosRuntimeException; import org.ros.internal.message.DefaultMessageFactory; import org.ros.internal.message.DefaultMessageSerializationFactory; import org.ros.internal.message.service.ServiceDescriptionFactory; import org.ros.internal.message.service.ServiceRequestMessageFactory; import org.ros.internal.message.service.ServiceResponseMessageFactory; import org.ros.internal.message.topic.TopicDescriptionFactory; import org.ros.message.MessageDefinitionProvider; import org.ros.message.MessageFactory; import org.ros.message.MessageSerializationFactory; import org.ros.namespace.GraphName; import org.ros.namespace.NameResolver; import org.ros.time.TimeProvider; import org.ros.time.WallTimeProvider; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.concurrent.ScheduledExecutorService; /** * Stores configuration information (e.g. ROS master URI) for {@link Node}s. * * @see <a href="http://www.ros.org/wiki/ROS/Technical%20Overview#Node">Node * documentation</a> * * @author ethan.rublee@gmail.com (Ethan Rublee) * @author kwc@willowgarage.com (Ken Conley) * @author damonkohler@google.com (Damon Kohler) */ public class NodeConfiguration { /** * The default master {@link URI}. */ public static final URI DEFAULT_MASTER_URI; static { try { DEFAULT_MASTER_URI = new URI("http://localhost:11311/"); } catch (URISyntaxException e) { throw new RosRuntimeException(e); } } private NameResolver parentResolver; private URI masterUri; private File rosRoot; private List<File> rosPackagePath; private GraphName nodeName; private TopicDescriptionFactory topicDescriptionFactory; private MessageFactory topicMessageFactory; private ServiceDescriptionFactory serviceDescriptionFactory; private MessageFactory serviceRequestMessageFactory; private MessageFactory serviceResponseMessageFactory; private MessageSerializationFactory messageSerializationFactory; private BindAddress tcpRosBindAddress; private AdvertiseAddressFactory tcpRosAdvertiseAddressFactory; private BindAddress xmlRpcBindAddress; private AdvertiseAddressFactory xmlRpcAdvertiseAddressFactory; private ScheduledExecutorService scheduledExecutorService; private TimeProvider timeProvider; /** * @param nodeConfiguration * the {@link NodeConfiguration} to copy * @return a copy of the supplied {@link NodeConfiguration} */ public static NodeConfiguration copyOf(NodeConfiguration nodeConfiguration) { NodeConfiguration copy = new NodeConfiguration(); copy.parentResolver = nodeConfiguration.parentResolver; copy.masterUri = nodeConfiguration.masterUri; copy.rosRoot = nodeConfiguration.rosRoot; copy.rosPackagePath = nodeConfiguration.rosPackagePath; copy.nodeName = nodeConfiguration.nodeName; copy.topicDescriptionFactory = nodeConfiguration.topicDescriptionFactory; copy.topicMessageFactory = nodeConfiguration.topicMessageFactory; copy.serviceDescriptionFactory = nodeConfiguration.serviceDescriptionFactory; copy.serviceRequestMessageFactory = nodeConfiguration.serviceRequestMessageFactory; copy.serviceResponseMessageFactory = nodeConfiguration.serviceResponseMessageFactory; copy.messageSerializationFactory = nodeConfiguration.messageSerializationFactory; copy.tcpRosBindAddress = nodeConfiguration.tcpRosBindAddress; copy.tcpRosAdvertiseAddressFactory = nodeConfiguration.tcpRosAdvertiseAddressFactory; copy.xmlRpcBindAddress = nodeConfiguration.xmlRpcBindAddress; copy.xmlRpcAdvertiseAddressFactory = nodeConfiguration.xmlRpcAdvertiseAddressFactory; copy.scheduledExecutorService = nodeConfiguration.scheduledExecutorService; copy.timeProvider = nodeConfiguration.timeProvider; return copy; } /** * Creates a new {@link NodeConfiguration} for a publicly accessible * {@link Node}. * * @param host * the host that the {@link Node} will run on * @param masterUri * the {@link URI} for the master that the {@link Node} will register * with * @return a new {@link NodeConfiguration} for a publicly accessible * {@link Node} */ public static NodeConfiguration newPublic(String host, URI masterUri) { NodeConfiguration configuration = new NodeConfiguration(); configuration.setXmlRpcBindAddress(BindAddress.newPublic()); configuration.setXmlRpcAdvertiseAddressFactory(new PublicAdvertiseAddressFactory(host)); configuration.setTcpRosBindAddress(BindAddress.newPublic()); configuration.setTcpRosAdvertiseAddressFactory(new PublicAdvertiseAddressFactory(host)); configuration.setMasterUri(masterUri); return configuration; } /** * Creates a new {@link NodeConfiguration} for a publicly accessible * {@link Node}. * * @param host * the host that the {@link Node} will run on * @return a new {@link NodeConfiguration} for a publicly accessible * {@link Node} */ public static NodeConfiguration newPublic(String host) { return newPublic(host, DEFAULT_MASTER_URI); } /** * Creates a new {@link NodeConfiguration} for a {@link Node} that is only * accessible on the local host. * * @param masterUri * the {@link URI} for the master that the {@link Node} will register * with * @return a new {@link NodeConfiguration} for a private {@link Node} */ public static NodeConfiguration newPrivate(URI masterUri) { NodeConfiguration configuration = new NodeConfiguration(); configuration.setXmlRpcBindAddress(BindAddress.newPrivate()); configuration.setXmlRpcAdvertiseAddressFactory(new PrivateAdvertiseAddressFactory()); configuration.setTcpRosBindAddress(BindAddress.newPrivate()); configuration.setTcpRosAdvertiseAddressFactory(new PrivateAdvertiseAddressFactory()); configuration.setMasterUri(masterUri); return configuration; } /** * Creates a new {@link NodeConfiguration} for a {@link Node} that is only * accessible on the local host. * * @return a new {@link NodeConfiguration} for a private {@link Node} */ public static NodeConfiguration newPrivate() { return newPrivate(DEFAULT_MASTER_URI); } private NodeConfiguration() { MessageDefinitionProvider messageDefinitionProvider = new MessageDefinitionReflectionProvider(); setTopicDescriptionFactory(new TopicDescriptionFactory(messageDefinitionProvider)); setTopicMessageFactory(new DefaultMessageFactory(messageDefinitionProvider)); setServiceDescriptionFactory(new ServiceDescriptionFactory(messageDefinitionProvider)); setServiceRequestMessageFactory(new ServiceRequestMessageFactory(messageDefinitionProvider)); setServiceResponseMessageFactory(new ServiceResponseMessageFactory(messageDefinitionProvider)); setMessageSerializationFactory(new DefaultMessageSerializationFactory(messageDefinitionProvider)); setParentResolver(NameResolver.newRoot()); setTimeProvider(new WallTimeProvider()); } /** * @return the {@link NameResolver} for the {@link Node}'s parent namespace */ public NameResolver getParentResolver() { return parentResolver; } /** * @param resolver * the {@link NameResolver} for the {@link Node}'s parent namespace * @return this {@link NodeConfiguration} */ public NodeConfiguration setParentResolver(NameResolver resolver) { this.parentResolver = resolver; return this; } /** * @see <a * href="http://www.ros.org/wiki/ROS/EnvironmentVariables#ROS_MASTER_URI">ROS_MASTER_URI * documentation</a> * @return the {@link URI} of the master that the {@link Node} will register * with */ public URI getMasterUri() { return masterUri; } /** * @see <a * href="http://www.ros.org/wiki/ROS/EnvironmentVariables#ROS_MASTER_URI">ROS_MASTER_URI * documentation</a> * @param masterUri * the {@link URI} of the master that the {@link Node} will register * with * @return this {@link NodeConfiguration} */ public NodeConfiguration setMasterUri(URI masterUri) { this.masterUri = masterUri; return this; } /** * @see <a * href="http://www.ros.org/wiki/ROS/EnvironmentVariables#ROS_ROOT">ROS_ROOT * documentation</a> * @return the location where the ROS core packages are installed */ public File getRosRoot() { return rosRoot; } /** * @see <a * href="http://www.ros.org/wiki/ROS/EnvironmentVariables#ROS_ROOT">ROS_ROOT * documentation</a> * @param rosRoot * the location where the ROS core packages are installed * @return this {@link NodeConfiguration} */ public NodeConfiguration setRosRoot(File rosRoot) { this.rosRoot = rosRoot; return this; } /** * These ordered paths tell the ROS system where to search for more ROS * packages. If there are multiple packages of the same name, ROS will choose * the one that appears in the {@link List} first. * * @see <a * href="http://www.ros.org/wiki/ROS/EnvironmentVariables#ROS_PACKAGE_PATH">ROS_PACKAGE_PATH * documentation</a> * @return the {@link List} of paths where the system will look for ROS * packages */ public List<File> getRosPackagePath() { return rosPackagePath; } /** * These ordered paths tell the ROS system where to search for more ROS * packages. If there are multiple packages of the same name, ROS will choose * the one that appears in the {@link List} first. * * @see <a * href="http://www.ros.org/wiki/ROS/EnvironmentVariables#ROS_PACKAGE_PATH">ROS_PACKAGE_PATH * documentation</a> * @param rosPackagePath * the {@link List} of paths where the system will look for ROS * packages * @return this {@link NodeConfiguration} */ public NodeConfiguration setRosPackagePath(List<File> rosPackagePath) { this.rosPackagePath = rosPackagePath; return this; } /** * @return the name of the {@link Node} */ public GraphName getNodeName() { return nodeName; } /** * @param nodeName * the name of the {@link Node} * @return this {@link NodeConfiguration} */ public NodeConfiguration setNodeName(GraphName nodeName) { this.nodeName = nodeName; return this; } /** * @param nodeName * the name of the {@link Node} * @return this {@link NodeConfiguration} */ public NodeConfiguration setNodeName(String nodeName) { return setNodeName(GraphName.of(nodeName)); } /** * Sets the name of the {@link Node} if the name has not already been set. * * @param nodeName * the name of the {@link Node} * @return this {@link NodeConfiguration} */ public NodeConfiguration setDefaultNodeName(GraphName nodeName) { if (this.nodeName == null) { setNodeName(nodeName); } return this; } /** * Sets the name of the {@link Node} if the name has not already been set. * * @param nodeName * the name of the {@link Node} * @return this {@link NodeConfiguration} */ public NodeConfiguration setDefaultNodeName(String nodeName) { return setDefaultNodeName(GraphName.of(nodeName)); } /** * @return the {@link MessageSerializationFactory} for the {@link Node} */ public MessageSerializationFactory getMessageSerializationFactory() { return messageSerializationFactory; } /** * @param messageSerializationFactory * the {@link MessageSerializationFactory} for the {@link Node} * @return this {@link NodeConfiguration} */ public NodeConfiguration setMessageSerializationFactory( MessageSerializationFactory messageSerializationFactory) { this.messageSerializationFactory = messageSerializationFactory; return this; } /** * @param topicMessageFactory * the {@link MessageFactory} for the {@link Node} * @return this {@link NodeConfiguration} */ public NodeConfiguration setTopicMessageFactory(MessageFactory topicMessageFactory) { this.topicMessageFactory = topicMessageFactory; return this; } public MessageFactory getTopicMessageFactory() { return topicMessageFactory; } /** * @param serviceRequestMessageFactory * the {@link ServiceRequestMessageFactory} for the {@link Node} * @return this {@link NodeConfiguration} */ public NodeConfiguration setServiceRequestMessageFactory( ServiceRequestMessageFactory serviceRequestMessageFactory) { this.serviceRequestMessageFactory = serviceRequestMessageFactory; return this; } public MessageFactory getServiceRequestMessageFactory() { return serviceRequestMessageFactory; } /** * @param serviceResponseMessageFactory * the {@link ServiceResponseMessageFactory} for the {@link Node} * @return this {@link NodeConfiguration} */ public NodeConfiguration setServiceResponseMessageFactory( ServiceResponseMessageFactory serviceResponseMessageFactory) { this.serviceResponseMessageFactory = serviceResponseMessageFactory; return this; } public MessageFactory getServiceResponseMessageFactory() { return serviceResponseMessageFactory; } /** * @param topicDescriptionFactory * the {@link TopicDescriptionFactory} for the {@link Node} * @return this {@link NodeConfiguration} */ public NodeConfiguration setTopicDescriptionFactory( TopicDescriptionFactory topicDescriptionFactory) { this.topicDescriptionFactory = topicDescriptionFactory; return this; } public TopicDescriptionFactory getTopicDescriptionFactory() { return topicDescriptionFactory; } /** * @param serviceDescriptionFactory * the {@link ServiceDescriptionFactory} for the {@link Node} * @return this {@link NodeConfiguration} */ public NodeConfiguration setServiceDescriptionFactory( ServiceDescriptionFactory serviceDescriptionFactory) { this.serviceDescriptionFactory = serviceDescriptionFactory; return this; } public ServiceDescriptionFactory getServiceDescriptionFactory() { return serviceDescriptionFactory; } /** * @see <a href="http://www.ros.org/wiki/ROS/TCPROS">TCPROS documentation</a> * * @return the {@link BindAddress} for the {@link Node}'s TCPROS server */ public BindAddress getTcpRosBindAddress() { return tcpRosBindAddress; } /** * @see <a href="http://www.ros.org/wiki/ROS/TCPROS">TCPROS documentation</a> * * @param tcpRosBindAddress * the {@link BindAddress} for the {@link Node}'s TCPROS server */ public NodeConfiguration setTcpRosBindAddress(BindAddress tcpRosBindAddress) { this.tcpRosBindAddress = tcpRosBindAddress; return this; } /** * @see <a href="http://www.ros.org/wiki/ROS/TCPROS">TCPROS documentation</a> * * @return the {@link AdvertiseAddressFactory} for the {@link Node}'s TCPROS * server */ public AdvertiseAddressFactory getTcpRosAdvertiseAddressFactory() { return tcpRosAdvertiseAddressFactory; } /** * @see <a href="http://www.ros.org/wiki/ROS/TCPROS">TCPROS documentation</a> * * @param tcpRosAdvertiseAddressFactory * the {@link AdvertiseAddressFactory} for the {@link Node}'s TCPROS * server * @return this {@link NodeConfiguration} */ public NodeConfiguration setTcpRosAdvertiseAddressFactory( AdvertiseAddressFactory tcpRosAdvertiseAddressFactory) { this.tcpRosAdvertiseAddressFactory = tcpRosAdvertiseAddressFactory; return this; } /** * @see <a href="http://www.ros.org/wiki/ROS/TCPROS">TCPROS documentation</a> * * @return the {@link AdvertiseAddress} for the {@link Node}'s TCPROS server */ public AdvertiseAddress getTcpRosAdvertiseAddress() { return tcpRosAdvertiseAddressFactory.newDefault(); } /** * @see <a href="http://www.ros.org/wiki/ROS/Technical%20Overview#Node">Node * documentation</a> * * @return the {@link BindAddress} for the {@link Node}'s XML-RPC server */ public BindAddress getXmlRpcBindAddress() { return xmlRpcBindAddress; } /** * @see <a href="http://www.ros.org/wiki/ROS/Technical%20Overview#Node">Node * documentation</a> * * @param xmlRpcBindAddress * the {@link BindAddress} for the {@link Node}'s XML-RPC server */ public NodeConfiguration setXmlRpcBindAddress(BindAddress xmlRpcBindAddress) { this.xmlRpcBindAddress = xmlRpcBindAddress; return this; } /** * @see <a href="http://www.ros.org/wiki/ROS/Technical%20Overview#Node">Node * documentation</a> * * @return the {@link AdvertiseAddress} for the {@link Node}'s XML-RPC server */ public AdvertiseAddress getXmlRpcAdvertiseAddress() { return xmlRpcAdvertiseAddressFactory.newDefault(); } /** * @see <a href="http://www.ros.org/wiki/ROS/Technical%20Overview#Node">Node * documentation</a> * * @return the {@link AdvertiseAddressFactory} for the {@link Node}'s XML-RPC * server */ public AdvertiseAddressFactory getXmlRpcAdvertiseAddressFactory() { return xmlRpcAdvertiseAddressFactory; } /** * @see <a href="http://www.ros.org/wiki/ROS/Technical%20Overview#Node">Node * documentation</a> * * @param xmlRpcAdvertiseAddressFactory * the {@link AdvertiseAddressFactory} for the {@link Node}'s XML-RPC * server */ public NodeConfiguration setXmlRpcAdvertiseAddressFactory( AdvertiseAddressFactory xmlRpcAdvertiseAddressFactory) { this.xmlRpcAdvertiseAddressFactory = xmlRpcAdvertiseAddressFactory; return this; } /** * @return the configured {@link TimeProvider} */ public TimeProvider getTimeProvider() { return timeProvider; } /** * Sets the {@link TimeProvider} that {@link Node}s will use. By default, the * {@link WallTimeProvider} is used. * * @param timeProvider * the {@link TimeProvider} that {@link Node}s will use */ public NodeConfiguration setTimeProvider(TimeProvider timeProvider) { this.timeProvider = timeProvider; return this; } }
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 the classes for communicating via services. * * @see <a href="http://ros.org/wiki/Services">services documentation</a> */ package org.ros.node.service;
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.node.service; /** * @author damonkohler@google.com (Damon Kohler) */ public class DefaultServiceServerListener<T, S> implements ServiceServerListener<T, S> { @Override public void onMasterRegistrationSuccess(ServiceServer<T, S> registrant) { } @Override public void onMasterRegistrationFailure(ServiceServer<T, S> registrant) { } @Override public void onMasterUnregistrationSuccess(ServiceServer<T, S> registrant) { } @Override public void onMasterUnregistrationFailure(ServiceServer<T, S> registrant) { } @Override public void onShutdown(ServiceServer<T, S> serviceServer) { } }
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.node.service; import org.ros.namespace.GraphName; import java.net.URI; /** * Provides a connection to a ROS service. * * @author damonkohler@google.com (Damon Kohler) * * @param <T> * the {@link ServiceServer} responds to requests of this type * @param <S> * the {@link ServiceServer} returns responses of this type */ public interface ServiceClient<T, S> { /** * Connects to a {@link ServiceServer}. * * @param uri * the {@link URI} of the {@link ServiceServer} to connect to */ void connect(URI uri); /** * Calls a method on the {@link ServiceServer}. * * @param request * the request message * @param listener * the {@link ServiceResponseListener} that will handle the response * to this request */ void call(T request, ServiceResponseListener<S> listener); /** * @return the name of the service this {@link ServiceClient} is connected to */ GraphName getName(); /** * Stops the client (e.g. disconnect a persistent service connection). */ void shutdown(); /** * @return a new request message */ T newMessage(); }
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.node.service; import org.ros.internal.node.CountDownRegistrantListener; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * A {@link ServiceServerListener} which uses {@link CountDownLatch} to track * message invocations. * * @author khughes@google.com (Keith M. Hughes) */ public class CountDownServiceServerListener<T, S> extends CountDownRegistrantListener<ServiceServer<T, S>> implements ServiceServerListener<T, S> { private final CountDownLatch shutdownLatch; /** * Construct a {@link CountDownServiceServerListener} with all counts set to * 1. */ public static <T, S> CountDownServiceServerListener<T, S> newDefault() { return newFromCounts(1, 1, 1, 1); } /** * @param masterRegistrationSuccessCount * the number of successful master registrations to wait for * @param masterRegistrationFailureCount * the number of failing master registrations to wait for * @param masterUnregistrationSuccessCount * the number of successful master unregistrations to wait for * @param masterUnregistrationFailureCount * the number of failing master unregistrations to wait for */ public static <T, S> CountDownServiceServerListener<T, S> newFromCounts( int masterRegistrationSuccessCount, int masterRegistrationFailureCount, int masterUnregistrationSuccessCount, int masterUnregistrationFailureCount) { return new CountDownServiceServerListener<T, S>(new CountDownLatch( masterRegistrationSuccessCount), new CountDownLatch(masterRegistrationFailureCount), new CountDownLatch(masterUnregistrationSuccessCount), new CountDownLatch( masterUnregistrationFailureCount)); } private CountDownServiceServerListener(CountDownLatch masterRegistrationSuccessLatch, CountDownLatch masterRegistrationFailureLatch, CountDownLatch masterUnregistrationSuccessLatch, CountDownLatch masterUnregistrationFailureLatch) { super(masterRegistrationSuccessLatch, masterRegistrationFailureLatch, masterUnregistrationSuccessLatch, masterUnregistrationFailureLatch); shutdownLatch = new CountDownLatch(1); } @Override public void onShutdown(ServiceServer<T, S> server) { shutdownLatch.countDown(); } /** * Wait for shutdown. * * @throws InterruptedException */ public void awaitShutdown() throws InterruptedException { shutdownLatch.await(); } /** * Wait for shutdown within the given time period. * * @param timeout * the maximum time to wait * @param unit * the time unit of the {@code timeout} argument * @return {@code true} if shutdown happened within the time period, * {@code false} otherwise * @throws InterruptedException */ public boolean awaitShutdown(long timeout, TimeUnit unit) throws InterruptedException { return shutdownLatch.await(timeout, unit); } }
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.node.service; import org.ros.exception.ServiceException; /** * Builds a service response given a service request. * * @author damonkohler@google.com (Damon Kohler) * * @param <T> * the {@link ServiceServer} responds to requests of this type * @param <S> * the {@link ServiceServer} returns responses of this type */ public interface ServiceResponseBuilder<T, S> { /** * Builds a service response given a service request. * * @param request * the received request * @param response * the response that will be sent * @throws ServiceException */ void build(T request, S response) throws ServiceException; }
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.node.service; import org.ros.exception.RemoteException; /** * A listener for service responses. * * @author damonkohler@google.com (Damon Kohler) * * @param <MessageType> * handles messages of this type */ public interface ServiceResponseListener<MessageType> { /** * Called when a service method returns successfully. * * @param response * the response message */ void onSuccess(MessageType response); /** * Called when a service method fails to return successfully. * * @param e * the {@link RemoteException} received from the service */ void onFailure(RemoteException 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.node.service; import org.ros.namespace.GraphName; import java.net.URI; /** * Provides a ROS service. * * @see <a href="http://www.ros.org/wiki/Services">Services documentation</a> * * @author damonkohler@google.com (Damon Kohler) * * @param <T> * this {@link ServiceServer} responds to requests of this type * @param <S> * this {@link ServiceServer} returns responses of this type */ public interface ServiceServer<T, S> { /** * @return the name of the {@link ServiceServer} */ GraphName getName(); /** * @return the {@link URI} for this {@link ServiceServer} */ URI getUri(); /** * Stops the service and unregisters it. */ void shutdown(); /** * Add a {@link ServiceServerListener}. * * @param listener * the {@link ServiceServerListener} to add */ void addListener(ServiceServerListener<T, S> listener); }
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.node.service; import org.ros.internal.node.RegistrantListener; /** * A lifecycle listener for {@link ServiceServer} instances. * * @author khughes@google.com (Keith M. Hughes) * * @param <T> * the {@link ServiceServer} responds to requests of this type * @param <S> * the {@link ServiceServer} returns responses of this type */ public interface ServiceServerListener<T, S> extends RegistrantListener<ServiceServer<T, S>> { /** * @param serviceServer * the {@link ServiceServer} which has been shut down */ void onShutdown(ServiceServer<T, S> serviceServer); }
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.node.topic; import org.ros.internal.node.topic.TopicParticipant; import org.ros.message.MessageListener; import java.util.concurrent.TimeUnit; /** * Subscribes to messages of a given type on a given ROS topic. * * @author ethan.rublee@gmail.com (Ethan Rublee) * @author damonkohler@google.com (Damon Kohler) * * @param <T> * the {@link Subscriber} may only subscribe to messages of this type */ public interface Subscriber<T> extends TopicParticipant { /** * The message type given when a {@link Subscriber} chooses not to commit to a * specific message type. */ public static final String TOPIC_MESSAGE_TYPE_WILDCARD = "*"; /** * Adds a {@link MessageListener} to be called when new messages are received. * <p> * The {@link MessageListener} will be executed serially in its own thread. If * the {@link MessageListener} processes new messages slower than they arrive, * new messages will be queued up to the specified limit. Older messages are * removed from the buffer when the buffer limit is exceeded. * * @param messageListener * this {@link MessageListener} will be called when new messages are * received * @param limit * the maximum number of messages to buffer */ void addMessageListener(MessageListener<T> messageListener, int limit); /** * Adds a {@link MessageListener} with a limit of 1. * * @see #addMessageListener(MessageListener, int) */ void addMessageListener(MessageListener<T> messageListener); /** * Shuts down and unregisters the {@link Subscriber}. using the default * timeout Shutdown is delayed by at most the specified timeout to allow * {@link SubscriberListener#onShutdown(Subscriber)} callbacks to complete. * * <p> * {@link SubscriberListener#onShutdown(Subscriber)} callbacks are executed in * separate threads. */ void shutdown(long timeout, TimeUnit unit); /** * Shuts down and unregisters the {@link Subscriber} using the default timeout * for {@link SubscriberListener#onShutdown(Subscriber)} callbacks. * * <p> * {@link SubscriberListener#onShutdown(Subscriber)} callbacks are executed in * separate threads. * * @see Subscriber#shutdown(long, TimeUnit) */ void shutdown(); /** * Add a new lifecycle listener to the subscriber. * * @param listener * The listener to add. */ void addSubscriberListener(SubscriberListener<T> listener); /** * @return {@code true} if the {@link Publisher} of this {@link Subscriber}'s * topic is latched, {@code false} otherwise */ boolean getLatchMode(); }
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.node.topic; import org.ros.internal.node.RegistrantListener; import org.ros.internal.node.topic.SubscriberIdentifier; /** * A lifecycle listener for {@link Publisher} instances. * * @author khughes@google.com (Keith M. Hughes) */ public interface PublisherListener<T> extends RegistrantListener<Publisher<T>> { /** * A {@link Subscriber} has connected to the {@link Publisher}. * * @param publisher * the {@link Publisher} that the {@link Subscriber} connected to * @param subscriberIdentifier * the {@link SubscriberIdentifier} of the new {@link Subscriber} */ void onNewSubscriber(Publisher<T> publisher, SubscriberIdentifier subscriberIdentifier); /** * The {@link Publisher} has been shut down. * * @param publisher * the {@link Publisher} that was shut down */ void onShutdown(Publisher<T> publisher); }
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 the classes for communicating via topics. * * @see <a href="http://ros.org/wiki/Topics">topics documentation</a> */ package org.ros.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.node.topic; import org.ros.internal.node.topic.TopicParticipant; import java.util.concurrent.TimeUnit; /** * Publishes messages of a given type on a given ROS topic. * * @author ethan.rublee@gmail.com (Ethan Rublee) * @author damonkohler@google.com (Damon Kohler) * * @param <T> * the {@link Publisher} may only publish messages of this type */ public interface Publisher<T> extends TopicParticipant { /** * @see <a * href="http://www.ros.org/wiki/roscpp/Overview/Publishers%20and%20Subscribers#Publisher_Options">Publisher * options documentation</a> * @param enabled * {@code true} if published messages should be latched, * {@code false} otherwise */ void setLatchMode(boolean enabled); /** * @see <a * href="http://www.ros.org/wiki/roscpp/Overview/Publishers%20and%20Subscribers#Publisher_Options">Publisher * options documentation</a> * @return {@code true} if published messages will be latched, {@code false} * otherwise */ boolean getLatchMode(); /** * Create a new message. * * @return a new message */ T newMessage(); /** * Publishes a message. This message will be available on the topic that this * {@link Publisher} has been associated with. * * @param message * the message to publish */ void publish(T message); /** * @return {@code true} if {@code getNumberOfSubscribers() > 0}, {@code false} * otherwise */ boolean hasSubscribers(); /** * Get the number of {@link Subscriber}s currently connected to the * {@link Publisher}. * * <p> * This counts the number of {@link Subscriber} registered. If a * {@link Subscriber} does not shutdown properly it will not be unregistered * and thus will contribute to this count. * * @return the number of {@link Subscriber}s currently connected to the * {@link Publisher} */ int getNumberOfSubscribers(); /** * Shuts down and unregisters the {@link Publisher}. Shutdown is delayed by at * most the specified timeout to allow * {@link PublisherListener#onShutdown(Publisher)} callbacks to complete. * * <p> * {@link PublisherListener#onShutdown(Publisher)} callbacks are executed in * separate threads. */ void shutdown(long timeout, TimeUnit unit); /** * Shuts down and unregisters the {@link Publisher} using the default timeout * for {@link PublisherListener#onShutdown(Publisher)} callbacks. * * <p> * {@link PublisherListener#onShutdown(Publisher)} callbacks are executed in * separate threads. * * @see Publisher#shutdown(long, TimeUnit) */ void shutdown(); /** * Add a new lifecycle listener to the {@link Publisher}. * * @param listener * the {@link PublisherListener} to add */ void addListener(PublisherListener<T> listener); }
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.node.topic; import org.ros.internal.node.topic.SubscriberIdentifier; import org.ros.internal.node.CountDownRegistrantListener; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * A {@link PublisherListener} which uses separate {@link CountDownLatch} * instances for all signals. * * @author khughes@google.com (Keith M. Hughes) */ public class CountDownPublisherListener<T> extends CountDownRegistrantListener<Publisher<T>> implements PublisherListener<T> { private final CountDownLatch shutdownLatch; private final CountDownLatch newSubscriberLatch; public static <T> CountDownPublisherListener<T> newDefault() { return newFromCounts(1, 1, 1, 1, 1); } /** * @param masterRegistrationSuccessCount * the number of successful master registrations to wait for * @param masterRegistrationFailureCount * the number of failing master registrations to wait for * @param masterUnregistrationSuccessCount * the number of successful master unregistrations to wait for * @param masterUnregistrationFailureCount * the number of failing master unregistrations to wait for * @param newSubscriberCount * the number of new subscribers to wait for */ public static <T> CountDownPublisherListener<T> newFromCounts(int masterRegistrationSuccessCount, int masterRegistrationFailureCount, int masterUnregistrationSuccessCount, int masterUnregistrationFailureCount, int newSubscriberCount) { return new CountDownPublisherListener<T>(new CountDownLatch(masterRegistrationSuccessCount), new CountDownLatch(masterRegistrationFailureCount), new CountDownLatch( masterUnregistrationSuccessCount), new CountDownLatch(masterUnregistrationFailureCount), new CountDownLatch(newSubscriberCount)); } private CountDownPublisherListener(CountDownLatch masterRegistrationSuccessLatch, CountDownLatch masterRegistrationFailureLatch, CountDownLatch masterUnregistrationSuccessLatch, CountDownLatch masterUnregistrationFailureLatch, CountDownLatch newSubscriberLatch) { super(masterRegistrationSuccessLatch, masterRegistrationFailureLatch, masterUnregistrationSuccessLatch, masterUnregistrationFailureLatch); this.newSubscriberLatch = newSubscriberLatch; shutdownLatch = new CountDownLatch(1); } @Override public void onNewSubscriber(Publisher<T> publisher, SubscriberIdentifier subscriberIdentifier) { newSubscriberLatch.countDown(); } @Override public void onShutdown(Publisher<T> publisher) { shutdownLatch.countDown(); } /** * Wait for the requested number of shutdowns. * * @throws InterruptedException */ public void awaitNewSubscriber() throws InterruptedException { newSubscriberLatch.await(); } /** * Wait for the requested number of new subscribers within the given time * period. * * @param timeout * the maximum time to wait * @param unit * the {@link TimeUnit} of the {@code timeout} argument * @return {@code true} if the requested number of new subscribers connect * within the time period {@code false} otherwise. * @throws InterruptedException */ public boolean awaitNewSubscriber(long timeout, TimeUnit unit) throws InterruptedException { return newSubscriberLatch.await(timeout, unit); } /** * Wait for for shutdown. * * @throws InterruptedException */ public void awaitShutdown() throws InterruptedException { shutdownLatch.await(); } /** * Wait for shutdown within the given time period. * * @param timeout * the maximum time to wait * @param unit * the {@link TimeUnit} of the {@code timeout} argument * @return {@code true} if shutdown happened within the time period, * {@code false} otherwise * @throws InterruptedException */ public boolean awaitShutdown(long timeout, TimeUnit unit) throws InterruptedException { return shutdownLatch.await(timeout, unit); } }
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.node.topic; import org.ros.internal.node.topic.SubscriberIdentifier; /** * A {@link PublisherListener} which provides empty defaults for all signals. * * @author khughes@google.com (Keith M. Hughes) */ public class DefaultPublisherListener<T> implements PublisherListener<T> { @Override public void onMasterRegistrationSuccess(Publisher<T> publisher) { } @Override public void onMasterRegistrationFailure(Publisher<T> publisher) { } @Override public void onMasterUnregistrationSuccess(Publisher<T> publisher) { } @Override public void onMasterUnregistrationFailure(Publisher<T> publisher) { } @Override public void onNewSubscriber(Publisher<T> publisher, SubscriberIdentifier subscriberIdentifier) { } @Override public void onShutdown(Publisher<T> 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.node.topic; import org.ros.internal.node.RegistrantListener; import org.ros.internal.node.topic.PublisherIdentifier; /** * A lifecycle listener for {@link Subscriber} instances. * * @author khughes@google.com (Keith M. Hughes) */ public interface SubscriberListener<T> extends RegistrantListener<Subscriber<T>> { /** * A new {@link Publisher} has connected to the {@link Subscriber}. * * @param subscriber * the {@link Subscriber} that the {@link Publisher} connected to * @param publisherIdentifier * the {@link PublisherIdentifier} of the new {@link Publisher} */ void onNewPublisher(Subscriber<T> subscriber, PublisherIdentifier publisherIdentifier); /** * The {@link Subscriber} has been shut down. * * @param subscriber * the {@link Subscriber} that was shut down */ void onShutdown(Subscriber<T> 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.node.topic; import org.ros.internal.node.topic.PublisherIdentifier; /** * A {@link SubscriberListener} which provides empty defaults for all signals. * * @author khughes@google.com (Keith M. Hughes) */ public class DefaultSubscriberListener<T> implements SubscriberListener<T> { @Override public void onMasterRegistrationSuccess(Subscriber<T> subscriber) { } @Override public void onMasterRegistrationFailure(Subscriber<T> subscriber) { } @Override public void onMasterUnregistrationSuccess(Subscriber<T> subscriber) { } @Override public void onMasterUnregistrationFailure(Subscriber<T> subscriber) { } @Override public void onNewPublisher(Subscriber<T> subscriber, PublisherIdentifier publisherIdentifier) { } @Override public void onShutdown(Subscriber<T> 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.node.topic; import org.ros.internal.node.topic.PublisherIdentifier; import org.ros.internal.node.CountDownRegistrantListener; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * A {@link SubscriberListener} which uses separate {@link CountDownLatch} * instances for all messages. * * @author khughes@google.com (Keith M. Hughes) */ public class CountDownSubscriberListener<T> extends CountDownRegistrantListener<Subscriber<T>> implements SubscriberListener<T> { private final CountDownLatch shutdownLatch; private final CountDownLatch newPublisherLatch; /** * Construct a {@link CountDownSubscriberListener} with all counts set to 1. */ public static <T> CountDownSubscriberListener<T> newDefault() { return newFromCounts(1, 1, 1, 1, 1); } /** * @param masterRegistrationSuccessCount * the number of successful master registrations to wait for * @param masterRegistrationFailureCount * the number of failing master registrations to wait for * @param masterUnregistrationSuccessCount * the number of successful master unregistrations to wait for * @param masterUnregistrationFailureCount * the number of failing master unregistrations to wait for * @param newSubscriberCount * the number of counts to wait for for a new publisher */ public static <T> CountDownSubscriberListener<T> newFromCounts( int masterRegistrationSuccessCount, int masterRegistrationFailureCount, int masterUnregistrationSuccessCount, int masterUnregistrationFailureCount, int newSubscriberCount) { return new CountDownSubscriberListener<T>(new CountDownLatch(masterRegistrationSuccessCount), new CountDownLatch(masterRegistrationFailureCount), new CountDownLatch( masterUnregistrationSuccessCount), new CountDownLatch(masterUnregistrationFailureCount), new CountDownLatch(newSubscriberCount)); } private CountDownSubscriberListener(CountDownLatch masterRegistrationSuccessLatch, CountDownLatch masterRegistrationFailureLatch, CountDownLatch masterUnregistrationSuccessLatch, CountDownLatch masterUnregistrationFailureLatch, CountDownLatch newPublisherLatch) { super(masterRegistrationSuccessLatch, masterRegistrationFailureLatch, masterUnregistrationSuccessLatch, masterUnregistrationFailureLatch); this.newPublisherLatch = newPublisherLatch; shutdownLatch = new CountDownLatch(1); } @Override public void onNewPublisher(Subscriber<T> subscriber, PublisherIdentifier publisherIdentifier) { newPublisherLatch.countDown(); } @Override public void onShutdown(Subscriber<T> subscriber) { shutdownLatch.countDown(); } /** * Wait for the requested number of new publishers. * * @throws InterruptedException */ public void awaitNewPublisher() throws InterruptedException { newPublisherLatch.await(); } /** * Wait for the requested number of new publishers within the given time * period. * * @param timeout * the maximum time to wait * @param unit * the time unit of the {@code timeout} argument * @return {@code true} if the new publishers connected within the time * period, {@code false} otherwise * @throws InterruptedException */ public boolean awaitNewPublisher(long timeout, TimeUnit unit) throws InterruptedException { return newPublisherLatch.await(timeout, unit); } /** * Wait for shutdown. * * @throws InterruptedException */ public void awaitShutdown() throws InterruptedException { shutdownLatch.await(); } /** * Wait for shutdown within the given time period. * * @param timeout * the maximum time to wait * @param unit * the time unit of the {@code timeout} argument * @return {@code true} if the shutdowns happened within the time period, * {@code false} otherwise * @throws InterruptedException */ public boolean awaitShutdown(long timeout, TimeUnit unit) throws InterruptedException { return shutdownLatch.await(timeout, unit); } }
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.node; import org.ros.internal.node.DefaultNode; import org.ros.concurrent.SharedScheduledExecutorService; import java.util.Collection; import java.util.concurrent.ScheduledExecutorService; /** * Constructs {@link DefaultNode}s. * * @author damonkohler@google.com (Damon Kohler) */ public class DefaultNodeFactory implements NodeFactory { private final ScheduledExecutorService scheduledExecutorService; public DefaultNodeFactory(ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = new SharedScheduledExecutorService(scheduledExecutorService); } @Override public Node newNode(NodeConfiguration nodeConfiguration, Collection<NodeListener> listeners) { return new DefaultNode(nodeConfiguration, listeners, scheduledExecutorService); } @Override public Node newNode(NodeConfiguration nodeConfiguration) { return newNode(nodeConfiguration, 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.node; import java.util.Collection; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; /** * Executes {@link NodeMain}s and allows shutting down individual * {@link NodeMain}s or all currently running {@link NodeMain}s as a group. * * @author damonkohler@google.com (Damon Kohler) */ public interface NodeMainExecutor { /** * @return the {@link ScheduledExecutorService} that this * {@link NodeMainExecutor} uses */ ScheduledExecutorService getScheduledExecutorService(); /** * Executes the supplied {@link NodeMain} using the supplied * {@link NodeConfiguration}. * * @param nodeMain * the {@link NodeMain} to execute * @param nodeConfiguration * the {@link NodeConfiguration} that will be used to create the * {@link Node} * @param nodeListeners * a {@link Collection} of {@link NodeListener}s to be added to the * {@link Node} before it starts, can be {@code null} */ void execute(NodeMain nodeMain, NodeConfiguration nodeConfiguration, Collection<NodeListener> nodeListeners); /** * Executes the supplied {@link NodeMain} using the supplied * {@link NodeConfiguration}. * * @param nodeMain * the {@link NodeMain} to execute * @param nodeConfiguration * the {@link NodeConfiguration} that will be used to create the * {@link Node} */ void execute(NodeMain nodeMain, NodeConfiguration nodeConfiguration); /** * Shuts down the supplied {@link NodeMain} (i.e. * {@link NodeMain#onShutdown(Node)} will be called). This does not * necessarily shut down the {@link Node} that is associated with the * {@link NodeMain}. * * <p> * This has no effect if the {@link NodeMain} has not started. * * @param nodeMain * the {@link NodeMain} to shutdown */ void shutdownNodeMain(NodeMain nodeMain); /** * Shutdown all started {@link Node}s. This does not shut down the supplied * {@link ExecutorService}. */ void 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.node; import org.ros.exception.ServiceNotFoundException; import org.ros.message.Time; import org.ros.namespace.GraphName; import org.ros.namespace.NameResolver; 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.Publisher; import org.ros.node.topic.Subscriber; import java.net.URI; /** * A node in the ROS graph that has successfully contacted the master. * <p> * A {@link ConnectedNode} serves as a factory for: * <ul> * <li>{@link Publisher}</li> * <li>{@link Subscriber}</li> * <li>{@link ServiceServer}</li> * <li>{@link ServiceClient}</li> * <li>{@link ParameterTree}</li> * </ul> * * @author damonkohler@google.com (Damon Kohler) */ public interface ConnectedNode extends Node { /** * In ROS, time can be wallclock (actual) or simulated, so it is important to * use {@link ConnectedNode#getCurrentTime()} instead of using the standard * Java routines for determining the current time. * * @return the current time */ Time getCurrentTime(); /** * @param <T> * the message type to create the publisher for * @param topicName * the topic name, will be pushed down under this namespace unless * '/' is prepended. * @param messageType * the message data type (e.g. "std_msgs/String") * @return a {@link Publisher} for the specified topic */ <T> Publisher<T> newPublisher(GraphName topicName, String messageType); /** * @see #newPublisher(GraphName, String) */ <T> Publisher<T> newPublisher(String topicName, String messageType); /** * @param <T> * the message type to create the {@link Subscriber} for * @param topicName * the topic name to be subscribed to, this will be auto resolved * @param messageType * the message data type (e.g. "std_msgs/String") * @return a {@link Subscriber} for the specified topic */ <T> Subscriber<T> newSubscriber(GraphName topicName, String messageType); /** * @see #newSubscriber(GraphName, String) */ <T> Subscriber<T> newSubscriber(String topicName, String messageType); /** * Create a new {@link ServiceServer}. * * @param serviceName * the name of the service * @param serviceType * the type of the service (e.g. "test_ros/AddTwoInts") * @param serviceResponseBuilder * called for every request to build a response * @return a {@link ServiceServer} */ <T, S> ServiceServer<T, S> newServiceServer(GraphName serviceName, String serviceType, ServiceResponseBuilder<T, S> serviceResponseBuilder); /** * @see ConnectedNode#newServiceServer(GraphName, String, * ServiceResponseBuilder) */ <T, S> ServiceServer<T, S> newServiceServer(String serviceName, String serviceType, ServiceResponseBuilder<T, S> serviceResponseBuilder); /** * @param serviceName * the {@link GraphName} of the {@link ServiceServer} * @return the {@link ServiceServer} with the given name or {@code null} if it * does not exist */ <T, S> ServiceServer<T, S> getServiceServer(GraphName serviceName); /** * @see ConnectedNode#getServiceServer(GraphName) */ <T, S> ServiceServer<T, S> getServiceServer(String serviceName); /** * @param serviceName * the {@link GraphName} of the service {@link URI} to lookup * @return the {@link URI} of the service or {@code null} if it does not exist */ URI lookupServiceUri(GraphName serviceName); /** * @see #lookupServiceUri(GraphName) */ URI lookupServiceUri(String serviceName); /** * Create a {@link ServiceClient}. * * @param serviceName * the name of the service * @param serviceType * the type of the service (e.g. "test_ros/AddTwoInts") * @return a {@link ServiceClient} * @throws ServiceNotFoundException * thrown if no matching service could be found */ <T, S> ServiceClient<T, S> newServiceClient(GraphName serviceName, String serviceType) throws ServiceNotFoundException; /** * @see #newServiceClient(GraphName, String) */ <T, S> ServiceClient<T, S> newServiceClient(String serviceName, String serviceType) throws ServiceNotFoundException; /** * Create a {@link ParameterTree} to query and set parameters on the ROS * parameter server. * * @return {@link ParameterTree} with {@link NameResolver} in this namespace. */ ParameterTree getParameterTree(); }
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.node; import java.util.Collection; /** * Builds new {@link Node}s. * * @author damonkohler@google.com (Damon Kohler) */ public interface NodeFactory { /** * Build a new {@link Node} with the given {@link NodeConfiguration}. * * @param configuration * the {@link NodeConfiguration} for the new {@link Node} * @return a new {@link Node} */ Node newNode(NodeConfiguration configuration); /** * Build a new {@link Node} with the given {@link NodeConfiguration} and * {@link NodeListener}s. * * @param configuration * the {@link NodeConfiguration} for the new {@link Node} * @param listeners * a collection of {@link NodeListener} instances which will be * registered with the node (can be {@code null}) * @return a new {@link Node} */ Node newNode(NodeConfiguration configuration, Collection<NodeListener> listeners); }
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.node; import com.google.common.base.Preconditions; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ros.concurrent.DefaultScheduledExecutorService; import org.ros.namespace.GraphName; import java.util.Collection; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; /** * Executes {@link NodeMain}s in separate threads. * * @author damonkohler@google.com (Damon Kohler) */ public class DefaultNodeMainExecutor implements NodeMainExecutor { private static final boolean DEBUG = false; private static final Log log = LogFactory.getLog(DefaultNodeMainExecutor.class); private final NodeFactory nodeFactory; private final ScheduledExecutorService scheduledExecutorService; private final Multimap<GraphName, ConnectedNode> connectedNodes; private final BiMap<Node, NodeMain> nodeMains; private class RegistrationListener implements NodeListener { @Override public void onStart(ConnectedNode connectedNode) { registerNode(connectedNode); } @Override public void onShutdown(Node node) { } @Override public void onShutdownComplete(Node node) { unregisterNode(node); } @Override public void onError(Node node, Throwable throwable) { log.error("Node error.", throwable); unregisterNode(node); } } /** * @return an instance of {@link DefaultNodeMainExecutor} that uses a * {@link ScheduledExecutorService} that is suitable for both * executing tasks immediately and scheduling tasks to execute in the * future */ public static NodeMainExecutor newDefault() { return newDefault(new DefaultScheduledExecutorService()); } /** * @return an instance of {@link DefaultNodeMainExecutor} that uses the * supplied {@link ExecutorService} */ public static NodeMainExecutor newDefault(ScheduledExecutorService executorService) { return new DefaultNodeMainExecutor(new DefaultNodeFactory(executorService), executorService); } /** * @param nodeFactory * {@link NodeFactory} to use for node creation. * @param scheduledExecutorService * {@link NodeMain}s will be executed using this */ private DefaultNodeMainExecutor(NodeFactory nodeFactory, ScheduledExecutorService scheduledExecutorService) { this.nodeFactory = nodeFactory; this.scheduledExecutorService = scheduledExecutorService; connectedNodes = Multimaps.synchronizedMultimap(HashMultimap.<GraphName, ConnectedNode>create()); nodeMains = Maps.synchronizedBiMap(HashBiMap.<Node, NodeMain>create()); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { DefaultNodeMainExecutor.this.shutdown(); } })); } @Override public ScheduledExecutorService getScheduledExecutorService() { return scheduledExecutorService; } @Override public void execute(final NodeMain nodeMain, final NodeConfiguration nodeConfiguration, final Collection<NodeListener> nodeListeners) { // NOTE(damonkohler): To avoid a race condition, we have to make our copy // of the NodeConfiguration in the current thread. final NodeConfiguration nodeConfigurationCopy = NodeConfiguration.copyOf(nodeConfiguration); nodeConfigurationCopy.setDefaultNodeName(nodeMain.getDefaultNodeName()); Preconditions.checkNotNull(nodeConfigurationCopy.getNodeName(), "Node name not specified."); if (DEBUG) { log.info("Starting node: " + nodeConfigurationCopy.getNodeName()); } scheduledExecutorService.execute(new Runnable() { @Override public void run() { Collection<NodeListener> nodeListenersCopy = Lists.newArrayList(); nodeListenersCopy.add(new RegistrationListener()); nodeListenersCopy.add(nodeMain); if (nodeListeners != null) { nodeListenersCopy.addAll(nodeListeners); } // The new Node will call onStart(). Node node = nodeFactory.newNode(nodeConfigurationCopy, nodeListenersCopy); nodeMains.put(node, nodeMain); } }); } @Override public void execute(NodeMain nodeMain, NodeConfiguration nodeConfiguration) { execute(nodeMain, nodeConfiguration, null); } @Override public void shutdownNodeMain(NodeMain nodeMain) { Node node = nodeMains.inverse().get(nodeMain); if (node != null) { safelyShutdownNode(node); } } @Override public void shutdown() { synchronized (connectedNodes) { for (ConnectedNode connectedNode : connectedNodes.values()) { safelyShutdownNode(connectedNode); } } } /** * Trap and log any exceptions while shutting down the supplied {@link Node}. * * @param node * the {@link Node} to shut down */ private void safelyShutdownNode(Node node) { boolean success = true; try { node.shutdown(); } catch (Exception e) { // Ignore spurious errors during shutdown. log.error("Exception thrown while shutting down node.", e); // We don't expect any more callbacks from a node that throws an exception // while shutting down. So, we unregister it immediately. unregisterNode(node); success = false; } if (success) { log.info("Shutdown successful."); } } /** * Register a {@link ConnectedNode} with the {@link NodeMainExecutor}. * * @param connectedNode * the {@link ConnectedNode} to register */ private void registerNode(ConnectedNode connectedNode) { GraphName nodeName = connectedNode.getName(); synchronized (connectedNodes) { for (ConnectedNode illegalConnectedNode : connectedNodes.get(nodeName)) { System.err.println(String.format( "Node name collision. Existing node %s (%s) will be shutdown.", nodeName, illegalConnectedNode.getUri())); illegalConnectedNode.shutdown(); } connectedNodes.put(nodeName, connectedNode); } } /** * Unregister a {@link Node} with the {@link NodeMainExecutor}. * * @param node * the {@link Node} to unregister */ private void unregisterNode(Node node) { connectedNodes.get(node.getName()).remove(node); nodeMains.remove(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.node; /** * A listener for lifecycle events on a {@link Node}. * * @author khughes@google.com (Keith M. Hughes) */ public interface NodeListener { /** * Called when the {@link Node} has started and successfully connected to the * master. * * @param connectedNode * the {@link ConnectedNode} that has been started */ void onStart(ConnectedNode connectedNode); /** * Called when the {@link ConnectedNode} has started shutting down. Shutdown * will be delayed, although not indefinitely, until all {@link NodeListener}s * have returned from this method. * <p> * Since this method can potentially delay {@link ConnectedNode} shutdown, it * is preferred to use {@link #onShutdownComplete(Node)} when * {@link ConnectedNode} resources are not required during the method call. * * @param node * the {@link Node} that has started shutting down */ void onShutdown(Node node); /** * Called when the {@link Node} has shut down. * * @param node * the {@link Node} that has shut down */ void onShutdownComplete(Node node); /** * Called when the {@link Node} experiences an unrecoverable error. * * @param node * the {@link Node} that experienced the error * @param throwable * the {@link Throwable} describing the error condition */ void onError(Node node, Throwable 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.namespace; import org.ros.node.Node; /** * Resolver for {@link Node} names. {@link Node} namespace must handle the ~name * syntax for private names. * * @author ethan.rublee@gmail.com (Ethan Rublee) * @author kwc@willowgarage.com (Ken Conley) */ public class NodeNameResolver extends NameResolver { private final GraphName privateNamespace; /** * @param nodeName * the name of the {@link Node} * @param defaultResolver * the {@link NameResolver} to use if asked to resolve a non-private * name */ public NodeNameResolver(GraphName nodeName, NameResolver defaultResolver) { super(defaultResolver.getNamespace(), defaultResolver.getRemappings()); this.privateNamespace = nodeName; } /** * @param name * name to resolve * @return the name resolved relative to the default or private namespace */ @Override public GraphName resolve(GraphName name) { GraphName graphName = lookUpRemapping(name); if (graphName.isPrivate()) { return resolve(privateNamespace, graphName.toRelative()); } return super.resolve(name); } /** * @see #resolve(GraphName) */ @Override public GraphName resolve(String name) { return resolve(GraphName.of(name)); } }
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 the classes for representing names in the ROS graph. */ package org.ros.namespace;
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.namespace; import org.ros.exception.RosRuntimeException; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * @author ethan.rublee@gmail.com (Ethan Rublee) * @author kwc@willowgarage.com (Ken Conley) */ public class NameResolver { private final GraphName namespace; private final Map<GraphName, GraphName> remappings; public static NameResolver newFromNamespace(GraphName namespace) { return new NameResolver(namespace, new HashMap<GraphName, GraphName>()); } public static NameResolver newFromNamespace(String namespace) { return newFromNamespace(GraphName.of(namespace)); } public static NameResolver newRoot() { return newFromNamespace(GraphName.root()); } public static NameResolver newRootFromRemappings(Map<GraphName, GraphName> remappings) { return new NameResolver(GraphName.root(), remappings); } public static NameResolver newFromNamespaceAndRemappings(String namespace, Map<GraphName, GraphName> remappings) { return new NameResolver(GraphName.of(namespace), remappings); } public NameResolver(GraphName namespace, Map<GraphName, GraphName> remappings) { this.remappings = Collections.unmodifiableMap(remappings); this.namespace = namespace; } public GraphName getNamespace() { return namespace; } /** * Resolve name relative to namespace. If namespace is not global, it will * first be resolved to a global name. This method will not resolve private * ~names. * * This does all remappings of both the namespace and name. * * @param namespace * @param name * @return the fully resolved name relative to the given namespace */ public GraphName resolve(GraphName namespace, GraphName name) { GraphName remappedNamespace = lookUpRemapping(namespace); if (!remappedNamespace.isGlobal()) { throw new IllegalArgumentException(String.format( "Namespace %s (remapped from %s) must be global.", remappedNamespace, namespace)); } GraphName remappedName = lookUpRemapping(name); if (remappedName.isGlobal()) { return remappedName; } if (remappedName.isRelative()) { return remappedNamespace.join(remappedName); } if (remappedName.isPrivate()) { throw new RosRuntimeException("Cannot resolve ~private names in arbitrary namespaces."); } throw new RosRuntimeException("Unable to resolve graph name: " + name); } /** * @see #resolve(GraphName, GraphName) */ public GraphName resolve(String namespace, String name) { return resolve(GraphName.of(namespace), GraphName.of(name)); } /** * @see #resolve(GraphName, GraphName) */ public GraphName resolve(GraphName namespace, String name) { return resolve(namespace, GraphName.of(name)); } /** * @see #resolve(GraphName, GraphName) */ public GraphName resolve(String namespace, GraphName name) { return resolve(GraphName.of(namespace), name); } /** * @param name * name to resolve * @return the name resolved relative to the default namespace */ public GraphName resolve(GraphName name) { return resolve(namespace, name); } /** * @see #resolve(GraphName) */ public GraphName resolve(String name) { return resolve(GraphName.of(name)); } /** * @return remappings */ public Map<GraphName, GraphName> getRemappings() { return remappings; } /** * Construct a new child {@link NameResolver} with the same remappings as this * {@link NameResolver}. The namespace of the new child {@link NameResolver} * will be the resolved in this namespace. * * @param namespace * the namespace of the child {@link NameResolver} relative to this * {@link NameResolver}'s namespace * @return a new child {@link NameResolver} whose namespace is relative to the * parent {@link NameResolver}'s namespace */ public NameResolver newChild(GraphName namespace) { return new NameResolver(resolve(namespace), remappings); } /** * @see #newChild(GraphName) */ public NameResolver newChild(String namespace) { return newChild(GraphName.of(namespace)); } protected GraphName lookUpRemapping(GraphName name) { GraphName remappedName = name; if (remappings.containsKey(name)) { remappedName = remappings.get(name); } return remappedName; } }
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 mathematical operations. */ package org.ros.math;
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.math; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.util.Collection; import java.util.Collections; import java.util.List; /** * @author damonkohler@google.com (Damon Kohler) */ public class CollectionMath { private CollectionMath() { // Utility class. } public static <T extends Comparable<? super T>> T median(Collection<T> collection) { Preconditions.checkArgument(collection.size() > 0); List<T> list = Lists.newArrayList(collection); Collections.sort(list); return list.get(list.size() / 2); } }
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.math; /** * Provides conversions from unsigned values to bitwise equal signed values. * * @author damonkohler@google.com (Damon Kohler) */ public class Unsigned { private Unsigned() { // Utility class. } /** * @param value * an unsigned {@link Integer} value * @return a signed {@link Long} that is bitwise equal to {@code value} */ public static long intToLong(int value) { return value & 0xffffffffl; } /** * @param value * an unsigned {@link Short} value * @return a signed {@link Integer} that is bitwise equal to {@code value} */ public static int shortToInt(short value) { return value & 0xffff; } /** * @param value * an unsigned {@link Byte} value * @return a signed {@link Short} that is bitwise equal to {@code value} */ public static short byteToShort(byte value) { return (short) (value & 0xff); } }
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.math; /** * @author damonkohler@google.com (Damon Kohler) */ public class RosMath { private RosMath() { // Utility class. } public static double clamp(double value, double minmum, double maximum) { if (value < minmum) { return minmum; } if (value > maximum) { return maximum; } return value; } public static float clamp(float value, float minmum, float maximum) { if (value < minmum) { return minmum; } if (value > maximum) { return maximum; } return value; } public static int clamp(int value, int minmum, int maximum) { if (value < minmum) { return minmum; } if (value > maximum) { return maximum; } return value; } public static long clamp(long value, long minmum, long maximum) { if (value < minmum) { return minmum; } if (value > maximum) { return maximum; } 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; import com.google.common.annotations.VisibleForTesting; import org.ros.address.AdvertiseAddress; import org.ros.address.BindAddress; import org.ros.internal.node.server.master.MasterServer; import java.net.URI; import java.util.concurrent.TimeUnit; // TODO(damonkohler): Add /rosout node. /** * {@link RosCore} is a collection of nodes and programs that are pre-requisites * of a ROS-based system. You must have a {@link RosCore} (either this * implementation or the default Python implementation distributed with ROS) * running in order for ROS nodes to communicate. * * @see <a href="http://www.ros.org/wiki/roscore">roscore documentation</a> * * @author damonkohler@google.com (Damon Kohler) */ public class RosCore { private final MasterServer masterServer; public static RosCore newPublic(String host, int port) { return new RosCore(BindAddress.newPublic(port), new AdvertiseAddress(host)); } public static RosCore newPublic(int port) { return new RosCore(BindAddress.newPublic(port), AdvertiseAddress.newPublic()); } public static RosCore newPublic() { return new RosCore(BindAddress.newPublic(), AdvertiseAddress.newPublic()); } public static RosCore newPrivate(int port) { return new RosCore(BindAddress.newPrivate(port), AdvertiseAddress.newPrivate()); } public static RosCore newPrivate() { return new RosCore(BindAddress.newPrivate(), AdvertiseAddress.newPrivate()); } private RosCore(BindAddress bindAddress, AdvertiseAddress advertiseAddress) { masterServer = new MasterServer(bindAddress, advertiseAddress); } public void start() { masterServer.start(); } public URI getUri() { return masterServer.getUri(); } public void awaitStart() throws InterruptedException { masterServer.awaitStart(); } public boolean awaitStart(long timeout, TimeUnit unit) throws InterruptedException { return masterServer.awaitStart(timeout, unit); } public void shutdown() { masterServer.shutdown(); } @VisibleForTesting public MasterServer getMasterServer() { return masterServer; } }
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 the network layer. * <p> * These classes should _not_ be used directly outside of the org.ros package. */ package org.ros.internal;
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 org.ros.node.topic.CountDownPublisherListener; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * @author damonkohler@google.com (Damon Kohler) */ public class CountDownRegistrantListener<T> implements RegistrantListener<T> { private final CountDownLatch masterRegistrationSuccessLatch; private final CountDownLatch masterRegistrationFailureLatch; private final CountDownLatch masterUnregistrationSuccessLatch; private final CountDownLatch masterUnregistrationFailureLatch; /** * Construct a {@link CountDownPublisherListener} with all counts set to 1. */ public CountDownRegistrantListener() { this(1, 1, 1, 1); } /** * @param masterRegistrationSuccessCount * the number of successful master registrations to wait for * @param masterRegistrationFailureCount * the number of failing master registrations to wait for * @param masterUnregistrationSuccessCount * the number of successful master unregistrations to wait for * @param masterUnregistrationFailureCount * the number of failing master unregistrations to wait for */ public CountDownRegistrantListener(int masterRegistrationSuccessCount, int masterRegistrationFailureCount, int masterUnregistrationSuccessCount, int masterUnregistrationFailureCount) { this(new CountDownLatch(masterRegistrationSuccessCount), new CountDownLatch( masterRegistrationFailureCount), new CountDownLatch(masterUnregistrationSuccessCount), new CountDownLatch(masterUnregistrationFailureCount)); } public CountDownRegistrantListener(CountDownLatch masterRegistrationSuccessLatch, CountDownLatch masterRegistrationFailureLatch, CountDownLatch masterUnregistrationSuccessLatch, CountDownLatch masterUnregistrationFailureLatch) { this.masterRegistrationSuccessLatch = masterRegistrationSuccessLatch; this.masterRegistrationFailureLatch = masterRegistrationFailureLatch; this.masterUnregistrationSuccessLatch = masterUnregistrationSuccessLatch; this.masterUnregistrationFailureLatch = masterUnregistrationFailureLatch; } @Override public void onMasterRegistrationSuccess(T registrant) { masterRegistrationSuccessLatch.countDown(); } @Override public void onMasterRegistrationFailure(T registrant) { masterRegistrationFailureLatch.countDown(); } @Override public void onMasterUnregistrationSuccess(T registrant) { masterUnregistrationSuccessLatch.countDown(); } @Override public void onMasterUnregistrationFailure(T registrant) { masterUnregistrationFailureLatch.countDown(); } /** * Wait for the requested number of successful registrations. * * @throws InterruptedException */ public void awaitMasterRegistrationSuccess() throws InterruptedException { masterRegistrationSuccessLatch.await(); } /** * Wait for the requested number of successful registrations within the given * time period. * * @param timeout * the maximum time to wait * @param unit * the {@link TimeUnit} of the {@code timeout} argument * @return {@code true} if the registration happened within the time period, * {@code false} otherwise * @throws InterruptedException */ public boolean awaitMasterRegistrationSuccess(long timeout, TimeUnit unit) throws InterruptedException { return masterRegistrationSuccessLatch.await(timeout, unit); } /** * Wait for the requested number of successful unregistrations. * * @throws InterruptedException */ public void awaitMasterUnregistrationSuccess() throws InterruptedException { masterUnregistrationSuccessLatch.await(); } /** * Wait for the requested number of successful unregistrations within the * given time period. * * @param timeout * the maximum time to wait * @param unit * the {@link TimeUnit} of the {@code timeout} argument * @return {@code true} if the unregistration happened within the time period, * {@code false} otherwise * @throws InterruptedException */ public boolean awaitMasterUnregistrationSuccess(long timeout, TimeUnit unit) throws InterruptedException { return masterUnregistrationSuccessLatch.await(timeout, unit); } /** * Wait for the requested number of failed registrations. * * @throws InterruptedException */ public void awaitMasterRegistrationFailure() throws InterruptedException { masterRegistrationFailureLatch.await(); } /** * Wait for the requested number of failed registrations within the given time * period. * * @param timeout * the maximum time to wait * @param unit * the {@link TimeUnit} of the {@code timeout} argument * @return {@code true} if the registration happened within the time period, * {@code false} otherwise * @throws InterruptedException */ public boolean awaitMasterRegistrationFailure(long timeout, TimeUnit unit) throws InterruptedException { return masterRegistrationFailureLatch.await(timeout, unit); } /** * Wait for the requested number of failed unregistrations. * * @throws InterruptedException */ public void awaitMasterUnregistrationFailure() throws InterruptedException { masterUnregistrationFailureLatch.await(); } /** * Wait for the requested number of failed unregistrations within the given * time period. * * @param timeout * the maximum time to wait * @param unit * the {@link TimeUnit} of the {@code timeout} argument * @return {@code true} if the unregistration happened within the time period, * {@code false} otherwise * @throws InterruptedException */ public boolean awaitMasterUnregistrationFailure(long timeout, TimeUnit unit) throws InterruptedException { return masterUnregistrationFailureLatch.await(timeout, unit); } }
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 org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ros.Topics; import org.ros.node.topic.Publisher; import java.io.PrintWriter; import java.io.StringWriter; /** * Logger that logs to both an underlying Apache Commons Log as well as /rosout. * * @author kwc@willowgarage.com (Ken Conley) * @author damonkohler@google.com (Damon Kohler) */ class RosoutLogger implements Log { private final DefaultNode defaultNode; private final Publisher<rosgraph_msgs.Log> publisher; private final Log log; public RosoutLogger(DefaultNode defaultNode) { this.defaultNode = defaultNode; publisher = defaultNode.newPublisher(Topics.ROSOUT, rosgraph_msgs.Log._TYPE); log = LogFactory.getLog(defaultNode.getName().toString()); } public Publisher<rosgraph_msgs.Log> getPublisher() { return publisher; } private void publish(byte level, Object message, Throwable throwable) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); throwable.printStackTrace(printWriter); publish(level, message.toString() + '\n' + stringWriter.toString()); } private void publish(byte level, Object message) { rosgraph_msgs.Log logMessage = publisher.newMessage(); logMessage.getHeader().setStamp(defaultNode.getCurrentTime()); logMessage.setLevel(level); logMessage.setName(defaultNode.getName().toString()); logMessage.setMsg(message.toString()); // TODO(damonkohler): Should update the topics field with a list of all // published and subscribed topics for the node that created this logger. // This helps filter the rosoutconsole. publisher.publish(logMessage); } @Override public boolean isDebugEnabled() { return log.isDebugEnabled(); } @Override public boolean isErrorEnabled() { return log.isErrorEnabled(); } @Override public boolean isFatalEnabled() { return log.isFatalEnabled(); } @Override public boolean isInfoEnabled() { return log.isInfoEnabled(); } @Override public boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public boolean isWarnEnabled() { return log.isWarnEnabled(); } @Override public void trace(Object message) { log.trace(message); if (log.isTraceEnabled() && publisher != null) { publish(rosgraph_msgs.Log.DEBUG, message); } } @Override public void trace(Object message, Throwable t) { log.trace(message, t); if (log.isTraceEnabled() && publisher != null) { publish(rosgraph_msgs.Log.DEBUG, message, t); } } @Override public void debug(Object message) { log.debug(message); if (log.isDebugEnabled() && publisher != null) { publish(rosgraph_msgs.Log.DEBUG, message); } } @Override public void debug(Object message, Throwable t) { log.debug(message, t); if (log.isDebugEnabled() && publisher != null) { publish(rosgraph_msgs.Log.DEBUG, message, t); } } @Override public void info(Object message) { log.info(message); if (log.isInfoEnabled() && publisher != null) { publish(rosgraph_msgs.Log.INFO, message); } } @Override public void info(Object message, Throwable t) { log.info(message, t); if (log.isInfoEnabled() && publisher != null) { publish(rosgraph_msgs.Log.INFO, message, t); } } @Override public void warn(Object message) { log.warn(message); if (log.isWarnEnabled() && publisher != null) { publish(rosgraph_msgs.Log.WARN, message); } } @Override public void warn(Object message, Throwable t) { log.warn(message, t); if (log.isWarnEnabled() && publisher != null) { publish(rosgraph_msgs.Log.WARN, message, t); } } @Override public void error(Object message) { log.error(message); if (log.isErrorEnabled() && publisher != null) { publish(rosgraph_msgs.Log.ERROR, message); } } @Override public void error(Object message, Throwable t) { log.error(message, t); if (log.isErrorEnabled() && publisher != null) { publish(rosgraph_msgs.Log.ERROR, message, t); } } @Override public void fatal(Object message) { log.fatal(message); if (log.isFatalEnabled() && publisher != null) { publish(rosgraph_msgs.Log.FATAL, message); } } @Override public void fatal(Object message, Throwable t) { log.fatal(message, t); if (log.isFatalEnabled() && publisher != null) { publish(rosgraph_msgs.Log.FATAL, message, t); } } }
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.xmlrpc; import java.util.List; import java.util.Map; import java.util.Vector; /** * @author damonkohler@google.com (Damon Kohler) */ public interface SlaveXmlRpcEndpoint extends XmlRpcEndpoint { /** * Retrieve transport/topic statistics. * * @param callerId * ROS caller ID. * @return stats in the form of <br> * [publishStats, subscribeStats, serviceStats] * <p> * where <br> * publishStats: [[topicName, messageDataSent, pubConnectionData]...] * <br> * subscribeStats: [[topicName, subConnectionData]...] <br> * serviceStats: (proposed) [numRequests, bytesReceived, bytesSent] <br> * * pubConnectionData: [connectionId, bytesSent, numSent, connected] <br> * subConnectionData: [connectionId, bytesReceived, dropEstimate, * connected] <br> * dropEstimate: -1 if no estimate. */ public List<Object> getBusStats(String callerId); /** * Retrieve transport/topic connection information. * * @param callerId * ROS caller ID. * @return busInfo in the form of:<br> * [[connectionId1, destinationId1, direction1, transport1, topic1, * connected1]... ] * <p> * connectionId is defined by the node and is opaque. destinationId is * the XMLRPC URI of the destination. * <p> * direction is one of 'i', 'o', or 'b' (in, out, both). * <p> * transport is the transport type (e.g. 'TCPROS'). topic is the topic * name. * <p> * connected1 indicates connection status. Note that this field is * only provided by slaves written in Python at the moment (cf. * rospy/masterslave.py in _TopicImpl.get_stats_info() vs. * roscpp/publication.cpp in Publication::getInfo()). */ public List<Object> getBusInfo(String callerId); public List<Object> getMasterUri(String callerId); public List<Object> shutdown(String callerId, String message); public List<Object> getPid(String callerId); public List<Object> getSubscriptions(String callerId); /** * Retrieve a list of topics that this node publishes. * * @param callerId * ROS caller ID. * @return topicList is a list of topics published by this node and is of the * form [ [topic1, topicType1]...[topicN, topicTypeN]]] */ public List<Object> getPublications(String callerId); /** * Callback from master with updated value of subscribed parameter. * * @param callerId * ROS caller ID. * @param key * parameter name, globally resolved * @param value * new parameter value * @return ignore */ public List<Object> paramUpdate(String callerId, String key, boolean value); public List<Object> paramUpdate(String callerId, String key, char value); public List<Object> paramUpdate(String callerId, String key, byte value); public List<Object> paramUpdate(String callerId, String key, short value); public List<Object> paramUpdate(String callerId, String key, int value); public List<Object> paramUpdate(String callerId, String key, double value); public List<Object> paramUpdate(String callerId, String key, String value); public List<Object> paramUpdate(String callerId, String key, List<?> value); public List<Object> paramUpdate(String callerId, String key, Vector<?> value); public List<Object> paramUpdate(String callerId, String key, Map<?, ?> value); public List<Object> publisherUpdate(String callerId, String topic, Object[] publishers); /** * Publisher node API method called by a subscriber node. This requests that * source allocate a channel for communication. Subscriber provides a list of * desired protocols for communication. Publisher returns the selected * protocol along with any additional params required for establishing * connection. For example, for a TCP/IP-based connection, the source node may * return a port number of TCP/IP server. * * @param callerId * ROS caller ID * @param topic * topic name * @param protocols * list of desired protocols for communication in order of preference * @return protocolParams or empty list if there are no compatible protocols */ public List<Object> requestTopic(String callerId, String topic, Object[] protocols); }
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 the ROS XML-RPC layer. * <p> * These classes should _not_ be used directly outside of the org.ros package. */ package org.ros.internal.node.xmlrpc;
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.xmlrpc; import com.google.common.collect.Lists; import org.ros.exception.RosRuntimeException; import org.ros.internal.node.response.Response; import org.ros.internal.node.server.NodeIdentifier; import org.ros.internal.node.server.ParameterServer; import org.ros.internal.node.server.master.MasterServer; import org.ros.namespace.GraphName; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A combined XML-RPC endpoint for the master and parameter servers. * * @author damonkohler@google.com (Damon Kohler) */ public class MasterXmlRpcEndpointImpl implements MasterXmlRpcEndpoint, ParameterServerXmlRpcEndpoint { private final MasterServer master; private final ParameterServer parameterServer; public MasterXmlRpcEndpointImpl(MasterServer master) { this.master = master; parameterServer = new ParameterServer(); } @Override public List<Object> getPid(String callerId) { return Response.newSuccess("server pid", master.getPid()).toList(); } @Override public List<Object> getPublishedTopics(String callerId, String subgraph) { return Response.newSuccess("current topics", master.getPublishedTopics(GraphName.of(callerId), GraphName.of(subgraph))).toList(); } @Override public List<Object> getTopicTypes(String callerId) { return Response.newSuccess("topic types", master.getTopicTypes(GraphName.of(callerId))) .toList(); } @Override public List<Object> getSystemState(String callerId) { return Response.newSuccess("current system state", master.getSystemState()).toList(); } @Override public List<Object> getUri(String callerId) { return Response.newSuccess("Success", master.getUri().toString()).toList(); } @Override public List<Object> lookupNode(String callerId, String nodeName) { URI nodeSlaveUri = master.lookupNode(GraphName.of(nodeName)); if (nodeSlaveUri != null) { return Response.newSuccess("Success", nodeSlaveUri.toString()).toList(); } else { return Response.newError("No such node", null).toList(); } } @Override public List<Object> registerPublisher(String callerId, String topicName, String topicMessageType, String callerSlaveUri) { try { List<URI> subscribers = master.registerPublisher(GraphName.of(callerId), new URI(callerSlaveUri), GraphName.of( topicName), topicMessageType); List<String> urls = Lists.newArrayList(); for (URI uri : subscribers) { urls.add(uri.toString()); } return Response.newSuccess("Success", urls).toList(); } catch (URISyntaxException e) { throw new RosRuntimeException(String.format("Improperly formatted URI %s for publisher", callerSlaveUri), e); } } @Override public List<Object> unregisterPublisher(String callerId, String topicName, String callerSlaveUri) { boolean result = master.unregisterPublisher(GraphName.of(callerId), GraphName.of(topicName)); return Response.newSuccess("Success", result ? 1 : 0).toList(); } @Override public List<Object> registerSubscriber(String callerId, String topicName, String topicMessageType, String callerSlaveUri) { try { List<URI> publishers = master.registerSubscriber(GraphName.of(callerId), new URI(callerSlaveUri), GraphName.of(topicName), topicMessageType); List<String> urls = Lists.newArrayList(); for (URI uri : publishers) { urls.add(uri.toString()); } return Response.newSuccess("Success", urls).toList(); } catch (URISyntaxException e) { throw new RosRuntimeException(String.format("Improperly formatted URI %s for subscriber", callerSlaveUri), e); } } @Override public List<Object> unregisterSubscriber(String callerId, String topicName, String callerSlaveUri) { boolean result = master.unregisterSubscriber(GraphName.of(callerId), GraphName.of(topicName)); return Response.newSuccess("Success", result ? 1 : 0).toList(); } @Override public List<Object> lookupService(String callerId, String serviceName) { URI slaveUri = master.lookupService(GraphName.of(serviceName)); if (slaveUri != null) { return Response.newSuccess("Success", slaveUri.toString()).toList(); } return Response.newError("No such service.", null).toList(); } @Override public List<Object> registerService(String callerId, String serviceName, String serviceUri, String callerSlaveUri) { try { master.registerService(GraphName.of(callerId), new URI(callerSlaveUri), GraphName.of( serviceName), new URI(serviceUri)); return Response.newSuccess("Success", 0).toList(); } catch (URISyntaxException e) { throw new RosRuntimeException(e); } } @Override public List<Object> unregisterService(String callerId, String serviceName, String serviceUri) { try { boolean result = master.unregisterService(GraphName.of(callerId), GraphName.of(serviceName), new URI( serviceUri)); return Response.newSuccess("Success", result ? 1 : 0).toList(); } catch (URISyntaxException e) { throw new RosRuntimeException(e); } } @Override public List<Object> setParam(String callerId, String key, Boolean value) { parameterServer.set(GraphName.of(key), value); return Response.newSuccess("Success", null).toList(); } @Override public List<Object> setParam(String callerId, String key, Integer value) { parameterServer.set(GraphName.of(key), value); return Response.newSuccess("Success", null).toList(); } @Override public List<Object> setParam(String callerId, String key, Double value) { parameterServer.set(GraphName.of(key), value); return Response.newSuccess("Success", null).toList(); } @Override public List<Object> setParam(String callerId, String key, String value) { parameterServer.set(GraphName.of(key), value); return Response.newSuccess("Success", null).toList(); } @Override public List<Object> setParam(String callerId, String key, List<?> value) { parameterServer.set(GraphName.of(key), value); return Response.newSuccess("Success", null).toList(); } @Override public List<Object> setParam(String callerId, String key, Map<?, ?> value) { parameterServer.set(GraphName.of(key), value); return Response.newSuccess("Success", null).toList(); } @Override public List<Object> getParam(String callerId, String key) { Object value = parameterServer.get(GraphName.of(key)); if (value == null) { return Response.newError("Parameter \"" + key + "\" is not set.", null).toList(); } return Response.newSuccess("Success", value).toList(); } @Override public List<Object> searchParam(String callerId, String key) { throw new UnsupportedOperationException(); } @Override public List<Object> subscribeParam(String callerId, String callerSlaveUri, String key) { parameterServer.subscribe(GraphName.of(key), NodeIdentifier.forNameAndUri(callerId, callerSlaveUri)); Object value = parameterServer.get(GraphName.of(key)); if (value == null) { // Must return an empty map as the value of an unset parameter. value = new HashMap<String, Object>(); } return Response.newSuccess("Success", value).toList(); } @Override public List<Object> unsubscribeParam(String callerId, String callerSlaveUri, String key) { throw new UnsupportedOperationException(); } @Override public List<Object> deleteParam(String callerId, String key) { parameterServer.delete(GraphName.of(key)); return Response.newSuccess("Success", null).toList(); } @Override public List<Object> hasParam(String callerId, String key) { return Response.newSuccess("Success", parameterServer.has(GraphName.of(key))).toList(); } @Override public List<Object> getParamNames(String callerId) { Collection<GraphName> names = parameterServer.getNames(); List<String> stringNames = Lists.newArrayList(); for (GraphName name : names) { stringNames.add(name.toString()); } return Response.newSuccess("Success", stringNames).toList(); } }
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.xmlrpc; /** * @author kwc@willowgarage.com (Ken Conley) * @author damonkohler@google.com (Damon Kohler) */ public class XmlRpcTimeoutException extends RuntimeException { public XmlRpcTimeoutException() { } public XmlRpcTimeoutException(Exception e) { super(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.xmlrpc; import java.util.List; /** * An XML-RPC endpoint description of a ROS master. * * @author damonkohler@google.com (Damon Kohler) */ public interface MasterXmlRpcEndpoint extends XmlRpcEndpoint { /** * Get the PID for the master process. * * @param callerId * ROS caller ID * @return The pid of the process. */ List<Object> getPid(String callerId); /** * Register the caller as a provider of the specified service. * * @param callerId * ROS caller ID * @param service * Fully-qualified name of service * @param serviceApi * XML-RPC URI of caller node * @param callerApi * @return ignore */ List<Object> registerService(String callerId, String service, String serviceApi, String callerApi); /** * Unregister the caller as a provider of the specified service. * * @param callerId * ROS caller ID * @param service * Fully-qualified name of service * @param serviceApi * API URI of service to unregister. Unregistration will only occur * if current registration matches. * @return Number of unregistrations (either 0 or 1). If this is zero it means * that the caller was not registered as a service provider. The call * still succeeds as the intended final state is reached. */ List<Object> unregisterService(String callerId, String service, String serviceApi); /** * 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 callerId * ROS caller ID * @param topicName * Fully-qualified name of topic * @param topicType * topic type, must be a package-resource name, i.e. the .msg name * @param callerApi * API URI of subscriber to register. Will be used for new publisher * notifications * @return publishers as a list of XMLRPC API URIs for nodes currently * publishing the specified topic */ List<Object> registerSubscriber(String callerId, String topicName, String topicType, String callerApi); /** * Unregister the caller as a publisher of the topic. * * @param callerId * ROS caller ID * @param topicName * Fully-qualified name of topic. * @param callerApi * API URI of service to unregister. Unregistration will only occur * if current registration matches. * @return If numUnsubscribed is zero it means that the caller was not * registered as a subscriber. The call still succeeds as the intended * final state is reached. */ List<Object> unregisterSubscriber(String callerId, String topicName, String callerApi); /** * Register the caller as a publisher the topic. * * @param callerId * ROS caller ID * @param topicName * fully-qualified name of topic to register * @param topicType * topic type, must be a package-resource name, i.e. the .msg name. * @param callerApi * API URI of publisher to register * @return list of current subscribers of topic in the form of XML-RPC URIs */ List<Object> registerPublisher(String callerId, String topicName, String topicType, String callerApi); /** * Unregister the caller as a publisher of the topic. * * @param callerId * ROS caller ID * @param topicName * Fully-qualified name of topic. * @param callerApi * API URI of publisher to unregister. Unregistration will only occur * if current registration matches. * @return If numUnsubscribed is zero it means that the caller was not * registered as a subscriber. The call still succeeds as the intended * final state is reached. */ List<Object> unregisterPublisher(String callerId, String topicName, String callerApi); /** * Get the XML-RPC URI of the node with the associated name/caller_id. This * API is for looking information about publishers and subscribers. Use * lookupService instead to lookup ROS-RPC URIs. * * @param callerId * ROS caller ID * @param nodeName * Name of node to lookup * @return URI of the node */ List<Object> lookupNode(String callerId, String nodeName); /** * Get list of topics that can be subscribed to. This does not return topics * that have no publishers. See getSystemState() to get more comprehensive * list. * * @param callerId * ROS caller ID * @param subgraph * Restrict topic names to match within the specified subgraph. * Subgraph namespace is resolved relative to the caller's namespace. * Use empty string to specify all names. * @return Topics is in list representation [[topic, message type], [topic, * message type] ...] */ List<Object> getPublishedTopics(String callerId, String subgraph); /** * Get a list of all topic types. * * @param callerId * ROS caller ID * @return The types are in the list representation [[topic, message type], * [topic, message type] ...] */ List<Object> getTopicTypes(String callerId); /** * Retrieve list representation of system state (i.e. publishers, subscribers, * and services). * * @param callerId * ROS caller ID * @return System state is in list representation [publishers, subscribers, * services] publishers is of the form [ [topic1, * [topic1Publisher1...topic1PublisherN]] ... ] subscribers is of the * form [ [topic1, [topic1Subscriber1...topic1SubscriberN]] ... ] * services is of the form [ [service1, * [service1Provider1...service1ProviderN]] ... ] */ List<Object> getSystemState(String callerId); /** * Get the URI of the the master. * * @param callerId * ROS caller ID * @return URI of the the master */ List<Object> getUri(String callerId); /** * Lookup all provider of a particular service. * * @param callerId * ROS caller ID * @param service * Fully-qualified name of service * @return service URL is provides address and port of the service. Fails if * there is no provider. */ List<Object> lookupService(String callerId, String service); }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you 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.xmlrpc; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.client.TimingOutCallback; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.common.TypeConverter; import org.apache.xmlrpc.common.TypeConverterFactory; import org.apache.xmlrpc.common.TypeConverterFactoryImpl; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; /** * Modified version of {@link org.apache.xmlrpc.client.util.ClientFactory} that * requires timeouts in calls. * * @param <T> * the type of {@link XmlRpcEndpoint} to create clients for * * @author kwc@willowgarage.com (Ken Conley) * @author damonkohler@google.com (Damon Kohler) */ public class XmlRpcClientFactory<T extends org.ros.internal.node.xmlrpc.XmlRpcEndpoint> { private final XmlRpcClient client; private final TypeConverterFactory typeConverterFactory; private boolean objectMethodLocal; /** * Creates a new instance. * * @param pClient * A fully configured XML-RPC client, which is used internally to * perform XML-RPC calls. * @param pTypeConverterFactory * Creates instances of {@link TypeConverterFactory}, which are used * to transform the result object in its target representation. */ public XmlRpcClientFactory(XmlRpcClient pClient, TypeConverterFactory pTypeConverterFactory) { typeConverterFactory = pTypeConverterFactory; client = pClient; } /** * Creates a new instance. Shortcut for * * <pre> * new ClientFactory(pClient, new TypeConverterFactoryImpl()); * </pre> * * @param pClient * A fully configured XML-RPC client, which is used internally to * perform XML-RPC calls. * @see TypeConverterFactoryImpl */ public XmlRpcClientFactory(XmlRpcClient pClient) { this(pClient, new TypeConverterFactoryImpl()); } /** * Returns the factories client. */ public XmlRpcClient getClient() { return client; } /** * Returns, whether a method declared by the {@link Object Object class} is * performed by the local object, rather than by the server. Defaults to true. */ public boolean isObjectMethodLocal() { return objectMethodLocal; } /** * Sets, whether a method declared by the {@link Object Object class} is * performed by the local object, rather than by the server. Defaults to true. */ public void setObjectMethodLocal(boolean pObjectMethodLocal) { objectMethodLocal = pObjectMethodLocal; } /** * Creates an object, which is implementing the given interface. The objects * methods are internally calling an XML-RPC server by using the factories * client. * * @param pClassLoader * The class loader, which is being used for loading classes, if * required. * @param pClass * Interface, which is being implemented. * @param pRemoteName * Handler name, which is being used when calling the server. This is * used for composing the method name. For example, if * <code>pRemoteName</code> is "Foo" and you want to invoke the * method "bar" in the handler, then the full method name would be * "Foo.bar". */ public Object newInstance(ClassLoader pClassLoader, final Class<T> pClass, final String pRemoteName, final int timeout) { return Proxy.newProxyInstance(pClassLoader, new Class[] { pClass }, new InvocationHandler() { @Override public Object invoke(Object pProxy, Method pMethod, Object[] pArgs) throws Throwable { if (isObjectMethodLocal() && pMethod.getDeclaringClass().equals(Object.class)) { return pMethod.invoke(pProxy, pArgs); } final String methodName; if (pRemoteName == null || pRemoteName.length() == 0) { methodName = pMethod.getName(); } else { methodName = pRemoteName + "." + pMethod.getName(); } Object result; try { TimingOutCallback callback = new TimingOutCallback(timeout); client.executeAsync(methodName, pArgs, callback); result = callback.waitForResponse(); } catch (TimingOutCallback.TimeoutException e) { throw new XmlRpcTimeoutException(e); } catch (InterruptedException e) { throw new XmlRpcTimeoutException(e); } catch (UndeclaredThrowableException e) { throw new RuntimeException(e); } catch (XmlRpcException e) { Throwable linkedException = e.linkedException; if (linkedException == null) { throw new RuntimeException(e); } Class<?>[] exceptionTypes = pMethod.getExceptionTypes(); for (int i = 0; i < exceptionTypes.length; i++) { Class<?> c = exceptionTypes[i]; if (c.isAssignableFrom(linkedException.getClass())) { throw linkedException; } } throw new RuntimeException(linkedException); } TypeConverter typeConverter = typeConverterFactory.getTypeConverter(pMethod.getReturnType()); return typeConverter.convert(result); } }); } }
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.xmlrpc; /** * Represents the XML-RPC interface for a client or server. * * @author damonkohler@google.com (Damon Kohler) */ public interface XmlRpcEndpoint { }
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.xmlrpc; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ros.internal.node.response.Response; import org.ros.internal.node.response.StatusCode; import org.ros.internal.node.server.ServerException; import org.ros.internal.node.server.SlaveServer; import org.ros.internal.node.topic.DefaultPublisher; import org.ros.internal.node.topic.DefaultSubscriber; import org.ros.internal.transport.ProtocolDescription; import org.ros.namespace.GraphName; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; /** * @author damonkohler@google.com (Damon Kohler) */ public class SlaveXmlRpcEndpointImpl implements SlaveXmlRpcEndpoint { private static final boolean DEBUG = false; private static final Log log = LogFactory.getLog(SlaveXmlRpcEndpointImpl.class); private final SlaveServer slave; public SlaveXmlRpcEndpointImpl(SlaveServer slave) { this.slave = slave; } @Override public List<Object> getBusStats(String callerId) { return slave.getBusStats(callerId); } @Override public List<Object> getBusInfo(String callerId) { List<Object> busInfo = slave.getBusInfo(callerId); return Response.newSuccess("bus info", busInfo).toList(); } @Override public List<Object> getMasterUri(String callerId) { URI uri = slave.getMasterUri(); return new Response<String>(StatusCode.SUCCESS, "", uri.toString()).toList(); } @Override public List<Object> shutdown(String callerId, String message) { log.info("Shutdown requested by " + callerId + " with message \"" + message + "\""); slave.shutdown(); return Response.newSuccess("Shutdown successful.", null).toList(); } @Override public List<Object> getPid(String callerId) { try { int pid = slave.getPid(); return Response.newSuccess("PID: " + pid, pid).toList(); } catch (UnsupportedOperationException e) { return Response.newFailure("Cannot retrieve PID on this platform.", -1).toList(); } } @Override public List<Object> getSubscriptions(String callerId) { Collection<DefaultSubscriber<?>> subscribers = slave.getSubscriptions(); List<List<String>> subscriptions = Lists.newArrayList(); for (DefaultSubscriber<?> subscriber : subscribers) { subscriptions.add(subscriber.getTopicDeclarationAsList()); } return Response.newSuccess("Success", subscriptions).toList(); } @Override public List<Object> getPublications(String callerId) { Collection<DefaultPublisher<?>> publishers = slave.getPublications(); List<List<String>> publications = Lists.newArrayList(); for (DefaultPublisher<?> publisher : publishers) { publications.add(publisher.getTopicDeclarationAsList()); } return Response.newSuccess("Success", publications).toList(); } private List<Object> parameterUpdate(String parameterName, Object parameterValue) { if (slave.paramUpdate(GraphName.of(parameterName), parameterValue) > 0) { return Response.newSuccess("Success", null).toList(); } return Response .newError("No subscribers for parameter key \"" + parameterName + "\".", null).toList(); } @Override public List<Object> paramUpdate(String callerId, String key, boolean value) { return parameterUpdate(key, value); } @Override public List<Object> paramUpdate(String callerId, String key, char value) { return parameterUpdate(key, value); } @Override public List<Object> paramUpdate(String callerId, String key, byte value) { return parameterUpdate(key, value); } @Override public List<Object> paramUpdate(String callerId, String key, short value) { return parameterUpdate(key, value); } @Override public List<Object> paramUpdate(String callerId, String key, int value) { return parameterUpdate(key, value); } @Override public List<Object> paramUpdate(String callerId, String key, double value) { return parameterUpdate(key, value); } @Override public List<Object> paramUpdate(String callerId, String key, String value) { return parameterUpdate(key, value); } @Override public List<Object> paramUpdate(String callerId, String key, List<?> value) { return parameterUpdate(key, value); } @Override public List<Object> paramUpdate(String callerId, String key, Vector<?> value) { return parameterUpdate(key, value); } @Override public List<Object> paramUpdate(String callerId, String key, Map<?, ?> value) { return parameterUpdate(key, value); } @Override public List<Object> publisherUpdate(String callerId, String topicName, Object[] publishers) { try { ArrayList<URI> publisherUris = new ArrayList<URI>(publishers.length); for (Object publisher : publishers) { URI uri = new URI(publisher.toString()); if (!uri.getScheme().equals("http") && !uri.getScheme().equals("https")) { return Response.newError("Unknown URI scheme sent in update.", 0).toList(); } publisherUris.add(uri); } slave.publisherUpdate(callerId, topicName, publisherUris); return Response.newSuccess("Publisher update received.", 0).toList(); } catch (URISyntaxException e) { return Response.newError("Invalid URI sent in update.", 0).toList(); } } @Override public List<Object> requestTopic(String callerId, String topic, Object[] protocols) { Set<String> requestedProtocols = Sets.newHashSet(); for (int i = 0; i < protocols.length; i++) { requestedProtocols.add((String) ((Object[]) protocols[i])[0]); } ProtocolDescription protocol; try { protocol = slave.requestTopic(topic, requestedProtocols); } catch (ServerException e) { return Response.newError(e.getMessage(), null).toList(); } List<Object> response = Response.newSuccess(protocol.toString(), protocol.toList()).toList(); if (DEBUG) { log.info("requestTopic(" + topic + ", " + requestedProtocols + ") response: " + response.toString()); } return 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.xmlrpc; import org.ros.internal.node.server.ParameterServer; import java.util.Collection; import java.util.List; import java.util.Map; /** * XML-RPC endpoint for a parameter server. * * @author damonkohler@google.com (Damon Kohler) */ public interface ParameterServerXmlRpcEndpoint extends XmlRpcEndpoint { /** * Deletes a parameter. * * @param callerId * ROS caller ID * @param key * parameter name * @return void */ public List<Object> deleteParam(String callerId, String key); /** * Sets a parameter. * * <p> * NOTE: if value is a dictionary it will be treated as a parameter tree, * where key is the parameter namespace. For example * {'x':1,'y':2,'sub':{'z':3}} will set key/x=1, key/y=2, and key/sub/z=3. * Furthermore, it will replace all existing parameters in the key parameter * namespace with the parameters in value. You must set parameters * individually if you wish to perform a union update. * * @param callerId * ROS caller ID * @param key * Parameter name. * @param value * Parameter value. * @return void */ public List<Object> setParam(String callerId, String key, Boolean value); public List<Object> setParam(String callerId, String key, Integer value); public List<Object> setParam(String callerId, String key, Double value); public List<Object> setParam(String callerId, String key, String value); public List<Object> setParam(String callerId, String key, List<?> value); public List<Object> setParam(String callerId, String key, Map<?, ?> value); /** * Retrieve parameter value from server. * * <p> * If code is not 1, parameterValue should be ignored. If key is a namespace, * the return value will be a dictionary, where each key is a parameter in * that namespace. Sub-namespaces are also represented as dictionaries. * * @param callerId * ROS caller ID * @param key * Parameter name. If key is a namespace, getParam() will return a * parameter tree. * @return the parameter value */ public List<Object> getParam(String callerId, String key); /** * Searches for a parameter key on the {@link ParameterServer}. * * <p> * Search starts in caller's namespace and proceeds upwards through parent * namespaces until Parameter Server finds a matching key. searchParam()'s * behavior is to search for the first partial match. For example, imagine * that there are two 'robot_description' parameters /robot_description * /robot_description/arm /robot_description/base /pr2/robot_description * /pr2/robot_description/base If I start in the namespace /pr2/foo and search * for robot_description, searchParam() will match /pr2/robot_description. If * I search for robot_description/arm it will return * /pr2/robot_description/arm, even though that parameter does not exist * (yet). * * If code is not 1, foundKey should be ignored. * * @param callerId * ROS caller ID * @param key * Parameter name to search for. * @return the found key */ public List<Object> searchParam(String callerId, String key); /** * Retrieves the parameter value from server and subscribe to updates to that * param. See paramUpdate() in the Node API. * * <p> * If code is not 1, parameterValue should be ignored. parameterValue is an * empty dictionary if the parameter has not been set yet. * * @param callerId * ROS caller ID * @param callerApi * Node API URI of subscriber for paramUpdate callbacks. * @param key * @return the parameter value */ public List<Object> subscribeParam(String callerId, String callerApi, String key); /** * Unsubscribes from updates to the specified param. See paramUpdate() in the * Node API. * * <p> * A return value of zero means that the caller was not subscribed to the * parameter. * * @param callerId * ROS caller ID * @param callerApi * Node API URI of subscriber * @param key * Parameter name * @return the number of parameters that were unsubscribed */ public List<Object> unsubscribeParam(String callerId, String callerApi, String key); /** * Check if parameter is stored on server. * * @param callerId * ROS caller ID. * @param key * Parameter name. * @return {@code true} if the parameter exists */ public List<Object> hasParam(String callerId, String key); /** * Gets the list of all parameter names stored on this server. * * @param callerId * ROS caller ID. * @return a {@link Collection} of parameter names */ public List<Object> getParamNames(String callerId); }
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 clients. * <p> * These classes should _not_ be used directly outside of the org.ros package. */ package org.ros.internal.node.client;
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.client; import com.google.common.collect.Lists; import org.ros.internal.node.response.IntegerResultFactory; import org.ros.internal.node.response.ProtocolDescriptionResultFactory; import org.ros.internal.node.response.Response; import org.ros.internal.node.response.TopicListResultFactory; import org.ros.internal.node.response.UriResultFactory; import org.ros.internal.node.response.VoidResultFactory; import org.ros.internal.node.topic.TopicDeclaration; import org.ros.internal.node.xmlrpc.SlaveXmlRpcEndpoint; import org.ros.internal.transport.ProtocolDescription; import org.ros.namespace.GraphName; import java.net.URI; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author damonkohler@google.com (Damon Kohler) */ public class SlaveClient extends Client<SlaveXmlRpcEndpoint> { private final GraphName nodeName; public SlaveClient(GraphName nodeName, URI uri) { super(uri, SlaveXmlRpcEndpoint.class); this.nodeName = nodeName; } public List<Object> getBusStats() { throw new UnsupportedOperationException(); } public List<Object> getBusInfo() { throw new UnsupportedOperationException(); } public Response<URI> getMasterUri() { return Response.fromListChecked(xmlRpcEndpoint.getMasterUri(nodeName.toString()), new UriResultFactory()); } public Response<Void> shutdown(String message) { return Response.fromListChecked(xmlRpcEndpoint.shutdown("/master", message), new VoidResultFactory()); } public Response<Integer> getPid() { return Response.fromListChecked(xmlRpcEndpoint.getPid(nodeName.toString()), new IntegerResultFactory()); } public Response<List<TopicDeclaration>> getSubscriptions() { return Response.fromListChecked(xmlRpcEndpoint.getSubscriptions(nodeName.toString()), new TopicListResultFactory()); } public Response<List<TopicDeclaration>> getPublications() { return Response.fromListChecked(xmlRpcEndpoint.getPublications(nodeName.toString()), new TopicListResultFactory()); } public Response<Void> paramUpdate(GraphName name, boolean value) { return Response.fromListChecked(xmlRpcEndpoint.paramUpdate(nodeName.toString(), name.toString(), value), new VoidResultFactory()); } public Response<Void> paramUpdate(GraphName name, char value) { return Response.fromListChecked(xmlRpcEndpoint.paramUpdate(nodeName.toString(), name.toString(), value), new VoidResultFactory()); } public Response<Void> paramUpdate(GraphName name, int value) { return Response.fromListChecked(xmlRpcEndpoint.paramUpdate(nodeName.toString(), name.toString(), value), new VoidResultFactory()); } public Response<Void> paramUpdate(GraphName name, double value) { return Response.fromListChecked(xmlRpcEndpoint.paramUpdate(nodeName.toString(), name.toString(), value), new VoidResultFactory()); } public Response<Void> paramUpdate(GraphName name, String value) { return Response.fromListChecked(xmlRpcEndpoint.paramUpdate(nodeName.toString(), name.toString(), value), new VoidResultFactory()); } public Response<Void> paramUpdate(GraphName name, List<?> value) { return Response.fromListChecked(xmlRpcEndpoint.paramUpdate(nodeName.toString(), name.toString(), value), new VoidResultFactory()); } public Response<Void> paramUpdate(GraphName name, Map<?, ?> value) { return Response.fromListChecked(xmlRpcEndpoint.paramUpdate(nodeName.toString(), name.toString(), value), new VoidResultFactory()); } public Response<Void> publisherUpdate(GraphName topic, Collection<URI> publisherUris) { List<String> publishers = Lists.newArrayList(); for (URI uri : publisherUris) { publishers.add(uri.toString()); } return Response.fromListChecked( xmlRpcEndpoint.publisherUpdate(nodeName.toString(), topic.toString(), publishers.toArray()), new VoidResultFactory()); } public Response<ProtocolDescription> requestTopic(GraphName topic, Collection<String> requestedProtocols) { return Response.fromListChecked(xmlRpcEndpoint.requestTopic(nodeName.toString(), topic.toString(), new Object[][] { requestedProtocols.toArray() }), new ProtocolDescriptionResultFactory()); } }
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.client; import org.ros.internal.node.response.IntegerResultFactory; import org.ros.internal.node.response.Response; import org.ros.internal.node.response.SystemStateResultFactory; import org.ros.internal.node.response.TopicListResultFactory; import org.ros.internal.node.response.TopicTypeListResultFactory; import org.ros.internal.node.response.UriListResultFactory; import org.ros.internal.node.response.UriResultFactory; import org.ros.internal.node.response.VoidResultFactory; import org.ros.internal.node.server.NodeIdentifier; import org.ros.internal.node.server.SlaveServer; import org.ros.internal.node.server.master.MasterServer; import org.ros.internal.node.topic.PublisherDeclaration; import org.ros.internal.node.topic.PublisherIdentifier; import org.ros.internal.node.topic.TopicDeclaration; import org.ros.internal.node.xmlrpc.MasterXmlRpcEndpoint; import org.ros.master.client.SystemState; import org.ros.master.client.TopicSystemState; import org.ros.master.client.TopicType; import org.ros.namespace.GraphName; 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.List; /** * Provides access to the XML-RPC API exposed by a {@link MasterServer}. * * @author damonkohler@google.com (Damon Kohler) */ public class MasterClient extends Client<MasterXmlRpcEndpoint> { /** * Create a new {@link MasterClient} connected to the specified * {@link MasterServer} URI. * * @param uri * the {@link URI} of the {@link MasterServer} to connect to */ public MasterClient(URI uri) { super(uri, MasterXmlRpcEndpoint.class); } /** * Registers the given {@link ServiceServer}. * * @param slave * the {@link NodeIdentifier} where the {@link ServiceServer} is * running * @param service * the {@link ServiceServer} to register * @return a void {@link Response} */ public Response<Void> registerService(NodeIdentifier slave, ServiceServer<?, ?> service) { return Response.fromListChecked(xmlRpcEndpoint.registerService(slave.getName().toString(), service.getName().toString(), service.getUri().toString(), slave.getUri().toString()), new VoidResultFactory()); } /** * Unregisters the specified {@link ServiceServer}. * * @param slave * the {@link NodeIdentifier} where the {@link ServiceServer} is * running * @param service * the {@link ServiceServer} to unregister * @return the number of unregistered services */ public Response<Integer> unregisterService(NodeIdentifier slave, ServiceServer<?, ?> service) { return Response.fromListChecked(xmlRpcEndpoint.unregisterService( slave.getName().toString(), service.getName().toString(), service.getUri().toString()), new IntegerResultFactory()); } /** * Registers the given {@link Subscriber}. In addition to receiving a list of * current {@link Publisher}s, the {@link Subscriber}s {@link SlaveServer} * will also receive notifications of new {@link Publisher}s via the * publisherUpdate API. * * @param slave * the {@link NodeIdentifier} that the {@link Subscriber} is running * on * @param subscriber * the {@link Subscriber} to register * @return a {@link List} or {@link SlaveServer} XML-RPC API URIs for nodes * currently publishing the specified topic */ public Response<List<URI>> registerSubscriber(NodeIdentifier slave, Subscriber<?> subscriber) { return Response.fromListChecked(xmlRpcEndpoint.registerSubscriber(slave.getName() .toString(), subscriber.getTopicName().toString(), subscriber.getTopicMessageType(), slave .getUri().toString()), new UriListResultFactory()); } /** * Unregisters the specified {@link Subscriber}. * * @param slave * the {@link NodeIdentifier} where the subscriber is running * @param subscriber * the {@link Subscriber} to unregister * @return the number of unregistered {@link Subscriber}s */ public Response<Integer> unregisterSubscriber(NodeIdentifier slave, Subscriber<?> subscriber) { return Response.fromListChecked(xmlRpcEndpoint.unregisterSubscriber(slave.getName() .toString(), subscriber.getTopicName().toString(), slave.getUri().toString()), new IntegerResultFactory()); } /** * Registers the specified {@link PublisherDeclaration}. * * @param publisherDeclaration * the {@link PublisherDeclaration} of the {@link Publisher} to * register * @return a {@link List} of the current {@link SlaveServer} URIs which have * {@link Subscriber}s for the published {@link TopicSystemState} */ public Response<List<URI>> registerPublisher(PublisherDeclaration publisherDeclaration) { String slaveName = publisherDeclaration.getSlaveName().toString(); String slaveUri = publisherDeclaration.getSlaveUri().toString(); String topicName = publisherDeclaration.getTopicName().toString(); String messageType = publisherDeclaration.getTopicMessageType(); return Response.fromListChecked( xmlRpcEndpoint.registerPublisher(slaveName, topicName, messageType, slaveUri), new UriListResultFactory()); } /** * Unregisters the specified {@link PublisherDeclaration}. * * @param publisherIdentifier * the {@link PublisherIdentifier} of the {@link Publisher} to * unregister * @return the number of unregistered {@link Publisher}s */ public Response<Integer> unregisterPublisher(PublisherIdentifier publisherIdentifier) { String slaveName = publisherIdentifier.getNodeName().toString(); String slaveUri = publisherIdentifier.getNodeUri().toString(); String topicName = publisherIdentifier.getTopicName().toString(); return Response.fromListChecked( xmlRpcEndpoint.unregisterPublisher(slaveName, topicName, slaveUri), new IntegerResultFactory()); } /** * @param slaveName * the {@link GraphName} of the caller * @param nodeName * the name of the {@link SlaveServer} to lookup * @return the {@link URI} of the {@link SlaveServer} with the given name */ public Response<URI> lookupNode(GraphName slaveName, String nodeName) { return Response.fromListChecked(xmlRpcEndpoint.lookupNode(slaveName.toString(), nodeName), new UriResultFactory()); } /** * @param slaveName * the {@link NodeIdentifier} of the caller * @return the {@link URI} of the {@link MasterServer} */ public Response<URI> getUri(GraphName slaveName) { return Response.fromListChecked(xmlRpcEndpoint.getUri(slaveName.toString()), new UriResultFactory()); } /** * @param callerName * the {@link GraphName} of the caller * @param serviceName * the name of the {@link ServiceServer} to look up * @return the {@link URI} of the {@link ServiceServer} with the given name. * {@link ServiceServer} as a result */ public Response<URI> lookupService(GraphName callerName, String serviceName) { return Response.fromListCheckedFailure( xmlRpcEndpoint.lookupService(callerName.toString(), serviceName), new UriResultFactory()); } /** * @param callerName * the {@link GraphName} of the caller * @param subgraph * the subgraph of the topics * @return the list of published {@link TopicDeclaration}s */ public Response<List<TopicDeclaration>> getPublishedTopics(GraphName callerName, String subgraph) { return Response.fromListChecked( xmlRpcEndpoint.getPublishedTopics(callerName.toString(), subgraph), new TopicListResultFactory()); } /** * Get a {@link List} of all {@link TopicSystemState} message types. * * @param callerName * the {@link GraphName} of the caller * @return a {@link List} of {@link TopicType}s */ public Response<List<TopicType>> getTopicTypes(GraphName callerName) { return Response.fromListChecked(xmlRpcEndpoint.getTopicTypes(callerName.toString()), new TopicTypeListResultFactory()); } /** * @param callerName * the {@link GraphName} of the caller * @return the current {@link SystemState} */ public Response<SystemState> getSystemState(GraphName callerName) { return Response.fromListChecked(xmlRpcEndpoint.getSystemState(callerName.toString()), new SystemStateResultFactory()); } }
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.client; import com.google.common.collect.Lists; import org.ros.internal.node.response.BooleanResultFactory; import org.ros.internal.node.response.IntegerResultFactory; import org.ros.internal.node.response.ObjectResultFactory; import org.ros.internal.node.response.Response; import org.ros.internal.node.response.StringListResultFactory; import org.ros.internal.node.response.StringResultFactory; import org.ros.internal.node.response.VoidResultFactory; import org.ros.internal.node.server.NodeIdentifier; import org.ros.internal.node.server.ParameterServer; import org.ros.internal.node.xmlrpc.ParameterServerXmlRpcEndpoint; import org.ros.namespace.GraphName; import java.net.URI; import java.util.List; import java.util.Map; /** * Provide access to the XML-RPC API for a ROS {@link ParameterServer}. * * @author kwc@willowgarage.com (Ken Conley) * @author damonkohler@google.com (Damon Kohler) */ public class ParameterClient extends Client<ParameterServerXmlRpcEndpoint> { private final NodeIdentifier nodeIdentifier; private final String nodeName; /** * Create a new {@link ParameterClient} connected to the specified * {@link ParameterServer} URI. * * @param uri * the {@link URI} of the {@link ParameterServer} to connect to */ public ParameterClient(NodeIdentifier nodeIdentifier, URI uri) { super(uri, ParameterServerXmlRpcEndpoint.class); this.nodeIdentifier = nodeIdentifier; nodeName = nodeIdentifier.getName().toString(); } public Response<Object> getParam(GraphName parameterName) { return Response.fromListCheckedFailure(xmlRpcEndpoint.getParam(nodeName, parameterName.toString()), new ObjectResultFactory()); } public Response<Void> setParam(GraphName parameterName, Boolean parameterValue) { return Response.fromListChecked( xmlRpcEndpoint.setParam(nodeName, parameterName.toString(), parameterValue), new VoidResultFactory()); } public Response<Void> setParam(GraphName parameterName, Integer parameterValue) { return Response.fromListChecked( xmlRpcEndpoint.setParam(nodeName, parameterName.toString(), parameterValue), new VoidResultFactory()); } public Response<Void> setParam(GraphName parameterName, Double parameterValue) { return Response.fromListChecked( xmlRpcEndpoint.setParam(nodeName, parameterName.toString(), parameterValue), new VoidResultFactory()); } public Response<Void> setParam(GraphName parameterName, String parameterValue) { return Response.fromListChecked( xmlRpcEndpoint.setParam(nodeName, parameterName.toString(), parameterValue), new VoidResultFactory()); } public Response<Void> setParam(GraphName parameterName, List<?> parameterValue) { return Response.fromListChecked( xmlRpcEndpoint.setParam(nodeName, parameterName.toString(), parameterValue), new VoidResultFactory()); } public Response<Void> setParam(GraphName parameterName, Map<?, ?> parameterValue) { return Response.fromListChecked( xmlRpcEndpoint.setParam(nodeName, parameterName.toString(), parameterValue), new VoidResultFactory()); } public Response<GraphName> searchParam(GraphName parameterName) { Response<String> response = Response.fromListCheckedFailure(xmlRpcEndpoint.searchParam(nodeName, parameterName.toString()), new StringResultFactory()); return new Response<GraphName>(response.getStatusCode(), response.getStatusMessage(), GraphName.of(response.getResult())); } public Response<Object> subscribeParam(GraphName parameterName) { return Response.fromListChecked(xmlRpcEndpoint.subscribeParam(nodeName, nodeIdentifier.getUri() .toString(), parameterName.toString()), new ObjectResultFactory()); } public Response<Integer> unsubscribeParam(GraphName parameterName) { return Response.fromListChecked( xmlRpcEndpoint.unsubscribeParam(nodeName, nodeIdentifier.getUri().toString(), parameterName.toString()), new IntegerResultFactory()); } public Response<Boolean> hasParam(GraphName parameterName) { return Response.fromListChecked(xmlRpcEndpoint.hasParam(nodeName, parameterName.toString()), new BooleanResultFactory()); } public Response<Void> deleteParam(GraphName parameterName) { return Response.fromListChecked(xmlRpcEndpoint.deleteParam(nodeName, parameterName.toString()), new VoidResultFactory()); } public Response<List<GraphName>> getParamNames() { Response<List<String>> response = Response.fromListChecked(xmlRpcEndpoint.getParamNames(nodeName), new StringListResultFactory()); List<GraphName> graphNames = Lists.newArrayList(); for (String name : response.getResult()) { graphNames.add(GraphName.of(name)); } return new Response<List<GraphName>>(response.getStatusCode(), response.getStatusMessage(), graphNames); } }
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.client; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory; import org.ros.exception.RosRuntimeException; import org.ros.internal.node.server.XmlRpcServer; import org.ros.internal.node.xmlrpc.XmlRpcClientFactory; import org.ros.internal.node.xmlrpc.XmlRpcEndpoint; import java.net.MalformedURLException; import java.net.URI; /** * Base class for XML-RPC clients (e.g. MasterClient and SlaveClient). * * @author damonkohler@google.com (Damon Kohler) * * @param <T> * the XML-RPC interface this {@link Client} connects to */ abstract class Client<T extends XmlRpcEndpoint> { // TODO(damonkohler): This should be pulled out into a user configurable // strategy. private static final int CONNECTION_TIMEOUT = 60 * 1000; // 60 seconds private static final int REPLY_TIMEOUT = 60 * 1000; // 60 seconds private static final int XMLRPC_TIMEOUT = 10 * 1000; // 10 seconds private final URI uri; protected final T xmlRpcEndpoint; /** * @param uri * the {@link URI} to connect to * @param interfaceClass * the class literal for the XML-RPC interface */ public Client(URI uri, Class<T> interfaceClass) { this.uri = uri; XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(uri.toURL()); } catch (MalformedURLException e) { throw new RosRuntimeException(e); } config.setConnectionTimeout(CONNECTION_TIMEOUT); config.setReplyTimeout(REPLY_TIMEOUT); XmlRpcClient client = new XmlRpcClient(); client.setTransportFactory(new XmlRpcCommonsTransportFactory(client)); client.setConfig(config); XmlRpcClientFactory<T> factory = new XmlRpcClientFactory<T>(client); xmlRpcEndpoint = interfaceClass.cast(factory.newInstance(getClass().getClassLoader(), interfaceClass, "", XMLRPC_TIMEOUT)); } /** * @return the {@link URI} of the remote {@link XmlRpcServer} */ public URI getRemoteUri() { return uri; } }
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.client; import com.google.common.base.Preconditions; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ros.concurrent.Holder; import org.ros.concurrent.RetryingExecutorService; import org.ros.exception.RosRuntimeException; 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.server.master.MasterServer; import org.ros.internal.node.service.DefaultServiceServer; import org.ros.internal.node.service.ServiceManagerListener; 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.TopicParticipantManagerListener; import java.net.URI; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Manages topic, and service registrations of a {@link SlaveServer} with the * {@link MasterServer}. * * @author kwc@willowgarage.com (Ken Conley) * @author damonkohler@google.com (Damon Kohler) */ public class Registrar implements TopicParticipantManagerListener, ServiceManagerListener { private static final boolean DEBUG = true; private static final Log log = LogFactory.getLog(Registrar.class); private static final int SHUTDOWN_TIMEOUT = 5; private static final TimeUnit SHUTDOWN_TIMEOUT_UNITS = TimeUnit.SECONDS; private final MasterClient masterClient; private final ScheduledExecutorService executorService; private final RetryingExecutorService retryingExecutorService; private NodeIdentifier nodeIdentifier; private boolean running; /** * @param masterClient * a {@link MasterClient} for communicating with the ROS master * @param executorService * a {@link ScheduledExecutorService} to be used for all asynchronous * operations */ public Registrar(MasterClient masterClient, ScheduledExecutorService executorService) { this.masterClient = masterClient; this.executorService = executorService; retryingExecutorService = new RetryingExecutorService(executorService); nodeIdentifier = null; running = false; if (DEBUG) { log.info("MasterXmlRpcEndpoint URI: " + masterClient.getRemoteUri()); } } /** * Failed registration actions are retried periodically until they succeed. * This method adjusts the delay between successive retry attempts for any * particular registration action. * * @param delay * the delay in units of {@code unit} between retries * @param unit * the unit of {@code delay} */ public void setRetryDelay(long delay, TimeUnit unit) { retryingExecutorService.setRetryDelay(delay, unit); } private boolean submit(Callable<Boolean> callable) { if (running) { retryingExecutorService.submit(callable); return true; } log.warn("Registrar no longer running, request ignored."); return false; } private <T> boolean callMaster(Callable<Response<T>> callable) { Preconditions.checkNotNull(nodeIdentifier, "Registrar not started."); boolean success; try { Response<T> response = callable.call(); if (DEBUG) { log.info(response); } success = response.isSuccess(); } catch (Exception e) { if (DEBUG) { log.error("Exception caught while communicating with master.", e); } else { log.error("Exception caught while communicating with master."); } success = false; } return success; } @Override public void onPublisherAdded(final DefaultPublisher<?> publisher) { if (DEBUG) { log.info("Registering publisher: " + publisher); } boolean submitted = submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { boolean success = callMaster(new Callable<Response<List<URI>>>() { @Override public Response<List<URI>> call() throws Exception { return masterClient.registerPublisher(publisher.toDeclaration()); } }); if (success) { publisher.signalOnMasterRegistrationSuccess(); } else { publisher.signalOnMasterRegistrationFailure(); } return !success; } }); if (!submitted) { executorService.execute(new Runnable() { @Override public void run() { publisher.signalOnMasterRegistrationFailure(); } }); } } @Override public void onPublisherRemoved(final DefaultPublisher<?> publisher) { if (DEBUG) { log.info("Unregistering publisher: " + publisher); } boolean submitted = submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { boolean success = callMaster(new Callable<Response<Integer>>() { @Override public Response<Integer> call() throws Exception { return masterClient.unregisterPublisher(publisher.getIdentifier()); } }); if (success) { publisher.signalOnMasterUnregistrationSuccess(); } else { publisher.signalOnMasterUnregistrationFailure(); } return !success; } }); if (!submitted) { executorService.execute(new Runnable() { @Override public void run() { publisher.signalOnMasterUnregistrationFailure(); } }); } } @Override public void onSubscriberAdded(final DefaultSubscriber<?> subscriber) { if (DEBUG) { log.info("Registering subscriber: " + subscriber); } boolean submitted = submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { final Holder<Response<List<URI>>> holder = Holder.newEmpty(); boolean success = callMaster(new Callable<Response<List<URI>>>() { @Override public Response<List<URI>> call() throws Exception { return holder.set(masterClient.registerSubscriber(nodeIdentifier, subscriber)); } }); if (success) { Collection<PublisherIdentifier> publisherIdentifiers = PublisherIdentifier.newCollectionFromUris(holder.get().getResult(), subscriber.getTopicDeclaration()); subscriber.updatePublishers(publisherIdentifiers); subscriber.signalOnMasterRegistrationSuccess(); } else { subscriber.signalOnMasterRegistrationFailure(); } return !success; } }); if (!submitted) { executorService.execute(new Runnable() { @Override public void run() { subscriber.signalOnMasterRegistrationFailure(); } }); } } @Override public void onSubscriberRemoved(final DefaultSubscriber<?> subscriber) { if (DEBUG) { log.info("Unregistering subscriber: " + subscriber); } boolean submitted = submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { boolean success = callMaster(new Callable<Response<Integer>>() { @Override public Response<Integer> call() throws Exception { return masterClient.unregisterSubscriber(nodeIdentifier, subscriber); } }); if (success) { subscriber.signalOnMasterUnregistrationSuccess(); } else { subscriber.signalOnMasterUnregistrationFailure(); } return !success; } }); if (!submitted) { executorService.execute(new Runnable() { @Override public void run() { subscriber.signalOnMasterUnregistrationFailure(); } }); } } @Override public void onServiceServerAdded(final DefaultServiceServer<?, ?> serviceServer) { if (DEBUG) { log.info("Registering service: " + serviceServer); } boolean submitted = submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { boolean success = callMaster(new Callable<Response<Void>>() { @Override public Response<Void> call() throws Exception { return masterClient.registerService(nodeIdentifier, serviceServer); } }); if (success) { serviceServer.signalOnMasterRegistrationSuccess(); } else { serviceServer.signalOnMasterRegistrationFailure(); } return !success; } }); if (!submitted) { executorService.execute(new Runnable() { @Override public void run() { serviceServer.signalOnMasterRegistrationFailure(); } }); } } @Override public void onServiceServerRemoved(final DefaultServiceServer<?, ?> serviceServer) { if (DEBUG) { log.info("Unregistering service: " + serviceServer); } boolean submitted = submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { boolean success = callMaster(new Callable<Response<Integer>>() { @Override public Response<Integer> call() throws Exception { return masterClient.unregisterService(nodeIdentifier, serviceServer); } }); if (success) { serviceServer.signalOnMasterUnregistrationSuccess(); } else { serviceServer.signalOnMasterUnregistrationFailure(); } return !success; } }); if (!submitted) { executorService.execute(new Runnable() { @Override public void run() { serviceServer.signalOnMasterUnregistrationFailure(); } }); } } /** * Starts the {@link Registrar} for the {@link SlaveServer} identified by the * given {@link NodeIdentifier}. * * @param nodeIdentifier * the {@link NodeIdentifier} for the {@link SlaveServer} this * {@link Registrar} is responsible for */ public void start(NodeIdentifier nodeIdentifier) { Preconditions.checkNotNull(nodeIdentifier); Preconditions.checkState(this.nodeIdentifier == null, "Registrar already started."); this.nodeIdentifier = nodeIdentifier; running = true; } /** * Shuts down the {@link Registrar}. * * <p> * No further registration requests will be accepted. All queued registration * jobs have up to {@link #SHUTDOWN_TIMEOUT} {@link #SHUTDOWN_TIMEOUT_UNITS} * to complete before being canceled. * * <p> * Calling {@link #shutdown()} more than once has no effect. */ public void shutdown() { if (!running) { return; } running = false; try { retryingExecutorService.shutdown(SHUTDOWN_TIMEOUT, SHUTDOWN_TIMEOUT_UNITS); } catch (InterruptedException 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. */ /** * Provides internal classes for working with the parameter server. * <p> * These classes should _not_ be used directly outside of the org.ros package. */ package org.ros.internal.node.parameter;
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.parameter; import com.google.common.collect.Maps; import org.ros.concurrent.ListenerGroup; import org.ros.concurrent.SignalRunnable; import org.ros.namespace.GraphName; import org.ros.node.parameter.ParameterListener; import java.util.Map; import java.util.concurrent.ExecutorService; /** * @author damonkohler@google.com (Damon Kohler) */ public class ParameterManager { private final ExecutorService executorService; private final Map<GraphName, ListenerGroup<ParameterListener>> listeners; public ParameterManager(ExecutorService executorService) { this.executorService = executorService; listeners = Maps.newHashMap(); } public void addListener(GraphName parameterName, ParameterListener listener) { synchronized (listeners) { if (!listeners.containsKey(parameterName)) { listeners.put(parameterName, new ListenerGroup<ParameterListener>(executorService)); } listeners.get(parameterName).add(listener); } } /** * @param parameterName * @param value * @return the number of listeners called with the new value */ public int updateParameter(GraphName parameterName, final Object value) { int numberOfListeners = 0; synchronized (listeners) { if (listeners.containsKey(parameterName)) { ListenerGroup<ParameterListener> listenerCollection = listeners.get(parameterName); numberOfListeners = listenerCollection.size(); listenerCollection.signal(new SignalRunnable<ParameterListener>() { @Override public void run(ParameterListener listener) { listener.onNewValue(value); } }); } } return numberOfListeners; } }
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.parameter; import com.google.common.base.Preconditions; import org.ros.exception.ParameterClassCastException; import org.ros.exception.ParameterNotFoundException; import org.ros.internal.node.client.ParameterClient; 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.ParameterServer; import org.ros.namespace.GraphName; import org.ros.namespace.NameResolver; import org.ros.node.parameter.ParameterListener; import org.ros.node.parameter.ParameterTree; import java.net.URI; import java.util.Arrays; import java.util.List; import java.util.Map; /** * Provides access to the ROS {@link ParameterServer}. * * @author kwc@willowgarage.com (Ken Conley) * @author damonkohler@google.com (Damon Kohler) */ public class DefaultParameterTree implements ParameterTree { private final ParameterClient parameterClient; private final ParameterManager parameterManager; private final NameResolver resolver; public static DefaultParameterTree newFromNodeIdentifier(NodeIdentifier nodeIdentifier, URI masterUri, NameResolver resolver, ParameterManager parameterManager) { ParameterClient client = new ParameterClient(nodeIdentifier, masterUri); return new DefaultParameterTree(client, parameterManager, resolver); } private DefaultParameterTree(ParameterClient parameterClient, ParameterManager parameterManager, NameResolver resolver) { this.parameterClient = parameterClient; this.parameterManager = parameterManager; this.resolver = resolver; } @Override public boolean has(GraphName name) { GraphName resolvedName = resolver.resolve(name); return parameterClient.hasParam(resolvedName).getResult(); } @Override public boolean has(String name) { return has(GraphName.of(name)); } @Override public void delete(GraphName name) { GraphName resolvedName = resolver.resolve(name); parameterClient.deleteParam(resolvedName); } @Override public void delete(String name) { delete(GraphName.of(name)); } @Override public GraphName search(GraphName name) { GraphName resolvedName = resolver.resolve(name); Response<GraphName> response = parameterClient.searchParam(resolvedName); if (response.getStatusCode() == StatusCode.SUCCESS) { return response.getResult(); } else { return null; } } @Override public GraphName search(String name) { return search(GraphName.of(name)); } @Override public List<GraphName> getNames() { return parameterClient.getParamNames().getResult(); } @Override public void addParameterListener(GraphName name, ParameterListener listener) { parameterManager.addListener(name, listener); parameterClient.subscribeParam(name); } @Override public void addParameterListener(String name, ParameterListener listener) { addParameterListener(GraphName.of(name), listener); } @Override public void set(GraphName name, boolean value) { GraphName resolvedName = resolver.resolve(name); parameterClient.setParam(resolvedName, value); } @Override public void set(String name, boolean value) { set(GraphName.of(name), value); } @Override public void set(GraphName name, int value) { GraphName resolvedName = resolver.resolve(name); parameterClient.setParam(resolvedName, value); } @Override public void set(String name, int value) { set(GraphName.of(name), value); } @Override public void set(GraphName name, double value) { GraphName resolvedName = resolver.resolve(name); parameterClient.setParam(resolvedName, value); } @Override public void set(String name, double value) { set(GraphName.of(name), value); } @Override public void set(GraphName name, String value) { GraphName resolvedName = resolver.resolve(name); parameterClient.setParam(resolvedName, value); } @Override public void set(String name, String value) { set(GraphName.of(name), value); } @Override public void set(GraphName name, List<?> value) { GraphName resolvedName = resolver.resolve(name); parameterClient.setParam(resolvedName, value); } @Override public void set(String name, List<?> value) { set(GraphName.of(name), value); } @Override public void set(GraphName name, Map<?, ?> value) { GraphName resolvedName = resolver.resolve(name); parameterClient.setParam(resolvedName, value); } @Override public void set(String name, Map<?, ?> value) { set(GraphName.of(name), value); } private <T> T get(GraphName name, Class<T> type) { GraphName resolvedName = resolver.resolve(name); Response<Object> response = parameterClient.getParam(resolvedName); try { if (response.getStatusCode() == StatusCode.SUCCESS) { return type.cast(response.getResult()); } } catch (ClassCastException e) { throw new ParameterClassCastException("Cannot cast parameter to: " + type.getName(), e); } throw new ParameterNotFoundException("Parameter does not exist: " + name); } @SuppressWarnings("unchecked") private <T> T get(GraphName name, T defaultValue) { Preconditions.checkNotNull(defaultValue); GraphName resolvedName = resolver.resolve(name); Response<Object> response = parameterClient.getParam(resolvedName); if (response.getStatusCode() == StatusCode.SUCCESS) { try { return (T) defaultValue.getClass().cast(response.getResult()); } catch (ClassCastException e) { throw new ParameterClassCastException("Cannot cast parameter to: " + defaultValue.getClass().getName(), e); } } else { return defaultValue; } } @Override public boolean getBoolean(GraphName name) { return get(name, Boolean.class); } @Override public boolean getBoolean(String name) { return getBoolean(GraphName.of(name)); } @Override public boolean getBoolean(GraphName name, boolean defaultValue) { return get(name, defaultValue); } @Override public boolean getBoolean(String name, boolean defaultValue) { return getBoolean(GraphName.of(name), defaultValue); } @Override public int getInteger(GraphName name) { return get(name, Integer.class); } @Override public int getInteger(String name) { return getInteger(GraphName.of(name)); } @Override public int getInteger(GraphName name, int defaultValue) { return get(name, defaultValue); } @Override public int getInteger(String name, int defaultValue) { return getInteger(GraphName.of(name), defaultValue); } @Override public double getDouble(GraphName name) { return get(name, Double.class); } @Override public double getDouble(String name) { return getDouble(GraphName.of(name)); } @Override public double getDouble(GraphName name, double defaultValue) { return get(name, defaultValue); } @Override public double getDouble(String name, double defaultValue) { return getDouble(GraphName.of(name), defaultValue); } @Override public String getString(GraphName name) { return get(name, String.class); } @Override public String getString(String name) { return get(GraphName.of(name), String.class); } @Override public String getString(GraphName name, String defaultValue) { return get(name, defaultValue); } @Override public String getString(String name, String defaultValue) { return getString(GraphName.of(name), defaultValue); } @Override public List<?> getList(GraphName name) { return Arrays.asList(get(name, Object[].class)); } @Override public List<?> getList(String name) { return getList(GraphName.of(name)); } @Override public List<?> getList(GraphName name, List<?> defaultValue) { return Arrays.asList(get(name, defaultValue.toArray())); } @Override public List<?> getList(String name, List<?> defaultValue) { return getList(GraphName.of(name), defaultValue); } @Override public Map<?, ?> getMap(GraphName name) { return get(name, Map.class); } @Override public Map<?, ?> getMap(String name) { return getMap(GraphName.of(name)); } @Override public Map<?, ?> getMap(GraphName name, Map<?, ?> defaultValue) { return get(name, defaultValue); } @Override public Map<?, ?> getMap(String name, Map<?, ?> defaultValue) { return getMap(GraphName.of(name), defaultValue); } }
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 creating and communicating with nodes in the ROS graph. * <p> * These classes should _not_ be used directly outside of the org.ros package. */ package org.ros.internal.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.service; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import org.ros.namespace.GraphName; import org.ros.node.service.ServiceClient; import org.ros.node.service.ServiceServer; import java.util.List; import java.util.Map; /** * Manages a collection of {@link ServiceServer}s and {@link ServiceClient}s. * * @author damonkohler@google.com (Damon Kohler) */ public class ServiceManager { /** * A mapping from service name to the server for the service. */ private final Map<GraphName, DefaultServiceServer<?, ?>> serviceServers; /** * A mapping from service name to a client for the service. */ private final Map<GraphName, DefaultServiceClient<?, ?>> serviceClients; // TODO(damonkohler): Change to ListenerGroup. private ServiceManagerListener listener; public ServiceManager() { serviceServers = Maps.newConcurrentMap(); serviceClients = Maps.newConcurrentMap(); } public void setListener(ServiceManagerListener listener) { this.listener = listener; } public boolean hasServer(GraphName name) { return serviceServers.containsKey(name); } public void addServer(DefaultServiceServer<?, ?> serviceServer) { serviceServers.put(serviceServer.getName(), serviceServer); if (listener != null) { listener.onServiceServerAdded(serviceServer); } } public void removeServer(DefaultServiceServer<?, ?> serviceServer) { serviceServers.remove(serviceServer.getName()); if (listener != null) { listener.onServiceServerRemoved(serviceServer); } } public DefaultServiceServer<?, ?> getServer(GraphName name) { return serviceServers.get(name); } public boolean hasClient(GraphName name) { return serviceClients.containsKey(name); } public void addClient(DefaultServiceClient<?, ?> serviceClient) { serviceClients.put(serviceClient.getName(), serviceClient); } public void removeClient(DefaultServiceClient<?, ?> serviceClient) { serviceClients.remove(serviceClient.getName()); } public DefaultServiceClient<?, ?> getClient(GraphName name) { return serviceClients.get(name); } public List<DefaultServiceServer<?, ?>> getServers() { return ImmutableList.copyOf(serviceServers.values()); } public List<DefaultServiceClient<?, ?>> getClients() { return ImmutableList.copyOf(serviceClients.values()); } }
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.internal.message.service.ServiceDescription; import org.ros.internal.transport.ConnectionHeader; import org.ros.internal.transport.ConnectionHeaderFields; import org.ros.namespace.GraphName; import java.net.URI; /** * @author damonkohler@google.com (Damon Kohler) */ public class ServiceDeclaration { private final ServiceIdentifier identifier; private final ServiceDescription description; public ServiceDeclaration(ServiceIdentifier identifier, ServiceDescription description) { Preconditions.checkNotNull(identifier); Preconditions.checkNotNull(description); this.identifier = identifier; this.description = description; } public ConnectionHeader toConnectionHeader() { ConnectionHeader connectionHeader = new ConnectionHeader(); connectionHeader.addField(ConnectionHeaderFields.SERVICE, getName().toString()); connectionHeader.addField(ConnectionHeaderFields.TYPE, description.getType()); connectionHeader.addField(ConnectionHeaderFields.MESSAGE_DEFINITION, description.getDefinition()); connectionHeader.addField(ConnectionHeaderFields.MD5_CHECKSUM, description.getMd5Checksum()); return connectionHeader; } public String getType() { return description.getType(); } public String getDefinition() { return description.getDefinition(); } public GraphName getName() { return identifier.getName(); } @Override public String toString() { return "ServiceDeclaration<" + getName().toString() + ", " + description.toString() + ">"; } public String getMd5Checksum() { return description.getMd5Checksum(); } public URI getUri() { return identifier.getUri(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((identifier == null) ? 0 : identifier.hashCode()); result = prime * result + ((description == null) ? 0 : description.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; ServiceDeclaration other = (ServiceDeclaration) obj; if (identifier == null) { if (other.identifier != null) return false; } else if (!identifier.equals(other.identifier)) return false; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) 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.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.replay.ReplayingDecoder; /** * Decodes service responses. * * @author damonkohler@google.com (Damon Kohler) */ class ServiceResponseDecoder<ResponseType> extends ReplayingDecoder<ServiceResponseDecoderState> { private ServiceServerResponse response; public ServiceResponseDecoder() { reset(); } @SuppressWarnings("fallthrough") @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, ServiceResponseDecoderState state) throws Exception { switch (state) { case ERROR_CODE: response.setErrorCode(buffer.readByte()); checkpoint(ServiceResponseDecoderState.MESSAGE_LENGTH); case MESSAGE_LENGTH: response.setMessageLength(buffer.readInt()); checkpoint(ServiceResponseDecoderState.MESSAGE); case MESSAGE: response.setMessage(buffer.readBytes(response.getMessageLength())); try { return response; } finally { reset(); } default: throw new IllegalStateException(); } } private void reset() { checkpoint(ServiceResponseDecoderState.ERROR_CODE); response = new ServiceServerResponse(); } }
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.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.tcp.TcpClientPipelineFactory; import org.ros.message.MessageDeserializer; import org.ros.node.service.ServiceResponseListener; import org.ros.node.service.ServiceServer; import java.util.Queue; import java.util.concurrent.ExecutorService; /** * Performs a handshake with the connected {@link ServiceServer}. * * @author damonkohler@google.com (Damon Kohler) * * @param <T> * the connected {@link ServiceServer} responds to requests of this * type * @param <S> * the connected {@link ServiceServer} returns responses of this type */ class ServiceClientHandshakeHandler<T, S> extends BaseClientHandshakeHandler { private static final Log log = LogFactory.getLog(ServiceClientHandshakeHandler.class); private final Queue<ServiceResponseListener<S>> responseListeners; private final MessageDeserializer<S> deserializer; private final ExecutorService executorService; public ServiceClientHandshakeHandler(ConnectionHeader outgoingConnectionHeader, Queue<ServiceResponseListener<S>> responseListeners, MessageDeserializer<S> deserializer, ExecutorService executorService) { super(new ServiceClientHandshake(outgoingConnectionHeader), executorService); this.responseListeners = responseListeners; this.deserializer = deserializer; this.executorService = executorService; } @Override protected void onSuccess(ConnectionHeader incommingConnectionHeader, ChannelHandlerContext ctx, MessageEvent e) { ChannelPipeline pipeline = e.getChannel().getPipeline(); pipeline.remove(TcpClientPipelineFactory.LENGTH_FIELD_BASED_FRAME_DECODER); pipeline.remove(ServiceClientHandshakeHandler.this); pipeline.addLast("ResponseDecoder", new ServiceResponseDecoder<S>()); pipeline.addLast("ResponseHandler", new ServiceResponseHandler<S>(responseListeners, deserializer, executorService)); } @Override protected void onFailure(String errorMessage, ChannelHandlerContext ctx, MessageEvent e) { log.error("Service client handshake failed: " + errorMessage); e.getChannel().close(); } @Override public String getName() { return "ServiceClientHandshakeHandler"; } }
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 services. * <p> * These classes should _not_ be used directly outside of the org.ros package. */ package org.ros.internal.node.service;
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.internal.message.RawMessage; /** * @author damonkohler@google.com (Damon Kohler) */ public class Service { public interface Request extends RawMessage { } public interface Response extends RawMessage { } private final Request request; private final Response response; public Service(Request request, Response response) { this.request = request; this.response = response; } @SuppressWarnings("unchecked") public <T extends Request> T getRequest() { return (T) request; } @SuppressWarnings("unchecked") public <T extends Response> T getResponse() { return (T) 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.service; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import org.jboss.netty.buffer.ChannelBuffer; import org.ros.exception.RosRuntimeException; import org.ros.internal.message.MessageBufferPool; import org.ros.internal.transport.ClientHandshakeListener; import org.ros.internal.transport.ConnectionHeader; import org.ros.internal.transport.ConnectionHeaderFields; import org.ros.internal.transport.tcp.TcpClient; import org.ros.internal.transport.tcp.TcpClientManager; 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.ServiceResponseListener; import java.net.InetSocketAddress; import java.net.URI; import java.util.Queue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Default implementation of a {@link ServiceClient}. * * @author damonkohler@google.com (Damon Kohler) */ public class DefaultServiceClient<T, S> implements ServiceClient<T, S> { private final class HandshakeLatch implements ClientHandshakeListener { private CountDownLatch latch; private boolean success; private String errorMessage; @Override public void onSuccess(ConnectionHeader outgoingConnectionHeader, ConnectionHeader incomingConnectionHeader) { success = true; latch.countDown(); } @Override public void onFailure(ConnectionHeader outgoingConnectionHeader, String errorMessage) { this.errorMessage = errorMessage; success = false; latch.countDown(); } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { latch.await(timeout, unit); return success; } public String getErrorMessage() { return errorMessage; } public void reset() { latch = new CountDownLatch(1); success = false; errorMessage = null; } } private final ServiceDeclaration serviceDeclaration; private final MessageSerializer<T> serializer; private final MessageFactory messageFactory; private final MessageBufferPool messageBufferPool; private final Queue<ServiceResponseListener<S>> responseListeners; private final ConnectionHeader connectionHeader; private final TcpClientManager tcpClientManager; private final HandshakeLatch handshakeLatch; private TcpClient tcpClient; public static <S, T> DefaultServiceClient<S, T> newDefault(GraphName nodeName, ServiceDeclaration serviceDeclaration, MessageSerializer<S> serializer, MessageDeserializer<T> deserializer, MessageFactory messageFactory, ScheduledExecutorService executorService) { return new DefaultServiceClient<S, T>(nodeName, serviceDeclaration, serializer, deserializer, messageFactory, executorService); } private DefaultServiceClient(GraphName nodeName, ServiceDeclaration serviceDeclaration, MessageSerializer<T> serializer, MessageDeserializer<S> deserializer, MessageFactory messageFactory, ScheduledExecutorService executorService) { this.serviceDeclaration = serviceDeclaration; this.serializer = serializer; this.messageFactory = messageFactory; messageBufferPool = new MessageBufferPool(); responseListeners = Lists.newLinkedList(); connectionHeader = new ConnectionHeader(); connectionHeader.addField(ConnectionHeaderFields.CALLER_ID, nodeName.toString()); // TODO(damonkohler): Support non-persistent connections. connectionHeader.addField(ConnectionHeaderFields.PERSISTENT, "1"); connectionHeader.merge(serviceDeclaration.toConnectionHeader()); tcpClientManager = new TcpClientManager(executorService); ServiceClientHandshakeHandler<T, S> serviceClientHandshakeHandler = new ServiceClientHandshakeHandler<T, S>(connectionHeader, responseListeners, deserializer, executorService); handshakeLatch = new HandshakeLatch(); serviceClientHandshakeHandler.addListener(handshakeLatch); tcpClientManager.addNamedChannelHandler(serviceClientHandshakeHandler); } @Override public void connect(URI uri) { Preconditions.checkNotNull(uri, "URI must be specified."); Preconditions.checkArgument(uri.getScheme().equals("rosrpc"), "Invalid service URI."); Preconditions.checkState(tcpClient == null, "Already connected once."); InetSocketAddress address = new InetSocketAddress(uri.getHost(), uri.getPort()); handshakeLatch.reset(); tcpClient = tcpClientManager.connect(toString(), address); try { if (!handshakeLatch.await(1, TimeUnit.SECONDS)) { throw new RosRuntimeException(handshakeLatch.getErrorMessage()); } } catch (InterruptedException e) { throw new RosRuntimeException("Handshake timed out."); } } @Override public void shutdown() { Preconditions.checkNotNull(tcpClient, "Not connected."); tcpClientManager.shutdown(); } @Override public void call(T request, ServiceResponseListener<S> listener) { ChannelBuffer buffer = messageBufferPool.acquire(); serializer.serialize(request, buffer); responseListeners.add(listener); tcpClient.write(buffer).awaitUninterruptibly(); messageBufferPool.release(buffer); } @Override public GraphName getName() { return serviceDeclaration.getName(); } @Override public String toString() { return "ServiceClient<" + serviceDeclaration + ">"; } @Override public T newMessage() { return messageFactory.newFromType(serviceDeclaration.getType()); } }
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.namespace.GraphName; import java.net.URI; /** * @author damonkohler@google.com (Damon Kohler) */ public class ServiceIdentifier { private final GraphName name; private final URI uri; public ServiceIdentifier(GraphName name, URI uri) { Preconditions.checkNotNull(name); Preconditions.checkArgument(name.isGlobal()); this.name = name; this.uri = uri; } public GraphName getName() { return name; } public URI getUri() { return uri; } @Override public String toString() { return "ServiceIdentifier<" + 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; ServiceIdentifier other = (ServiceIdentifier) 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.service; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.ros.exception.ServiceException; import org.ros.internal.message.MessageBufferPool; import org.ros.message.MessageDeserializer; import org.ros.message.MessageFactory; import org.ros.message.MessageSerializer; import org.ros.node.service.ServiceResponseBuilder; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.concurrent.ExecutorService; /** * @author damonkohler@google.com (Damon Kohler) */ class ServiceRequestHandler<T, S> extends SimpleChannelHandler { private final ServiceDeclaration serviceDeclaration; private final ServiceResponseBuilder<T, S> responseBuilder; private final MessageDeserializer<T> deserializer; private final MessageSerializer<S> serializer; private final MessageFactory messageFactory; private final ExecutorService executorService; private final MessageBufferPool messageBufferPool; public ServiceRequestHandler(ServiceDeclaration serviceDeclaration, ServiceResponseBuilder<T, S> responseBuilder, MessageDeserializer<T> deserializer, MessageSerializer<S> serializer, MessageFactory messageFactory, ExecutorService executorService) { this.serviceDeclaration = serviceDeclaration; this.deserializer = deserializer; this.serializer = serializer; this.responseBuilder = responseBuilder; this.messageFactory = messageFactory; this.executorService = executorService; messageBufferPool = new MessageBufferPool(); } private void handleRequest(ChannelBuffer requestBuffer, ChannelBuffer responseBuffer) throws ServiceException { T request = deserializer.deserialize(requestBuffer); S response = messageFactory.newFromType(serviceDeclaration.getType()); responseBuilder.build(request, response); serializer.serialize(response, responseBuffer); } private void handleSuccess(final ChannelHandlerContext ctx, ServiceServerResponse response, ChannelBuffer responseBuffer) { response.setErrorCode(1); response.setMessageLength(responseBuffer.readableBytes()); response.setMessage(responseBuffer); ctx.getChannel().write(response); } private void handleError(final ChannelHandlerContext ctx, ServiceServerResponse response, String message) { response.setErrorCode(0); ByteBuffer encodedMessage = Charset.forName("US-ASCII").encode(message); response.setMessageLength(encodedMessage.limit()); response.setMessage(ChannelBuffers.wrappedBuffer(encodedMessage)); ctx.getChannel().write(response); } @Override public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) throws Exception { // Although the ChannelHandlerContext is explicitly documented as being safe // to keep for later use, the MessageEvent is not. So, we make a defensive // copy of the ChannelBuffer. final ChannelBuffer requestBuffer = ((ChannelBuffer) e.getMessage()).copy(); executorService.execute(new Runnable() { @Override public void run() { ServiceServerResponse response = new ServiceServerResponse(); ChannelBuffer responseBuffer = messageBufferPool.acquire(); boolean success; try { handleRequest(requestBuffer, responseBuffer); success = true; } catch (ServiceException ex) { handleError(ctx, response, ex.getMessage()); success = false; } if (success) { handleSuccess(ctx, response, responseBuffer); } messageBufferPool.release(responseBuffer); } }); super.messageReceived(ctx, e); } }
Java