code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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.message;
import org.jboss.netty.buffer.ChannelBuffer;
import org.ros.internal.message.field.Field;
import org.ros.message.MessageDeserializer;
import org.ros.message.MessageFactory;
import org.ros.message.MessageIdentifier;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class DefaultMessageDeserializer<T> implements MessageDeserializer<T> {
private final MessageIdentifier messageIdentifier;
private final MessageFactory messageFactory;
public DefaultMessageDeserializer(MessageIdentifier messageIdentifier,
MessageFactory messageFactory) {
this.messageIdentifier = messageIdentifier;
this.messageFactory = messageFactory;
}
@SuppressWarnings("unchecked")
@Override
public T deserialize(ChannelBuffer buffer) {
Message message = messageFactory.newFromType(messageIdentifier.getType());
for (Field field : message.toRawMessage().getFields()) {
if (!field.isConstant()) {
field.deserialize(buffer);
}
}
return (T) message;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.message.service;
import org.ros.internal.message.definition.MessageDefinitionFileProvider;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.ros.internal.message.StringFileProvider;
import java.io.File;
import java.io.FileFilter;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceDefinitionFileProvider extends MessageDefinitionFileProvider {
private static final String PARENT = "srv";
private static final String SUFFIX = "srv";
private static StringFileProvider newStringFileProvider() {
IOFileFilter extensionFilter = FileFilterUtils.suffixFileFilter(SUFFIX);
IOFileFilter parentBaseNameFilter = FileFilterUtils.asFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
return getParentBaseName(file.getAbsolutePath()).equals(PARENT);
}
});
IOFileFilter fileFilter = FileFilterUtils.andFileFilter(extensionFilter, parentBaseNameFilter);
return new StringFileProvider(fileFilter);
}
public ServiceDefinitionFileProvider() {
super(newStringFileProvider());
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides internal classes for representing service messages.
* <p>
* These classes should _not_ be used directly outside of the org.ros package.
*/
package org.ros.internal.message.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.message.service;
import org.ros.internal.message.DefaultMessageFactory;
import org.ros.internal.message.DefaultMessageInterfaceClassProvider;
import org.ros.internal.message.MessageProxyFactory;
import org.ros.message.MessageDeclaration;
import org.ros.message.MessageDefinitionProvider;
import org.ros.message.MessageFactory;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceResponseMessageFactory implements MessageFactory {
private final ServiceDescriptionFactory serviceDescriptionFactory;
private final MessageFactory messageFactory;
private final MessageProxyFactory messageProxyFactory;
public ServiceResponseMessageFactory(MessageDefinitionProvider messageDefinitionProvider) {
serviceDescriptionFactory = new ServiceDescriptionFactory(messageDefinitionProvider);
messageFactory = new DefaultMessageFactory(messageDefinitionProvider);
messageProxyFactory =
new MessageProxyFactory(new DefaultMessageInterfaceClassProvider(), messageFactory);
}
@Override
public <T> T newFromType(String serviceType) {
ServiceDescription serviceDescription = serviceDescriptionFactory.newFromType(serviceType);
MessageDeclaration messageDeclaration =
MessageDeclaration.of(serviceDescription.getResponseType(),
serviceDescription.getResponseDefinition());
return messageProxyFactory.newMessageProxy(messageDeclaration);
}
}
| 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.message.service;
import org.ros.internal.message.definition.MessageDefinitionTupleParser;
import org.ros.message.MessageDeclaration;
import org.ros.message.MessageIdentifier;
import java.util.List;
/**
* The description of a ROS service.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceDescription extends MessageDeclaration {
private final String requestType;
private final String requestDefinition;
private final String responseType;
private final String responseDefinition;
private final String md5Checksum;
public ServiceDescription(String type, String definition, String md5Checksum) {
super(MessageIdentifier.of(type), definition);
this.md5Checksum = md5Checksum;
List<String> requestAndResponse = MessageDefinitionTupleParser.parse(definition, 2);
requestType = type + "Request";
responseType = type + "Response";
requestDefinition = requestAndResponse.get(0);
responseDefinition = requestAndResponse.get(1);
}
public String getMd5Checksum() {
return md5Checksum;
}
public String getRequestType() {
return requestType;
}
public String getRequestDefinition() {
return requestDefinition;
}
public String getResponseType() {
return responseType;
}
public String getResponseDefinition() {
return responseDefinition;
}
@Override
public String toString() {
return "ServiceDescription<" + getType() + ", " + md5Checksum + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((md5Checksum == null) ? 0 : md5Checksum.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ServiceDescription other = (ServiceDescription) obj;
if (md5Checksum == null) {
if (other.md5Checksum != null)
return false;
} else if (!md5Checksum.equals(other.md5Checksum))
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.message.service;
import org.ros.internal.message.Md5Generator;
import org.ros.message.MessageDefinitionProvider;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceDescriptionFactory {
private final MessageDefinitionProvider messageDefinitionProvider;
private final Md5Generator md5Generator;
public ServiceDescriptionFactory(MessageDefinitionProvider messageDefinitionProvider) {
this.messageDefinitionProvider = messageDefinitionProvider;
md5Generator = new Md5Generator(messageDefinitionProvider);
}
public ServiceDescription newFromType(String serviceType) {
String serviceDefinition = messageDefinitionProvider.get(serviceType);
String md5Checksum = md5Generator.generate(serviceType);
return new ServiceDescription(serviceType, serviceDefinition, md5Checksum);
}
public boolean hasType(String serviceType) {
return messageDefinitionProvider.has(serviceType);
}
}
| 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.message.service;
import org.ros.internal.message.MessageInterfaceClassProvider;
import org.ros.internal.message.RawMessage;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceResponseMessageInterfaceClassProvider implements MessageInterfaceClassProvider {
@SuppressWarnings("unchecked")
@Override
public <T> Class<T> get(String messageType) {
try {
String className = messageType.replace("/", ".") + "$Response";
return (Class<T>) getClass().getClassLoader().loadClass(className);
} catch (ClassNotFoundException e) {
return (Class<T>) RawMessage.class;
}
}
}
| 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.message.service;
import com.google.common.base.Preconditions;
import org.ros.internal.message.StringResourceProvider;
import org.ros.message.MessageDefinitionProvider;
import org.ros.message.MessageIdentifier;
import java.util.Collection;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceDefinitionResourceProvider implements MessageDefinitionProvider {
private final StringResourceProvider stringResourceProvider;
public ServiceDefinitionResourceProvider() {
stringResourceProvider = new StringResourceProvider();
}
private String serviceTypeToResourceName(String serviceType) {
Preconditions.checkArgument(serviceType.contains("/"), "Service type must be fully qualified: "
+ serviceType);
String[] packageAndType = serviceType.split("/", 2);
return String.format("/%s/srv/%s.srv", packageAndType[0], packageAndType[1]);
}
@Override
public String get(String serviceType) {
return stringResourceProvider.get(serviceTypeToResourceName(serviceType));
}
@Override
public boolean has(String serviceType) {
return stringResourceProvider.has(serviceTypeToResourceName(serviceType));
}
public void add(String serviceType, String serviceDefinition) {
stringResourceProvider.addStringToCache(serviceTypeToResourceName(serviceType),
serviceDefinition);
}
@Override
public Collection<String> getPackages() {
throw new UnsupportedOperationException();
}
@Override
public Collection<MessageIdentifier> getMessageIdentifiersByPackage(String pkg) {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.message.service;
import org.ros.internal.message.DefaultMessageFactory;
import org.ros.internal.message.DefaultMessageInterfaceClassProvider;
import org.ros.internal.message.MessageProxyFactory;
import org.ros.message.MessageDeclaration;
import org.ros.message.MessageDefinitionProvider;
import org.ros.message.MessageFactory;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceRequestMessageFactory implements MessageFactory {
private final ServiceDescriptionFactory serviceDescriptionFactory;
private final MessageFactory messageFactory;
private final MessageProxyFactory messageProxyFactory;
public ServiceRequestMessageFactory(MessageDefinitionProvider messageDefinitionProvider) {
serviceDescriptionFactory = new ServiceDescriptionFactory(messageDefinitionProvider);
messageFactory = new DefaultMessageFactory(messageDefinitionProvider);
messageProxyFactory =
new MessageProxyFactory(new DefaultMessageInterfaceClassProvider(), messageFactory);
}
@Override
public <T> T newFromType(String serviceType) {
ServiceDescription serviceDescription = serviceDescriptionFactory.newFromType(serviceType);
MessageDeclaration messageDeclaration =
MessageDeclaration.of(serviceDescription.getRequestType(),
serviceDescription.getRequestDefinition());
return messageProxyFactory.newMessageProxy(messageDeclaration);
}
}
| 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.message.service;
import org.ros.internal.message.MessageInterfaceClassProvider;
import org.ros.internal.message.RawMessage;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class ServiceRequestMessageInterfaceClassProvider implements MessageInterfaceClassProvider {
@SuppressWarnings("unchecked")
@Override
public <T> Class<T> get(String messageType) {
try {
String className = messageType.replace("/", ".") + "$Request";
return (Class<T>) getClass().getClassLoader().loadClass(className);
} catch (ClassNotFoundException e) {
return (Class<T>) RawMessage.class;
}
}
}
| 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.message;
import org.jboss.netty.buffer.ChannelBuffer;
import org.ros.internal.message.field.Field;
import org.ros.message.MessageSerializer;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class DefaultMessageSerializer implements MessageSerializer<Message> {
@Override
public void serialize(Message message, ChannelBuffer buffer) {
for (Field field : message.toRawMessage().getFields()) {
if (!field.isConstant()) {
field.serialize(buffer);
}
}
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.message;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public interface Message {
/**
* @return returns this {@link Message} as a {@link RawMessage}
*/
RawMessage toRawMessage();
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides internal classes for representing topic messages.
* <p>
* These classes should _not_ be used directly outside of the org.ros package.
*/
package org.ros.internal.message.topic; | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.message.topic;
import org.ros.internal.message.definition.MessageDefinitionFileProvider;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.ros.internal.message.StringFileProvider;
import java.io.File;
import java.io.FileFilter;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class TopicDefinitionFileProvider extends MessageDefinitionFileProvider {
private static final String PARENT = "msg";
private static final String SUFFIX = "msg";
private static StringFileProvider newStringFileProvider() {
IOFileFilter extensionFilter = FileFilterUtils.suffixFileFilter(SUFFIX);
IOFileFilter parentBaseNameFilter = FileFilterUtils.asFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
return getParentBaseName(file.getAbsolutePath()).equals(PARENT);
}
});
IOFileFilter fileFilter = FileFilterUtils.andFileFilter(extensionFilter, parentBaseNameFilter);
return new StringFileProvider(fileFilter);
}
public TopicDefinitionFileProvider() {
super(newStringFileProvider());
}
}
| 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.message.topic;
import org.ros.message.MessageDeclaration;
import org.ros.message.MessageIdentifier;
/**
* The description of a ROS topic.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class TopicDescription extends MessageDeclaration {
private final String md5Checksum;
public TopicDescription(String type, String definition, String md5Checksum) {
super(MessageIdentifier.of(type), definition);
this.md5Checksum = md5Checksum;
}
public String getMd5Checksum() {
return md5Checksum;
}
@Override
public String toString() {
return "TopicDescription<" + getType() + ", " + md5Checksum + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((md5Checksum == null) ? 0 : md5Checksum.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
TopicDescription other = (TopicDescription) obj;
if (md5Checksum == null) {
if (other.md5Checksum != null)
return false;
} else if (!md5Checksum.equals(other.md5Checksum))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.message.topic;
import org.ros.internal.message.DefaultMessageFactory;
import org.ros.message.MessageDefinitionProvider;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class TopicMessageFactory extends DefaultMessageFactory {
public TopicMessageFactory(MessageDefinitionProvider messageDefinitionProvider) {
super(messageDefinitionProvider);
}
}
| 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.message.topic;
import org.ros.internal.message.Md5Generator;
import org.ros.message.MessageDefinitionProvider;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class TopicDescriptionFactory {
private final MessageDefinitionProvider messageDefinitionProvider;
private final Md5Generator md5Generator;
public TopicDescriptionFactory(MessageDefinitionProvider messageDefinitionProvider) {
this.messageDefinitionProvider = messageDefinitionProvider;
md5Generator = new Md5Generator(messageDefinitionProvider);
}
public TopicDescription newFromType(String topicType) {
String md5Checksum = md5Generator.generate(topicType);
String topicDefinition = messageDefinitionProvider.get(topicType);
return new TopicDescription(topicType, topicDefinition, md5Checksum);
}
public boolean hasType(String topicType) {
return messageDefinitionProvider.has(topicType);
}
}
| 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.message.topic;
import com.google.common.annotations.VisibleForTesting;
import org.ros.internal.message.StringResourceProvider;
import org.ros.message.MessageDefinitionProvider;
import org.ros.message.MessageIdentifier;
import java.util.Collection;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class TopicDefinitionResourceProvider implements MessageDefinitionProvider {
private final StringResourceProvider stringResourceProvider;
public TopicDefinitionResourceProvider() {
stringResourceProvider = new StringResourceProvider();
}
private String topicTypeToResourceName(String topicType) {
MessageIdentifier messageIdentifier = MessageIdentifier.of(topicType);
return String.format("/%s/msg/%s.msg", messageIdentifier.getPackage(),
messageIdentifier.getName());
}
@Override
public String get(String topicType) {
return stringResourceProvider.get(topicTypeToResourceName(topicType));
}
@Override
public boolean has(String topicType) {
return stringResourceProvider.has(topicTypeToResourceName(topicType));
}
@VisibleForTesting
public void add(String topicType, String topicDefinition) {
stringResourceProvider.addStringToCache(topicTypeToResourceName(topicType), topicDefinition);
}
@Override
public Collection<String> getPackages() {
throw new UnsupportedOperationException();
}
@Override
public Collection<MessageIdentifier> getMessageIdentifiersByPackage(String pkg) {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.message.context;
import com.google.common.base.Preconditions;
import org.ros.internal.message.definition.MessageDefinitionParser.MessageDefinitionVisitor;
import org.ros.internal.message.field.Field;
import org.ros.internal.message.field.FieldFactory;
import org.ros.internal.message.field.FieldType;
import org.ros.internal.message.field.MessageFieldType;
import org.ros.internal.message.field.PrimitiveFieldType;
import org.ros.message.MessageIdentifier;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
class MessageContextBuilder implements MessageDefinitionVisitor {
private final MessageContext messageContext;
public MessageContextBuilder(MessageContext context) {
this.messageContext = context;
}
private FieldType getFieldType(String type) {
Preconditions.checkArgument(!type.equals(messageContext.getType()),
"Message definitions may not be self-referential.");
FieldType fieldType;
if (PrimitiveFieldType.existsFor(type)) {
fieldType = PrimitiveFieldType.valueOf(type.toUpperCase());
} else {
fieldType =
new MessageFieldType(MessageIdentifier.of(type), messageContext.getMessageFactory());
}
return fieldType;
}
@Override
public void variableValue(String type, final String name) {
final FieldType fieldType = getFieldType(type);
messageContext.addFieldFactory(name, new FieldFactory() {
@Override
public Field create() {
return fieldType.newVariableValue(name);
}
});
}
@Override
public void variableList(String type, final int size, final String name) {
final FieldType fieldType = getFieldType(type);
messageContext.addFieldFactory(name, new FieldFactory() {
@Override
public Field create() {
return fieldType.newVariableList(name, size);
}
});
}
@Override
public void constantValue(String type, final String name, final String value) {
final FieldType fieldType = getFieldType(type);
messageContext.addFieldFactory(name, new FieldFactory() {
@Override
public Field create() {
return fieldType.newConstantValue(name, fieldType.parseFromString(value));
}
});
}
} | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.internal.message.context;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import org.ros.internal.message.definition.MessageDefinitionParser;
import org.ros.internal.message.definition.MessageDefinitionParser.MessageDefinitionVisitor;
import org.ros.message.MessageDeclaration;
import org.ros.message.MessageFactory;
import java.util.Map;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class MessageContextProvider {
private final Map<MessageDeclaration, MessageContext> cache;
private final MessageFactory messageFactory;
public MessageContextProvider(MessageFactory messageFactory) {
Preconditions.checkNotNull(messageFactory);
this.messageFactory = messageFactory;
cache = Maps.newConcurrentMap();
}
public MessageContext get(MessageDeclaration messageDeclaration) {
MessageContext messageContext = cache.get(messageDeclaration);
if (messageContext == null) {
messageContext = new MessageContext(messageDeclaration, messageFactory);
MessageDefinitionVisitor visitor = new MessageContextBuilder(messageContext);
MessageDefinitionParser messageDefinitionParser = new MessageDefinitionParser(visitor);
messageDefinitionParser.parse(messageDeclaration.getType(),
messageDeclaration.getDefinition());
cache.put(messageDeclaration, messageContext);
}
return messageContext;
}
}
| 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.message.context;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.ros.internal.message.field.FieldFactory;
import org.ros.message.MessageDeclaration;
import org.ros.message.MessageFactory;
import org.ros.message.MessageIdentifier;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Encapsulates the immutable metadata that describes a message type.
* <p>
* Note that this class is not thread safe.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class MessageContext {
private final MessageDeclaration messageDeclaration;
private final MessageFactory messageFactory;
private final Map<String, FieldFactory> fieldFactories;
private final Map<String, String> fieldGetterNames;
private final Map<String, String> fieldSetterNames;
private final List<String> fieldNames;
public MessageContext(MessageDeclaration messageDeclaration, MessageFactory messageFactory) {
this.messageDeclaration = messageDeclaration;
this.messageFactory = messageFactory;
this.fieldFactories = Maps.newHashMap();
this.fieldGetterNames = Maps.newHashMap();
this.fieldSetterNames = Maps.newHashMap();
this.fieldNames = Lists.newArrayList();
}
public MessageFactory getMessageFactory() {
return messageFactory;
}
public MessageIdentifier getMessageIdentifer() {
return messageDeclaration.getMessageIdentifier();
}
public String getType() {
return messageDeclaration.getType();
}
public String getPackage() {
return messageDeclaration.getPackage();
}
public String getName() {
return messageDeclaration.getName();
}
public String getDefinition() {
return messageDeclaration.getDefinition();
}
public void addFieldFactory(String name, FieldFactory fieldFactory) {
fieldFactories.put(name, fieldFactory);
fieldGetterNames.put(name, "get" + getJavaName(name));
fieldSetterNames.put(name, "set" + getJavaName(name));
fieldNames.add(name);
}
private String getJavaName(String name) {
String[] parts = name.split("_");
StringBuilder fieldName = new StringBuilder();
for (String part : parts) {
fieldName.append(part.substring(0, 1).toUpperCase() + part.substring(1));
}
return fieldName.toString();
}
public boolean hasField(String name) {
// O(1) instead of an O(n) check against the list of field names.
return fieldFactories.containsKey(name);
}
public String getFieldGetterName(String name) {
return fieldGetterNames.get(name);
}
public String getFieldSetterName(String name) {
return fieldSetterNames.get(name);
}
public FieldFactory getFieldFactory(String name) {
return fieldFactories.get(name);
}
/**
* @return a {@link List} of field names in the order they were added
*/
public List<String> getFieldNames() {
return Collections.unmodifiableList(fieldNames);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((messageDeclaration == null) ? 0 : messageDeclaration.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;
MessageContext other = (MessageContext) obj;
if (messageDeclaration == null) {
if (other.messageDeclaration != null)
return false;
} else if (!messageDeclaration.equals(other.messageDeclaration))
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.message;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
interface GetInstance {
public Object getInstance();
}
| 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.message;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.ros.exception.RosRuntimeException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.NoSuchElementException;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class StringResourceProvider {
private final Map<String, String> cache;
public StringResourceProvider() {
cache = Maps.newConcurrentMap();
}
public String get(String resourceName) {
if (!has(resourceName)) {
throw new NoSuchElementException("Resource does not exist: " + resourceName);
}
if (!cache.containsKey(resourceName)) {
InputStream in = getClass().getResourceAsStream(resourceName);
StringBuilder out = new StringBuilder();
Charset charset = Charset.forName("US-ASCII");
byte[] buffer = new byte[8192];
try {
for (int bytesRead; (bytesRead = in.read(buffer)) != -1;) {
out.append(new String(buffer, 0, bytesRead, charset));
}
} catch (IOException e) {
throw new RosRuntimeException("Failed to read resource: " + resourceName, e);
}
cache.put(resourceName, out.toString());
}
return cache.get(resourceName);
}
public boolean has(String resourceName) {
return cache.containsKey(resourceName) || getClass().getResource(resourceName) != null;
}
public Map<String, String> getCachedStrings() {
return ImmutableMap.copyOf(cache);
}
public void addStringToCache(String resourceName, String resourceContent) {
cache.put(resourceName, resourceContent);
}
}
| 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.message;
import com.google.common.annotations.VisibleForTesting;
import org.ros.message.MessageDeclaration;
import org.ros.message.MessageDefinitionProvider;
import org.ros.message.MessageFactory;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class DefaultMessageFactory implements MessageFactory {
private final MessageDefinitionProvider messageDefinitionProvider;
private final DefaultMessageInterfaceClassProvider messageInterfaceClassProvider;
private final MessageProxyFactory messageProxyFactory;
public DefaultMessageFactory(MessageDefinitionProvider messageDefinitionProvider) {
this.messageDefinitionProvider = messageDefinitionProvider;
messageInterfaceClassProvider = new DefaultMessageInterfaceClassProvider();
messageProxyFactory = new MessageProxyFactory(getMessageInterfaceClassProvider(), this);
}
@Override
public <T> T newFromType(String messageType) {
String messageDefinition = messageDefinitionProvider.get(messageType);
MessageDeclaration messageDeclaration = MessageDeclaration.of(messageType, messageDefinition);
return messageProxyFactory.newMessageProxy(messageDeclaration);
}
@VisibleForTesting
DefaultMessageInterfaceClassProvider getMessageInterfaceClassProvider() {
return messageInterfaceClassProvider;
}
}
| 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.message.definition;
import com.google.common.base.Preconditions;
import org.ros.exception.RosRuntimeException;
import org.ros.internal.message.field.PrimitiveFieldType;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
/**
* Parses message definitions and invokes a {@link MessageDefinitionVisitor} for
* each field.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class MessageDefinitionParser {
private final MessageDefinitionVisitor visitor;
public interface MessageDefinitionVisitor {
/**
* Called for each constant in the message definition.
*
* @param type
* the type of the constant
* @param name
* the name of the constant
* @param value
* the value of the constant
*/
void constantValue(String type, String name, String value);
/**
* Called for each scalar in the message definition.
*
* @param type
* the type of the scalar
* @param name
* the name of the scalar
*/
void variableValue(String type, String name);
/**
* Called for each array in the message definition.
*
* @param type
* the type of the array
* @param size
* the size of the array or -1 if the size is unbounded
* @param name
* the name of the array
*/
void variableList(String type, int size, String name);
}
/**
* @param visitor
* the {@link MessageDefinitionVisitor} that will be called for each
* field
*/
public MessageDefinitionParser(MessageDefinitionVisitor visitor) {
this.visitor = visitor;
}
/**
* Parses the message definition
*
* @param messageType
* the type of message defined (e.g. std_msgs/String)
* @param messageDefinition
* the message definition (e.g. "string data")
*/
public void parse(String messageType, String messageDefinition) {
Preconditions.checkNotNull(messageType);
Preconditions.checkNotNull(messageDefinition);
BufferedReader reader = new BufferedReader(new StringReader(messageDefinition));
String line;
try {
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
line = line.trim();
if (line.startsWith("#")) {
continue;
}
if (line.length() > 0) {
parseField(messageType, line);
}
}
} catch (IOException e) {
throw new RosRuntimeException(e);
}
}
private void parseField(String messageType, String fieldDefinition) {
// TODO(damonkohler): Regex input validation.
String[] typeAndName = fieldDefinition.split("\\s+", 2);
Preconditions.checkState(typeAndName.length == 2,
String.format("Invalid field definition: \"%s\"", fieldDefinition));
String type = typeAndName[0];
String name = typeAndName[1];
String value = null;
if (name.contains("=") && (!name.contains("#") || name.indexOf('#') > name.indexOf('='))) {
String[] nameAndValue = name.split("=", 2);
name = nameAndValue[0].trim();
value = nameAndValue[1].trim();
} else if (name.contains("#")) {
// Stripping comments from constants is deferred until we also know the
// type since strings are handled differently.
Preconditions.checkState(!name.startsWith("#"), String.format(
"Fields must define a name. Field definition in %s was: \"%s\"", messageType,
fieldDefinition));
name = name.substring(0, name.indexOf('#'));
name = name.trim();
}
boolean array = false;
int size = -1;
if (type.endsWith("]")) {
int leftBracketIndex = type.lastIndexOf('[');
int rightBracketIndex = type.lastIndexOf(']');
array = true;
if (rightBracketIndex - leftBracketIndex > 1) {
size = Integer.parseInt(type.substring(leftBracketIndex + 1, rightBracketIndex));
}
type = type.substring(0, leftBracketIndex);
}
if (type.equals("Header")) {
// The header field is treated as though it were a built-in and silently
// expanded to "std_msgs/Header."
Preconditions.checkState(name.equals("header"), "Header field must be named \"header.\"");
type = "std_msgs/Header";
} else if (!PrimitiveFieldType.existsFor(type) && !type.contains("/")) {
// Handle package relative message names.
type = messageType.substring(0, messageType.lastIndexOf('/') + 1) + type;
}
if (value != null) {
if (array) {
// TODO(damonkohler): Handle array constants?
throw new UnsupportedOperationException("Array constants are not supported.");
}
// Comments inline with string constants are treated as data.
if (!type.equals(PrimitiveFieldType.STRING.getName()) && value.contains("#")) {
Preconditions.checkState(!value.startsWith("#"), "Constants must define a value.");
value = value.substring(0, value.indexOf('#'));
value = value.trim();
}
visitor.constantValue(type, name, value);
} else {
if (array) {
visitor.variableList(type, size, name);
} else {
visitor.variableValue(type, name);
}
}
}
}
| 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.message.definition;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Maps;
import org.ros.exception.RosRuntimeException;
import org.ros.message.MessageDefinitionProvider;
import org.ros.message.MessageIdentifier;
import java.util.Collection;
import java.util.Map;
/**
* A {@link MessageDefinitionProvider} that uses reflection to load the message
* definition {@link String} from a generated interface {@link Class}.
* <p>
* Note that this {@link MessageDefinitionProvider} does not support enumerating
* messages by package.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class MessageDefinitionReflectionProvider implements MessageDefinitionProvider {
private static final String DEFINITION_FIELD = "_DEFINITION";
private final Map<String, String> cache;
public MessageDefinitionReflectionProvider() {
cache = Maps.newConcurrentMap();
}
@Override
public String get(String messageType) {
String messageDefinition = cache.get(messageType);
if (messageDefinition == null) {
String className = messageType.replace("/", ".");
try {
Class<?> loadedClass = getClass().getClassLoader().loadClass(className);
messageDefinition = (String) loadedClass.getDeclaredField(DEFINITION_FIELD).get(null);
cache.put(messageType, messageDefinition);
} catch (Exception e) {
throw new RosRuntimeException(e);
}
}
return messageDefinition;
}
@Override
public boolean has(String messageType) {
try {
get(messageType);
} catch (Exception e) {
return false;
}
return true;
}
@Override
public Collection<String> getPackages() {
throw new UnsupportedOperationException();
}
@Override
public Collection<MessageIdentifier> getMessageIdentifiersByPackage(String pkg) {
throw new UnsupportedOperationException();
}
@VisibleForTesting
public void add(String messageType, String messageDefinition) {
cache.put(messageType, messageDefinition);
}
}
| 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.message.definition;
import com.google.common.collect.Maps;
import org.ros.internal.message.StringFileProvider;
import org.apache.commons.io.FilenameUtils;
import org.ros.message.MessageDefinitionProvider;
import org.ros.message.MessageIdentifier;
import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class MessageDefinitionFileProvider implements MessageDefinitionProvider {
private final StringFileProvider stringFileProvider;
private final Map<String, Collection<MessageIdentifier>> messageIdentifiers;
private final Map<String, String> definitions;
public MessageDefinitionFileProvider(StringFileProvider stringFileProvider) {
this.stringFileProvider = stringFileProvider;
messageIdentifiers = Maps.newConcurrentMap();
definitions = Maps.newConcurrentMap();
}
private static String getParent(String filename) {
return FilenameUtils.getFullPathNoEndSeparator(filename);
}
protected static String getParentBaseName(String filename) {
return FilenameUtils.getBaseName(getParent(filename));
}
private static MessageIdentifier fileToMessageIdentifier(File file) {
String filename = file.getAbsolutePath();
String name = FilenameUtils.getBaseName(filename);
String pkg = getParentBaseName(getParent(filename));
return MessageIdentifier.of(pkg, name);
}
private void addDefinition(File file, String definition) {
MessageIdentifier topicType = fileToMessageIdentifier(file);
if (definitions.containsKey(topicType.getType())) {
// First definition wins.
return;
}
definitions.put(topicType.getType(), definition);
if (!messageIdentifiers.containsKey(topicType.getPackage())) {
messageIdentifiers.put(topicType.getPackage(), new HashSet<MessageIdentifier>());
}
messageIdentifiers.get(topicType.getPackage()).add(topicType);
}
/**
* Updates the topic definition cache.
*
* @see StringFileProvider#update()
*/
public void update() {
stringFileProvider.update();
for (Entry<File, String> entry : stringFileProvider.getStrings().entrySet()) {
addDefinition(entry.getKey(), entry.getValue());
}
}
/**
* @see StringFileProvider#addDirectory(File)
*/
public void addDirectory(File directory) {
stringFileProvider.addDirectory(directory);
}
@Override
public Collection<String> getPackages() {
return messageIdentifiers.keySet();
}
@Override
public Collection<MessageIdentifier> getMessageIdentifiersByPackage(String pkg) {
return messageIdentifiers.get(pkg);
}
@Override
public String get(String type) {
return definitions.get(type);
}
@Override
public boolean has(String type) {
return definitions.containsKey(type);
}
} | 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.message.definition;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.ros.message.MessageDefinitionProvider;
import org.ros.message.MessageIdentifier;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class MessageDefinitionProviderChain implements MessageDefinitionProvider {
private final Collection<MessageDefinitionProvider> messageDefinitionProviders;
public MessageDefinitionProviderChain() {
messageDefinitionProviders = Lists.newArrayList();
}
public void addMessageDefinitionProvider(MessageDefinitionProvider messageDefinitionProvider) {
messageDefinitionProviders.add(messageDefinitionProvider);
}
@Override
public String get(String messageType) {
for (MessageDefinitionProvider messageDefinitionProvider : messageDefinitionProviders) {
if (messageDefinitionProvider.has(messageType)) {
return messageDefinitionProvider.get(messageType);
}
}
throw new NoSuchElementException("No message definition available for: " + messageType);
}
@Override
public boolean has(String messageType) {
for (MessageDefinitionProvider messageDefinitionProvider : messageDefinitionProviders) {
if (messageDefinitionProvider.has(messageType)) {
return true;
}
}
return false;
}
@Override
public Collection<String> getPackages() {
Set<String> result = Sets.newHashSet();
for (MessageDefinitionProvider messageDefinitionProvider : messageDefinitionProviders) {
Collection<String> packages = messageDefinitionProvider.getPackages();
result.addAll(packages);
}
return result;
}
@Override
public Collection<MessageIdentifier> getMessageIdentifiersByPackage(String pkg) {
Set<MessageIdentifier> result = Sets.newHashSet();
for (MessageDefinitionProvider messageDefinitionProvider : messageDefinitionProviders) {
Collection<MessageIdentifier> messageIdentifiers =
messageDefinitionProvider.getMessageIdentifiersByPackage(pkg);
if (messageIdentifiers != null) {
result.addAll(messageIdentifiers);
}
}
return 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.message.definition;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.List;
/**
* Splits message definitions tuples (e.g. service definitions) into separate
* message definitions.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class MessageDefinitionTupleParser {
private static final String SEPARATOR = "---";
/**
* Splits the message definition tuple into a {@link List} of message
* definitions. Split message definitions may be empty (e.g. std_srvs/Empty).
*
* @param definition
* the message definition tuple
* @param size
* the expected tuple size, or -1 to ignore this requirement
* @return a {@link List} of the specified size
*/
public static List<String> parse(String definition, int size) {
Preconditions.checkNotNull(definition);
List<String> definitions = Lists.newArrayList();
StringBuilder current = new StringBuilder();
for (String line : definition.split("\n")) {
if (line.startsWith(SEPARATOR)) {
definitions.add(current.toString());
current = new StringBuilder();
continue;
}
current.append(line);
current.append("\n");
}
if (current.length() > 0) {
current.deleteCharAt(current.length() - 1);
}
definitions.add(current.toString());
Preconditions.checkState(size == -1 || definitions.size() <= size,
String.format("Message tuple exceeds expected size: %d > %d", definitions.size(), size));
while (definitions.size() < size) {
definitions.add("");
}
return definitions;
}
}
| 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.message;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Maps;
import java.util.Map;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class DefaultMessageInterfaceClassProvider implements MessageInterfaceClassProvider {
private final Map<String, Class<?>> cache;
public DefaultMessageInterfaceClassProvider() {
cache = Maps.newConcurrentMap();
}
@SuppressWarnings("unchecked")
@Override
public <T> Class<T> get(String messageType) {
if (cache.containsKey(messageType)) {
return (Class<T>) cache.get(messageType);
}
try {
String className = messageType.replace("/", ".");
Class<T> messageInterfaceClass = (Class<T>) getClass().getClassLoader().loadClass(className);
cache.put(messageType, messageInterfaceClass);
return messageInterfaceClass;
} catch (ClassNotFoundException e) {
return (Class<T>) RawMessage.class;
}
}
@VisibleForTesting
<T> void add(String messageType, Class<T> messageInterfaceClass) {
cache.put(messageType, messageInterfaceClass);
}
}
| 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.message;
import org.jboss.netty.buffer.ChannelBuffer;
import org.ros.exception.RosRuntimeException;
import org.ros.internal.message.context.MessageContext;
import org.ros.internal.message.field.Field;
import org.ros.internal.message.field.MessageFieldType;
import org.ros.internal.message.field.MessageFields;
import org.ros.message.Duration;
import org.ros.message.MessageIdentifier;
import org.ros.message.Time;
import java.util.List;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
class MessageImpl implements RawMessage, GetInstance {
private final MessageContext messageContext;
private final MessageFields messageFields;
public MessageImpl(MessageContext messageContext) {
this.messageContext = messageContext;
messageFields = new MessageFields(messageContext);
}
public MessageContext getMessageContext() {
return messageContext;
}
public MessageFields getMessageFields() {
return messageFields;
}
@Override
public RawMessage toRawMessage() {
return (RawMessage) this;
}
@Override
public MessageIdentifier getIdentifier() {
return messageContext.getMessageIdentifer();
}
@Override
public String getType() {
return messageContext.getType();
}
@Override
public String getPackage() {
return messageContext.getPackage();
}
@Override
public String getName() {
return messageContext.getName();
}
@Override
public String getDefinition() {
return messageContext.getDefinition();
}
@Override
public List<Field> getFields() {
return messageFields.getFields();
}
@Override
public boolean getBool(String name) {
return (Boolean) messageFields.getFieldValue(name);
}
@Override
public boolean[] getBoolArray(String name) {
return (boolean[]) messageFields.getFieldValue(name);
}
@Override
public Duration getDuration(String name) {
return (Duration) messageFields.getFieldValue(name);
}
@SuppressWarnings("unchecked")
@Override
public List<Duration> getDurationList(String name) {
return (List<Duration>) messageFields.getFieldValue(name);
}
@Override
public float getFloat32(String name) {
return (Float) messageFields.getFieldValue(name);
}
@Override
public float[] getFloat32Array(String name) {
return (float[]) messageFields.getFieldValue(name);
}
@Override
public double getFloat64(String name) {
return (Double) messageFields.getFieldValue(name);
}
@Override
public double[] getFloat64Array(String name) {
return (double[]) messageFields.getFieldValue(name);
}
@Override
public short getInt16(String name) {
return (Short) messageFields.getFieldValue(name);
}
@Override
public short[] getInt16Array(String name) {
return (short[]) messageFields.getFieldValue(name);
}
@Override
public int getInt32(String name) {
return (Integer) messageFields.getFieldValue(name);
}
@Override
public int[] getInt32Array(String name) {
return (int[]) messageFields.getFieldValue(name);
}
@Override
public long getInt64(String name) {
return (Long) messageFields.getFieldValue(name);
}
@Override
public long[] getInt64Array(String name) {
return (long[]) messageFields.getFieldValue(name);
}
@Override
public byte getInt8(String name) {
return (Byte) messageFields.getFieldValue(name);
}
@Override
public byte[] getInt8Array(String name) {
return (byte[]) messageFields.getFieldValue(name);
}
@Override
public <T extends Message> T getMessage(String name) {
if (messageFields.getField(name).getType() instanceof MessageFieldType) {
return messageFields.getField(name).<T>getValue();
}
throw new RosRuntimeException("Failed to access message field: " + name);
}
@Override
public <T extends Message> List<T> getMessageList(String name) {
if (messageFields.getField(name).getType() instanceof MessageFieldType) {
return messageFields.getField(name).<List<T>>getValue();
}
throw new RosRuntimeException("Failed to access list field: " + name);
}
@Override
public String getString(String name) {
return (String) messageFields.getFieldValue(name);
}
@SuppressWarnings("unchecked")
@Override
public List<String> getStringList(String name) {
return (List<String>) messageFields.getFieldValue(name);
}
@Override
public Time getTime(String name) {
return (Time) messageFields.getFieldValue(name);
}
@SuppressWarnings("unchecked")
@Override
public List<Time> getTimeList(String name) {
return (List<Time>) messageFields.getFieldValue(name);
}
@Override
public short getUInt16(String name) {
return (Short) messageFields.getFieldValue(name);
}
@Override
public short[] getUInt16Array(String name) {
return (short[]) messageFields.getFieldValue(name);
}
@Override
public int getUInt32(String name) {
return (Integer) messageFields.getFieldValue(name);
}
@Override
public int[] getUInt32Array(String name) {
return (int[]) messageFields.getFieldValue(name);
}
@Override
public long getUInt64(String name) {
return (Long) messageFields.getFieldValue(name);
}
@Override
public long[] getUInt64Array(String name) {
return (long[]) messageFields.getFieldValue(name);
}
@Override
public short getUInt8(String name) {
return (Short) messageFields.getFieldValue(name);
}
@Override
public short[] getUInt8Array(String name) {
return (short[]) messageFields.getFieldValue(name);
}
@Override
public void setBool(String name, boolean value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setBoolArray(String name, boolean[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setDurationList(String name, List<Duration> value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setDuration(String name, Duration value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setFloat32(String name, float value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setFloat32Array(String name, float[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setFloat64(String name, double value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setFloat64Array(String name, double[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setInt16(String name, short value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setInt16Array(String name, short[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setInt32(String name, int value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setInt32Array(String name, int[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setInt64(String name, long value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setInt64Array(String name, long[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setInt8(String name, byte value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setInt8Array(String name, byte[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setMessage(String name, Message value) {
// TODO(damonkohler): Verify the type of the provided Message?
messageFields.setFieldValue(name, value);
}
@Override
public void setMessageList(String name, List<Message> value) {
// TODO(damonkohler): Verify the type of all Messages in the provided list?
messageFields.setFieldValue(name, value);
}
@Override
public void setString(String name, String value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setStringList(String name, List<String> value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setTime(String name, Time value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setTimeList(String name, List<Time> value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setUInt16(String name, short value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setUInt16Array(String name, short[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setUInt32(String name, int value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setUInt32Array(String name, int[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setUInt64(String name, long value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setUInt64Array(String name, long[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setUInt8(String name, byte value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setUInt8Array(String name, byte[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public byte getByte(String name) {
return (Byte) messageFields.getFieldValue(name);
}
@Override
public short getChar(String name) {
return (Short) messageFields.getFieldValue(name);
}
@Override
public void setByte(String name, byte value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setChar(String name, short value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setByteArray(String name, byte[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public void setCharArray(String name, short[] value) {
messageFields.setFieldValue(name, value);
}
@Override
public byte[] getByteArray(String name) {
return (byte[]) messageFields.getFieldValue(name);
}
@Override
public short[] getCharArray(String name) {
return (short[]) messageFields.getFieldValue(name);
}
@Override
public ChannelBuffer getChannelBuffer(String name) {
return (ChannelBuffer) messageFields.getFieldValue(name);
}
@Override
public void setChannelBuffer(String name, ChannelBuffer value) {
messageFields.setFieldValue(name, value);
}
@Override
public Object getInstance() {
return this;
}
@Override
public String toString() {
return String.format("MessageImpl<%s>", getType());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((messageContext == null) ? 0 : messageContext.hashCode());
result = prime * result + ((messageFields == null) ? 0 : messageFields.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof GetInstance))
return false;
obj = ((GetInstance) obj).getInstance();
if (getClass() != obj.getClass())
return false;
MessageImpl other = (MessageImpl) obj;
if (messageContext == null) {
if (other.messageContext != null)
return false;
} else if (!messageContext.equals(other.messageContext))
return false;
if (messageFields == null) {
if (other.messageFields != null)
return false;
} else if (!messageFields.equals(other.messageFields))
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.message;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.io.FileUtils;
import org.ros.EnvironmentVariables;
import org.ros.exception.RosRuntimeException;
import org.ros.internal.message.definition.MessageDefinitionProviderChain;
import org.ros.internal.message.definition.MessageDefinitionTupleParser;
import org.ros.internal.message.service.ServiceDefinitionFileProvider;
import org.ros.internal.message.topic.TopicDefinitionFileProvider;
import org.ros.message.MessageDeclaration;
import org.ros.message.MessageFactory;
import org.ros.message.MessageIdentifier;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class GenerateInterfaces {
private final TopicDefinitionFileProvider topicDefinitionFileProvider;
private final ServiceDefinitionFileProvider serviceDefinitionFileProvider;
private final MessageDefinitionProviderChain messageDefinitionProviderChain;
private final MessageFactory messageFactory;
public GenerateInterfaces() {
messageDefinitionProviderChain = new MessageDefinitionProviderChain();
topicDefinitionFileProvider = new TopicDefinitionFileProvider();
messageDefinitionProviderChain.addMessageDefinitionProvider(topicDefinitionFileProvider);
serviceDefinitionFileProvider = new ServiceDefinitionFileProvider();
messageDefinitionProviderChain.addMessageDefinitionProvider(serviceDefinitionFileProvider);
messageFactory = new DefaultMessageFactory(messageDefinitionProviderChain);
}
/**
* @param packages
* a list of packages containing the topic types to generate
* interfaces for
* @param outputDirectory
* the directory to write the generated interfaces to
* @throws IOException
*/
private void writeTopicInterfaces(File outputDirectory, Collection<String> packages)
throws IOException {
Collection<MessageIdentifier> topicTypes = Sets.newHashSet();
if (packages.size() == 0) {
packages = topicDefinitionFileProvider.getPackages();
}
for (String pkg : packages) {
Collection<MessageIdentifier> messageIdentifiers =
topicDefinitionFileProvider.getMessageIdentifiersByPackage(pkg);
if (messageIdentifiers != null) {
topicTypes.addAll(messageIdentifiers);
}
}
for (MessageIdentifier topicType : topicTypes) {
String definition = messageDefinitionProviderChain.get(topicType.getType());
MessageDeclaration messageDeclaration = new MessageDeclaration(topicType, definition);
writeInterface(messageDeclaration, outputDirectory, true);
}
}
/**
* @param packages
* a list of packages containing the topic types to generate
* interfaces for
* @param outputDirectory
* the directory to write the generated interfaces to
* @throws IOException
*/
private void writeServiceInterfaces(File outputDirectory, Collection<String> packages)
throws IOException {
Collection<MessageIdentifier> serviceTypes = Sets.newHashSet();
if (packages.size() == 0) {
packages = serviceDefinitionFileProvider.getPackages();
}
for (String pkg : packages) {
Collection<MessageIdentifier> messageIdentifiers =
serviceDefinitionFileProvider.getMessageIdentifiersByPackage(pkg);
if (messageIdentifiers != null) {
serviceTypes.addAll(messageIdentifiers);
}
}
for (MessageIdentifier serviceType : serviceTypes) {
String definition = messageDefinitionProviderChain.get(serviceType.getType());
MessageDeclaration serviceDeclaration =
MessageDeclaration.of(serviceType.getType(), definition);
writeInterface(serviceDeclaration, outputDirectory, false);
List<String> requestAndResponse = MessageDefinitionTupleParser.parse(definition, 2);
MessageDeclaration requestDeclaration =
MessageDeclaration.of(serviceType.getType() + "Request", requestAndResponse.get(0));
MessageDeclaration responseDeclaration =
MessageDeclaration.of(serviceType.getType() + "Response", requestAndResponse.get(1));
writeInterface(requestDeclaration, outputDirectory, true);
writeInterface(responseDeclaration, outputDirectory, true);
}
}
private void writeInterface(MessageDeclaration messageDeclaration, File outputDirectory,
boolean addConstantsAndMethods) {
MessageInterfaceBuilder builder = new MessageInterfaceBuilder();
builder.setPackageName(messageDeclaration.getPackage());
builder.setInterfaceName(messageDeclaration.getName());
builder.setMessageDeclaration(messageDeclaration);
builder.setAddConstantsAndMethods(addConstantsAndMethods);
try {
String content;
content = builder.build(messageFactory);
File file = new File(outputDirectory, messageDeclaration.getType() + ".java");
FileUtils.writeStringToFile(file, content);
} catch (Exception e) {
System.out.printf("Failed to generate interface for %s.\n", messageDeclaration.getType());
e.printStackTrace();
}
}
public void generate(File outputDirectory, Collection<String> packages,
Collection<File> packagePath) {
for (File directory : packagePath) {
topicDefinitionFileProvider.addDirectory(directory);
serviceDefinitionFileProvider.addDirectory(directory);
}
topicDefinitionFileProvider.update();
serviceDefinitionFileProvider.update();
try {
writeTopicInterfaces(outputDirectory, packages);
writeServiceInterfaces(outputDirectory, packages);
} catch (IOException e) {
throw new RosRuntimeException(e);
}
}
public static void main(String[] args) {
List<String> arguments = Lists.newArrayList(args);
if (arguments.size() == 0) {
arguments.add(".");
}
String rosPackagePath = System.getenv(EnvironmentVariables.ROS_PACKAGE_PATH);
Collection<File> packagePath = Lists.newArrayList();
for (String path : rosPackagePath.split(File.pathSeparator)) {
File packageDirectory = new File(path);
if (packageDirectory.exists()) {
packagePath.add(packageDirectory);
}
}
GenerateInterfaces generateInterfaces = new GenerateInterfaces();
File outputDirectory = new File(arguments.remove(0));
generateInterfaces.generate(outputDirectory, arguments, packagePath);
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.exception;
/**
* @author ethan.rublee@gmail.com (Ethan Rublee)
*/
public class RosException extends Exception {
public RosException(final Throwable throwable) {
super(throwable);
}
public RosException(final String message, final Throwable throwable) {
super(message, throwable);
}
public RosException(final String message) {
super(message);
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides the classes for representing common rosjava exceptions.
*/
package org.ros.exception; | Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.exception;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class RosRuntimeException extends RuntimeException {
public RosRuntimeException(final Throwable throwable) {
super(throwable);
}
public RosRuntimeException(final String message, final Throwable throwable) {
super(message, throwable);
}
public RosRuntimeException(final String message) {
super(message);
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros;
import org.ros.namespace.GraphName;
/**
* ROS parameters.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public interface Parameters {
public static final GraphName USE_SIM_TIME = GraphName.of("/use_sim_time");
}
| 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;
/**
* Remapping keys used to override ROS environment and other configuration
* settings from a command-line-based executation of a node. As of ROS 1.4, only
* {@code CommandLine.NODE_NAME} and {@code CommandLine.ROS_NAMESPACE} are
* required.
*
* @author kwc@willowgarage.com (Ken Conley)
*/
public interface CommandLineVariables {
public static String ROS_NAMESPACE = "__ns";
public static String ROS_IP = "__ip";
public static String ROS_MASTER_URI = "__master";
public static String TCPROS_PORT = "__tcpros_server_port";
public static String NODE_NAME = "__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.
*/
package org.ros;
import org.ros.namespace.GraphName;
/**
* ROS topics.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public interface Topics {
public static final GraphName ROSOUT = GraphName.of("/rosout");
public static final GraphName CLOCK = GraphName.of("/clock");
}
| 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 org.apache.commons.logging.Log;
import org.ros.concurrent.CancellableLoop;
import org.ros.message.MessageFactory;
import org.ros.namespace.GraphName;
import org.ros.namespace.NameResolver;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.parameter.ParameterTree;
import org.ros.node.topic.Publisher;
import java.util.List;
import java.util.Map;
/**
* This node is used in rostest end-to-end integration tests with other client
* libraries.
*
* @author kwc@willowgarage.com (Ken Conley)
*/
public class ParameterServerTestNode extends AbstractNodeMain {
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("rosjava/parameter_server_test_node");
}
@SuppressWarnings("rawtypes")
@Override
public void onStart(ConnectedNode connectedNode) {
final Publisher<std_msgs.String> pub_tilde =
connectedNode.newPublisher("tilde", std_msgs.String._TYPE);
final Publisher<std_msgs.String> pub_string =
connectedNode.newPublisher("string", std_msgs.String._TYPE);
final Publisher<std_msgs.Int64> pub_int =
connectedNode.newPublisher("int", std_msgs.Int64._TYPE);
final Publisher<std_msgs.Bool> pub_bool =
connectedNode.newPublisher("bool", std_msgs.Bool._TYPE);
final Publisher<std_msgs.Float64> pub_float =
connectedNode.newPublisher("float", std_msgs.Float64._TYPE);
final Publisher<test_ros.Composite> pub_composite =
connectedNode.newPublisher("composite", test_ros.Composite._TYPE);
final Publisher<test_ros.TestArrays> pub_list =
connectedNode.newPublisher("list", test_ros.TestArrays._TYPE);
ParameterTree param = connectedNode.getParameterTree();
Log log = connectedNode.getLog();
MessageFactory topicMessageFactory = connectedNode.getTopicMessageFactory();
final std_msgs.String tilde_m = topicMessageFactory.newFromType(std_msgs.String._TYPE);
tilde_m.setData(param.getString(connectedNode.resolveName("~tilde").toString()));
log.info("tilde: " + tilde_m.getData());
GraphName paramNamespace = GraphName.of(param.getString("parameter_namespace"));
GraphName targetNamespace = GraphName.of(param.getString("target_namespace"));
log.info("parameter_namespace: " + paramNamespace);
log.info("target_namespace: " + targetNamespace);
NameResolver resolver = connectedNode.getResolver().newChild(paramNamespace);
NameResolver setResolver = connectedNode.getResolver().newChild(targetNamespace);
final std_msgs.String string_m = topicMessageFactory.newFromType(std_msgs.String._TYPE);
string_m.setData(param.getString(resolver.resolve("string")));
log.info("string: " + string_m.getData());
final std_msgs.Int64 int_m = topicMessageFactory.newFromType(std_msgs.Int64._TYPE);
int_m.setData(param.getInteger(resolver.resolve("int")));
log.info("int: " + int_m.getData());
final std_msgs.Bool bool_m = topicMessageFactory.newFromType(std_msgs.Bool._TYPE);
bool_m.setData(param.getBoolean(resolver.resolve("bool")));
log.info("bool: " + bool_m.getData());
final std_msgs.Float64 float_m = topicMessageFactory.newFromType(std_msgs.Float64._TYPE);
float_m.setData(param.getDouble(resolver.resolve("float")));
log.info("float: " + float_m.getData());
final test_ros.Composite composite_m =
topicMessageFactory.newFromType(test_ros.Composite._TYPE);
Map composite_map = param.getMap(resolver.resolve("composite"));
composite_m.getA().setW((Double) ((Map) composite_map.get("a")).get("w"));
composite_m.getA().setX((Double) ((Map) composite_map.get("a")).get("x"));
composite_m.getA().setY((Double) ((Map) composite_map.get("a")).get("y"));
composite_m.getA().setZ((Double) ((Map) composite_map.get("a")).get("z"));
composite_m.getB().setX((Double) ((Map) composite_map.get("b")).get("x"));
composite_m.getB().setY((Double) ((Map) composite_map.get("b")).get("y"));
composite_m.getB().setZ((Double) ((Map) composite_map.get("b")).get("z"));
final test_ros.TestArrays list_m = topicMessageFactory.newFromType(test_ros.TestArrays._TYPE);
// only using the integer part for easier (non-float) comparison
@SuppressWarnings("unchecked")
List<Integer> list = (List<Integer>) param.getList(resolver.resolve("list"));
int[] data = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
data[i] = list.get(i);
}
list_m.setInt32Array(data);
// Set parameters
param.set(setResolver.resolve("string"), string_m.getData());
param.set(setResolver.resolve("int"), (int) int_m.getData());
param.set(setResolver.resolve("float"), float_m.getData());
param.set(setResolver.resolve("bool"), bool_m.getData());
param.set(setResolver.resolve("composite"), composite_map);
param.set(setResolver.resolve("list"), list);
connectedNode.executeCancellableLoop(new CancellableLoop() {
@Override
protected void loop() throws InterruptedException {
pub_tilde.publish(tilde_m);
pub_string.publish(string_m);
pub_int.publish(int_m);
pub_bool.publish(bool_m);
pub_float.publish(float_m);
pub_composite.publish(composite_m);
pub_list.publish(list_m);
Thread.sleep(100);
}
});
}
}
| 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 org.ros.concurrent.CancellableLoop;
import org.ros.message.MessageFactory;
import org.ros.message.MessageListener;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
/**
* This node is used to test the slave API externally using rostest.
*
* @author kwc@willowgarage.com (Ken Conley)
*/
public class SlaveApiTestNode extends AbstractNodeMain {
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("rosjava/slave_api_test_node");
}
@Override
public void onStart(final ConnectedNode connectedNode) {
// Basic chatter in/out test.
final Publisher<std_msgs.String> pub_string =
connectedNode.newPublisher("chatter_out", std_msgs.String._TYPE);
MessageListener<std_msgs.String> chatter_cb = new MessageListener<std_msgs.String>() {
@Override
public void onNewMessage(std_msgs.String m) {
System.out.println("String: " + m.getData());
}
};
Subscriber<std_msgs.String> stringSubscriber =
connectedNode.newSubscriber("chatter_in", std_msgs.String._TYPE);
stringSubscriber.addMessageListener(chatter_cb);
// Have at least one case of dual pub/sub on the same topic.
final Publisher<std_msgs.Int64> pub_int64_pubsub =
connectedNode.newPublisher("int64", std_msgs.Int64._TYPE);
MessageListener<std_msgs.Int64> int64_cb = new MessageListener<std_msgs.Int64>() {
@Override
public void onNewMessage(std_msgs.Int64 m) {
}
};
Subscriber<std_msgs.Int64> int64Subscriber =
connectedNode.newSubscriber("int64", "std_msgs/std_msgs.Int64");
int64Subscriber.addMessageListener(int64_cb);
// Don't do any performance optimizations here. We want to make sure that
// GC, etc. is working.
connectedNode.executeCancellableLoop(new CancellableLoop() {
@Override
protected void loop() throws InterruptedException {
MessageFactory topicMessageFactory = connectedNode.getTopicMessageFactory();
std_msgs.String chatter = topicMessageFactory.newFromType(std_msgs.String._TYPE);
chatter.setData("hello " + System.currentTimeMillis());
pub_string.publish(chatter);
std_msgs.Int64 num = topicMessageFactory.newFromType(std_msgs.Int64._TYPE);
num.setData(1);
pub_int64_pubsub.publish(num);
Thread.sleep(100);
}
});
}
}
| 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 org.ros.message.MessageListener;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
/**
* This node is used in rostest end-to-end integration tests with other client
* libraries.
*
* @author kwc@willowgarage.com (Ken Conley)
*/
public class PassthroughTestNode extends AbstractNodeMain {
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("rosjava/passthrough_test_node");
}
@Override
public void onStart(final ConnectedNode connectedNode) {
// The goal of the passthrough node is simply to retransmit the messages
// sent to it. This allows us to external verify that the node is compatible
// with multiple publishers, multiple subscribers, etc...
// String pass through
final Publisher<std_msgs.String> pub_string =
connectedNode.newPublisher("string_out", std_msgs.String._TYPE);
MessageListener<std_msgs.String> string_cb = new MessageListener<std_msgs.String>() {
@Override
public void onNewMessage(std_msgs.String m) {
pub_string.publish(m);
}
};
Subscriber<std_msgs.String> stringSubscriber =
connectedNode.newSubscriber("string_in", "std_msgs/String");
stringSubscriber.addMessageListener(string_cb);
// Int64 pass through
final Publisher<std_msgs.Int64> pub_int64 = connectedNode.newPublisher("int64_out", "std_msgs/Int64");
MessageListener<std_msgs.Int64> int64_cb = new MessageListener<std_msgs.Int64>() {
@Override
public void onNewMessage(std_msgs.Int64 m) {
pub_int64.publish(m);
}
};
Subscriber<std_msgs.Int64> int64Subscriber = connectedNode.newSubscriber("int64_in", "std_msgs/Int64");
int64Subscriber.addMessageListener(int64_cb);
// TestHeader pass through
final Publisher<test_ros.TestHeader> pub_header =
connectedNode.newPublisher("test_header_out", test_ros.TestHeader._TYPE);
MessageListener<test_ros.TestHeader> header_cb = new MessageListener<test_ros.TestHeader>() {
@Override
public void onNewMessage(test_ros.TestHeader m) {
m.setOrigCallerId(m.getCallerId());
m.setCallerId(connectedNode.getName().toString());
pub_header.publish(m);
}
};
Subscriber<test_ros.TestHeader> testHeaderSubscriber =
connectedNode.newSubscriber("test_header_in", "test_ros/TestHeader");
testHeaderSubscriber.addMessageListener(header_cb);
// TestComposite pass through
final Publisher<test_ros.Composite> pub_composite =
connectedNode.newPublisher("composite_out", "test_ros/Composite");
MessageListener<test_ros.Composite> composite_cb = new MessageListener<test_ros.Composite>() {
@Override
public void onNewMessage(test_ros.Composite m) {
pub_composite.publish(m);
}
};
Subscriber<test_ros.Composite> compositeSubscriber =
connectedNode.newSubscriber("composite_in", "test_ros/Composite");
compositeSubscriber.addMessageListener(composite_cb);
}
}
| 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;
import nav_msgs.Odometry;
import org.ros.message.MessageListener;
import org.ros.namespace.GraphName;
import org.ros.node.ConnectedNode;
import org.ros.node.Node;
import org.ros.node.NodeMain;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class MessageSerializationTestNode implements NodeMain {
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("message_serialization_test_node");
}
@Override
public void onStart(ConnectedNode connectedNode) {
final Publisher<nav_msgs.Odometry> publisher =
connectedNode.newPublisher("odom_echo", nav_msgs.Odometry._TYPE);
Subscriber<nav_msgs.Odometry> subscriber =
connectedNode.newSubscriber("odom", nav_msgs.Odometry._TYPE);
subscriber.addMessageListener(new MessageListener<Odometry>() {
@Override
public void onNewMessage(Odometry message) {
publisher.publish(message);
}
});
}
@Override
public void onShutdown(Node node) {
}
@Override
public void onShutdownComplete(Node node) {
}
@Override
public void onError(Node node, Throwable throwable) {
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.rosjava_tutorial_right_hand_rule;
import org.ros.message.MessageListener;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class RightHandRule extends AbstractNodeMain {
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("right_hand_rule");
}
@Override
public void onStart(ConnectedNode connectedNode) {
final Publisher<geometry_msgs.Twist> publisher =
connectedNode.newPublisher("cmd_vel", geometry_msgs.Twist._TYPE);
final geometry_msgs.Twist twist = publisher.newMessage();
final Subscriber<sensor_msgs.LaserScan> subscriber =
connectedNode.newSubscriber("base_scan", sensor_msgs.LaserScan._TYPE);
subscriber.addMessageListener(new MessageListener<sensor_msgs.LaserScan>() {
@Override
public void onNewMessage(sensor_msgs.LaserScan message) {
float[] ranges = message.getRanges();
float northRange = ranges[ranges.length / 2];
float northEastRange = ranges[ranges.length / 3];
double linearVelocity = 0.5;
double angularVelocity = -0.5;
if (northRange < 1. || northEastRange < 1.) {
linearVelocity = 0;
angularVelocity = 0.5;
}
twist.getAngular().setZ(angularVelocity);
twist.getLinear().setX(linearVelocity);
publisher.publish(twist);
}
});
}
}
| 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.rosjava_tutorial_pubsub;
import org.apache.commons.logging.Log;
import org.ros.message.MessageListener;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.NodeMain;
import org.ros.node.topic.Subscriber;
/**
* A simple {@link Subscriber} {@link NodeMain}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class Listener extends AbstractNodeMain {
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("rosjava_tutorial_pubsub/listener");
}
@Override
public void onStart(ConnectedNode connectedNode) {
final Log log = connectedNode.getLog();
Subscriber<std_msgs.String> subscriber = connectedNode.newSubscriber("chatter", std_msgs.String._TYPE);
subscriber.addMessageListener(new MessageListener<std_msgs.String>() {
@Override
public void onNewMessage(std_msgs.String message) {
log.info("I heard: \"" + message.getData() + "\"");
}
});
}
}
| 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.rosjava_tutorial_pubsub;
import org.ros.concurrent.CancellableLoop;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.NodeMain;
import org.ros.node.topic.Publisher;
/**
* A simple {@link Publisher} {@link NodeMain}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class Talker extends AbstractNodeMain {
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("rosjava_tutorial_pubsub/talker");
}
@Override
public void onStart(final ConnectedNode connectedNode) {
final Publisher<std_msgs.String> publisher =
connectedNode.newPublisher("chatter", std_msgs.String._TYPE);
// This CancellableLoop will be canceled automatically when the node shuts
// down.
connectedNode.executeCancellableLoop(new CancellableLoop() {
private int sequenceNumber;
@Override
protected void setup() {
sequenceNumber = 0;
}
@Override
protected void loop() throws InterruptedException {
std_msgs.String str = publisher.newMessage();
str.setData("Hello world! " + sequenceNumber);
publisher.publish(str);
sequenceNumber++;
Thread.sleep(1000);
}
});
}
}
| 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.rosjava_benchmarks;
import org.ros.concurrent.CancellableLoop;
import org.ros.concurrent.Rate;
import org.ros.concurrent.WallTimeRate;
import org.ros.message.Duration;
import org.ros.message.Time;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.topic.Publisher;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class MessagesBenchmark extends AbstractNodeMain {
private final AtomicInteger counter;
private Time time;
public MessagesBenchmark() {
counter = new AtomicInteger();
}
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("messages_benchmark");
}
@Override
public void onStart(final ConnectedNode connectedNode) {
connectedNode.executeCancellableLoop(new CancellableLoop() {
@Override
protected void loop() throws InterruptedException {
geometry_msgs.TransformStamped message =
connectedNode.getTopicMessageFactory()
.newFromType(geometry_msgs.TransformStamped._TYPE);
message.getHeader().setFrameId("world");
message.setChildFrameId("turtle");
message.getHeader().setStamp(connectedNode.getCurrentTime());
message.getTransform().getRotation().setW(Math.random());
message.getTransform().getRotation().setX(Math.random());
message.getTransform().getRotation().setY(Math.random());
message.getTransform().getRotation().setZ(Math.random());
message.getTransform().getTranslation().setX(Math.random());
message.getTransform().getTranslation().setY(Math.random());
message.getTransform().getTranslation().setZ(Math.random());
counter.incrementAndGet();
}
});
time = connectedNode.getCurrentTime();
final Publisher<std_msgs.String> statusPublisher =
connectedNode.newPublisher("status", std_msgs.String._TYPE);
final Rate rate = new WallTimeRate(1);
final std_msgs.String status = statusPublisher.newMessage();
connectedNode.executeCancellableLoop(new CancellableLoop() {
@Override
protected void loop() throws InterruptedException {
Time now = connectedNode.getCurrentTime();
Duration delta = now.subtract(time);
if (delta.totalNsecs() > TimeUnit.NANOSECONDS.convert(5, TimeUnit.SECONDS)) {
double hz = counter.getAndSet(0) * 1e9 / delta.totalNsecs();
status.setData(String.format("%.2f Hz", hz));
statusPublisher.publish(status);
time = now;
}
rate.sleep();
}
});
}
}
| 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.rosjava_benchmarks;
import org.ros.concurrent.CancellableLoop;
import org.ros.concurrent.Rate;
import org.ros.concurrent.WallTimeRate;
import org.ros.message.Duration;
import org.ros.message.Time;
import org.ros.namespace.GraphName;
import org.ros.namespace.NameResolver;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.topic.Publisher;
import org.ros.rosjava_geometry.FrameTransformTree;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class TransformBenchmark extends AbstractNodeMain {
private final AtomicInteger counter;
private Time time;
public TransformBenchmark() {
counter = new AtomicInteger();
}
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("transform_benchmark");
}
@Override
public void onStart(final ConnectedNode connectedNode) {
final geometry_msgs.TransformStamped turtle1 =
connectedNode.getTopicMessageFactory().newFromType(geometry_msgs.TransformStamped._TYPE);
turtle1.getHeader().setFrameId("world");
turtle1.setChildFrameId("turtle1");
final geometry_msgs.TransformStamped turtle2 =
connectedNode.getTopicMessageFactory().newFromType(geometry_msgs.TransformStamped._TYPE);
turtle2.getHeader().setFrameId("world");
turtle2.setChildFrameId("turtle2");
final FrameTransformTree frameTransformTree = new FrameTransformTree(NameResolver.newRoot());
connectedNode.executeCancellableLoop(new CancellableLoop() {
@Override
protected void loop() throws InterruptedException {
updateTransform(turtle1, connectedNode, frameTransformTree);
updateTransform(turtle2, connectedNode, frameTransformTree);
frameTransformTree.transform("turtle1", "turtle2");
counter.incrementAndGet();
}
});
time = connectedNode.getCurrentTime();
final Publisher<std_msgs.String> statusPublisher =
connectedNode.newPublisher("status", std_msgs.String._TYPE);
final Rate rate = new WallTimeRate(1);
final std_msgs.String status = statusPublisher.newMessage();
connectedNode.executeCancellableLoop(new CancellableLoop() {
@Override
protected void loop() throws InterruptedException {
Time now = connectedNode.getCurrentTime();
Duration delta = now.subtract(time);
if (delta.totalNsecs() > TimeUnit.NANOSECONDS.convert(5, TimeUnit.SECONDS)) {
double hz = counter.getAndSet(0) * 1e9 / delta.totalNsecs();
status.setData(String.format("%.2f Hz", hz));
statusPublisher.publish(status);
time = now;
}
rate.sleep();
}
});
}
private void updateTransform(geometry_msgs.TransformStamped transformStamped,
ConnectedNode connectedNode, FrameTransformTree frameTransformTree) {
transformStamped.getHeader().setStamp(connectedNode.getCurrentTime());
transformStamped.getTransform().getRotation().setW(Math.random());
transformStamped.getTransform().getRotation().setX(Math.random());
transformStamped.getTransform().getRotation().setY(Math.random());
transformStamped.getTransform().getRotation().setZ(Math.random());
transformStamped.getTransform().getTranslation().setX(Math.random());
transformStamped.getTransform().getTranslation().setY(Math.random());
transformStamped.getTransform().getTranslation().setZ(Math.random());
frameTransformTree.update(transformStamped);
}
}
| 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.rosjava_benchmarks;
import org.ros.concurrent.CancellableLoop;
import org.ros.concurrent.Rate;
import org.ros.concurrent.WallTimeRate;
import org.ros.message.Duration;
import org.ros.message.MessageListener;
import org.ros.message.Time;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;
import tf.tfMessage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author damonkohler@google.com (Damon Kohler)
*/
public class PubsubBenchmark extends AbstractNodeMain {
private final AtomicInteger counter;
private Publisher<std_msgs.String> statusPublisher;
private Publisher<tf.tfMessage> tfPublisher;
private Subscriber<tf.tfMessage> tfSubscriber;
private Time time;
public PubsubBenchmark() {
counter = new AtomicInteger();
}
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("pubsub_benchmark");
}
@Override
public void onStart(final ConnectedNode connectedNode) {
tfSubscriber = connectedNode.newSubscriber("tf", tf.tfMessage._TYPE);
tfSubscriber.addMessageListener(new MessageListener<tf.tfMessage>() {
@Override
public void onNewMessage(tfMessage message) {
counter.incrementAndGet();
}
});
tfPublisher = connectedNode.newPublisher("tf", tf.tfMessage._TYPE);
final tf.tfMessage tfMessage = tfPublisher.newMessage();
geometry_msgs.TransformStamped transformStamped =
connectedNode.getTopicMessageFactory().newFromType(geometry_msgs.TransformStamped._TYPE);
tfMessage.getTransforms().add(transformStamped);
connectedNode.executeCancellableLoop(new CancellableLoop() {
@Override
protected void loop() throws InterruptedException {
tfPublisher.publish(tfMessage);
}
});
time = connectedNode.getCurrentTime();
statusPublisher = connectedNode.newPublisher("status", std_msgs.String._TYPE);
final Rate rate = new WallTimeRate(1);
final std_msgs.String status = statusPublisher.newMessage();
connectedNode.executeCancellableLoop(new CancellableLoop() {
@Override
protected void loop() throws InterruptedException {
Time now = connectedNode.getCurrentTime();
Duration delta = now.subtract(time);
if (delta.totalNsecs() > TimeUnit.NANOSECONDS.convert(5, TimeUnit.SECONDS)) {
double hz = counter.getAndSet(0) * 1e9 / delta.totalNsecs();
status.setData(String.format("%.2f Hz", hz));
statusPublisher.publish(status);
time = now;
}
rate.sleep();
}
});
}
}
| 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.rosjava_geometry;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.List;
/**
* A quaternion.
*
* @author damonkohler@google.com (Damon Kohler)
* @author moesenle@google.com (Lorenz Moesenlechner)
*/
public class Quaternion {
private final double x;
private final double y;
private final double z;
private final double w;
public static Quaternion fromAxisAngle(Vector3 axis, double angle) {
Vector3 normalized = axis.normalize();
double sin = Math.sin(angle / 2.0d);
double cos = Math.cos(angle / 2.0d);
return new Quaternion(normalized.getX() * sin, normalized.getY() * sin,
normalized.getZ() * sin, cos);
}
public static Quaternion fromQuaternionMessage(geometry_msgs.Quaternion message) {
return new Quaternion(message.getX(), message.getY(), message.getZ(), message.getW());
}
public static Quaternion rotationBetweenVectors(Vector3 vector1, Vector3 vector2) {
Preconditions.checkArgument(vector1.getMagnitude() > 0,
"Cannot calculate rotation between zero-length vectors.");
Preconditions.checkArgument(vector2.getMagnitude() > 0,
"Cannot calculate rotation between zero-length vectors.");
if (vector1.normalize().equals(vector2.normalize())) {
return identity();
}
double angle =
Math.acos(vector1.dotProduct(vector2) / (vector1.getMagnitude() * vector2.getMagnitude()));
double axisX = vector1.getY() * vector2.getZ() - vector1.getZ() * vector2.getY();
double axisY = vector1.getZ() * vector2.getX() - vector1.getX() * vector2.getZ();
double axisZ = vector1.getX() * vector2.getY() - vector1.getY() * vector2.getX();
return fromAxisAngle(new Vector3(axisX, axisY, axisZ), angle);
}
public static Quaternion identity() {
return new Quaternion(0, 0, 0, 1);
}
public Quaternion(double x, double y, double z, double w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
public Quaternion scale(double factor) {
return new Quaternion(x * factor, y * factor, z * factor, w * factor);
}
public Quaternion conjugate() {
return new Quaternion(-x, -y, -z, w);
}
public Quaternion invert() {
double mm = getMagnitudeSquared();
Preconditions.checkState(mm != 0);
return conjugate().scale(1 / mm);
}
public Quaternion normalize() {
return scale(1 / getMagnitude());
}
public Quaternion multiply(Quaternion other) {
return new Quaternion(w * other.x + x * other.w + y * other.z - z * other.y, w * other.y + y
* other.w + z * other.x - x * other.z, w * other.z + z * other.w + x * other.y - y
* other.x, w * other.w - x * other.x - y * other.y - z * other.z);
}
public Vector3 rotateAndScaleVector(Vector3 vector) {
Quaternion vectorQuaternion = new Quaternion(vector.getX(), vector.getY(), vector.getZ(), 0);
Quaternion rotatedQuaternion = multiply(vectorQuaternion.multiply(conjugate()));
return new Vector3(rotatedQuaternion.getX(), rotatedQuaternion.getY(), rotatedQuaternion.getZ());
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getZ() {
return z;
}
public double getW() {
return w;
}
public double getMagnitudeSquared() {
return x * x + y * y + z * z + w * w;
}
public double getMagnitude() {
return Math.sqrt(getMagnitudeSquared());
}
public boolean isAlmostNeutral(double epsilon) {
return Math.abs(1 - x * x - y * y - z * z - w * w) < epsilon;
}
public geometry_msgs.Quaternion toQuaternionMessage(geometry_msgs.Quaternion result) {
result.setX(x);
result.setY(y);
result.setZ(z);
result.setW(w);
return result;
}
public boolean almostEquals(Quaternion other, double epsilon) {
List<Double> epsilons = Lists.newArrayList();
epsilons.add(x - other.x);
epsilons.add(y - other.y);
epsilons.add(z - other.z);
epsilons.add(w - other.w);
for (double e : epsilons) {
if (Math.abs(e) > epsilon) {
return false;
}
}
return true;
}
@Override
public String toString() {
return String.format("Quaternion<x: %.4f, y: %.4f, z: %.4f, w: %.4f>", x, y, z, w);
}
@Override
public int hashCode() {
// Ensure that -0 and 0 are considered equal.
double w = this.w == 0 ? 0 : this.w;
double x = this.x == 0 ? 0 : this.x;
double y = this.y == 0 ? 0 : this.y;
double z = this.z == 0 ? 0 : this.z;
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(w);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(x);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(z);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Quaternion other = (Quaternion) obj;
// Ensure that -0 and 0 are considered equal.
double w = this.w == 0 ? 0 : this.w;
double x = this.x == 0 ? 0 : this.x;
double y = this.y == 0 ? 0 : this.y;
double z = this.z == 0 ? 0 : this.z;
double otherW = other.w == 0 ? 0 : other.w;
double otherX = other.x == 0 ? 0 : other.x;
double otherY = other.y == 0 ? 0 : other.y;
double otherZ = other.z == 0 ? 0 : other.z;
if (Double.doubleToLongBits(w) != Double.doubleToLongBits(otherW))
return false;
if (Double.doubleToLongBits(x) != Double.doubleToLongBits(otherX))
return false;
if (Double.doubleToLongBits(y) != Double.doubleToLongBits(otherY))
return false;
if (Double.doubleToLongBits(z) != Double.doubleToLongBits(otherZ))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Provides the classes for common geometry operations and representations (e.g. transformations).
*/
package org.ros.rosjava_geometry; | 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.rosjava_geometry;
import com.google.common.collect.Lists;
import java.util.List;
/**
* A three dimensional vector.
*
* @author damonkohler@google.com (Damon Kohler)
* @author moesenle@google.com (Lorenz Moesenlechner)
*/
public class Vector3 {
private static final Vector3 ZERO = new Vector3(0, 0, 0);
private static final Vector3 X_AXIS = new Vector3(1, 0, 0);
private static final Vector3 Y_AXIS = new Vector3(0, 1, 0);
private static final Vector3 Z_AXIS = new Vector3(0, 0, 1);
private final double x;
private final double y;
private final double z;
public static Vector3 fromVector3Message(geometry_msgs.Vector3 message) {
return new Vector3(message.getX(), message.getY(), message.getZ());
}
public static Vector3 fromPointMessage(geometry_msgs.Point message) {
return new Vector3(message.getX(), message.getY(), message.getZ());
}
public static Vector3 zero() {
return ZERO;
}
public static Vector3 xAxis() {
return X_AXIS;
}
public static Vector3 yAxis() {
return Y_AXIS;
}
public static Vector3 zAxis() {
return Z_AXIS;
}
public Vector3(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector3 add(Vector3 other) {
return new Vector3(x + other.x, y + other.y, z + other.z);
}
public Vector3 subtract(Vector3 other) {
return new Vector3(x - other.x, y - other.y, z - other.z);
}
public Vector3 invert() {
return new Vector3(-x, -y, -z);
}
public double dotProduct(Vector3 other) {
return x * other.x + y * other.y + z * other.z;
}
public Vector3 normalize() {
return new Vector3(x / getMagnitude(), y / getMagnitude(), z / getMagnitude());
}
public Vector3 scale(double factor) {
return new Vector3(x * factor, y * factor, z * factor);
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getZ() {
return z;
}
public double getMagnitudeSquared() {
return x * x + y * y + z * z;
}
public double getMagnitude() {
return Math.sqrt(getMagnitudeSquared());
}
public geometry_msgs.Vector3 toVector3Message(geometry_msgs.Vector3 result) {
result.setX(x);
result.setY(y);
result.setZ(z);
return result;
}
public geometry_msgs.Point toPointMessage(geometry_msgs.Point result) {
result.setX(x);
result.setY(y);
result.setZ(z);
return result;
}
public boolean almostEquals(Vector3 other, double epsilon) {
List<Double> epsilons = Lists.newArrayList();
epsilons.add(x - other.x);
epsilons.add(y - other.y);
epsilons.add(z - other.z);
for (double e : epsilons) {
if (Math.abs(e) > epsilon) {
return false;
}
}
return true;
}
@Override
public String toString() {
return String.format("Vector3<x: %.4f, y: %.4f, z: %.4f>", x, y, z);
}
@Override
public int hashCode() {
// Ensure that -0 and 0 are considered equal.
double x = this.x == 0 ? 0 : this.x;
double y = this.y == 0 ? 0 : this.y;
double z = this.z == 0 ? 0 : this.z;
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(x);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(z);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vector3 other = (Vector3) obj;
// Ensure that -0 and 0 are considered equal.
double x = this.x == 0 ? 0 : this.x;
double y = this.y == 0 ? 0 : this.y;
double z = this.z == 0 ? 0 : this.z;
double otherX = other.x == 0 ? 0 : other.x;
double otherY = other.y == 0 ? 0 : other.y;
double otherZ = other.z == 0 ? 0 : other.z;
if (Double.doubleToLongBits(x) != Double.doubleToLongBits(otherX))
return false;
if (Double.doubleToLongBits(y) != Double.doubleToLongBits(otherY))
return false;
if (Double.doubleToLongBits(z) != Double.doubleToLongBits(otherZ))
return false;
return true;
}
}
| Java |
/*
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.rosjava_geometry;
import com.google.common.annotations.VisibleForTesting;
/**
* Lazily converts a {@link geometry_msgs.Transform} message to a
* {@link Transform} on the first call to {@link #get()} and caches the result.
* <p>
* This class is thread-safe.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class LazyFrameTransform {
private final geometry_msgs.TransformStamped message;
// Avoiding constructor code duplication.
private final Object mutex = new Object();
private FrameTransform frameTransform;
public LazyFrameTransform(geometry_msgs.TransformStamped message) {
this.message = message;
}
@VisibleForTesting
LazyFrameTransform(FrameTransform frameTransform) {
message = null;
this.frameTransform = frameTransform;
}
/**
* @return the {@link FrameTransform} for the wrapped
* {@link geometry_msgs.TransformStamped} message
*/
public FrameTransform get() {
synchronized (mutex) {
if (frameTransform != null) {
return frameTransform;
}
frameTransform = FrameTransform.fromTransformStampedMessage(message);
}
return frameTransform;
}
} | 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.rosjava_geometry;
import com.google.common.annotations.VisibleForTesting;
import org.ros.message.Time;
import org.ros.namespace.GraphName;
/**
* A transformation in terms of translation, rotation, and scale.
*
* @author damonkohler@google.com (Damon Kohler)
* @author moesenle@google.com (Lorenz Moesenlechner)
*/
public class Transform {
private Vector3 translation;
private Quaternion rotationAndScale;
public static Transform fromTransformMessage(geometry_msgs.Transform message) {
return new Transform(Vector3.fromVector3Message(message.getTranslation()),
Quaternion.fromQuaternionMessage(message.getRotation()));
}
public static Transform fromPoseMessage(geometry_msgs.Pose message) {
return new Transform(Vector3.fromPointMessage(message.getPosition()),
Quaternion.fromQuaternionMessage(message.getOrientation()));
}
public static Transform identity() {
return new Transform(Vector3.zero(), Quaternion.identity());
}
public static Transform xRotation(double angle) {
return new Transform(Vector3.zero(), Quaternion.fromAxisAngle(Vector3.xAxis(), angle));
}
public static Transform yRotation(double angle) {
return new Transform(Vector3.zero(), Quaternion.fromAxisAngle(Vector3.yAxis(), angle));
}
public static Transform zRotation(double angle) {
return new Transform(Vector3.zero(), Quaternion.fromAxisAngle(Vector3.zAxis(), angle));
}
public static Transform translation(double x, double y, double z) {
return new Transform(new Vector3(x, y, z), Quaternion.identity());
}
public static Transform translation(Vector3 vector) {
return new Transform(vector, Quaternion.identity());
}
public Transform(Vector3 translation, Quaternion rotation) {
this.translation = translation;
this.rotationAndScale = rotation;
}
/**
* Apply another {@link Transform} to this {@link Transform}.
*
* @param other
* the {@link Transform} to apply to this {@link Transform}
* @return the resulting {@link Transform}
*/
public Transform multiply(Transform other) {
return new Transform(apply(other.translation), apply(other.rotationAndScale));
}
public Transform invert() {
Quaternion inverseRotationAndScale = rotationAndScale.invert();
return new Transform(inverseRotationAndScale.rotateAndScaleVector(translation.invert()),
inverseRotationAndScale);
}
public Vector3 apply(Vector3 vector) {
return rotationAndScale.rotateAndScaleVector(vector).add(translation);
}
public Quaternion apply(Quaternion quaternion) {
return rotationAndScale.multiply(quaternion);
}
public Transform scale(double factor) {
return new Transform(translation, rotationAndScale.scale(Math.sqrt(factor)));
}
public double getScale() {
return rotationAndScale.getMagnitudeSquared();
}
/**
* @see <a
* href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">Quaternion
* rotation matrix</a>
*/
public double[] toMatrix() {
double x = rotationAndScale.getX();
double y = rotationAndScale.getY();
double z = rotationAndScale.getZ();
double w = rotationAndScale.getW();
double mm = rotationAndScale.getMagnitudeSquared();
return new double[] { mm - 2 * y * y - 2 * z * z, 2 * x * y + 2 * z * w, 2 * x * z - 2 * y * w,
0, 2 * x * y - 2 * z * w, mm - 2 * x * x - 2 * z * z, 2 * y * z + 2 * x * w, 0,
2 * x * z + 2 * y * w, 2 * y * z - 2 * x * w, mm - 2 * x * x - 2 * y * y, 0,
translation.getX(), translation.getY(), translation.getZ(), 1 };
}
public geometry_msgs.Transform toTransformMessage(geometry_msgs.Transform result) {
result.setTranslation(translation.toVector3Message(result.getTranslation()));
result.setRotation(rotationAndScale.toQuaternionMessage(result.getRotation()));
return result;
}
public geometry_msgs.Pose toPoseMessage(geometry_msgs.Pose result) {
result.setPosition(translation.toPointMessage(result.getPosition()));
result.setOrientation(rotationAndScale.toQuaternionMessage(result.getOrientation()));
return result;
}
public geometry_msgs.PoseStamped toPoseStampedMessage(GraphName frame, Time stamp,
geometry_msgs.PoseStamped result) {
result.getHeader().setFrameId(frame.toString());
result.getHeader().setStamp(stamp);
result.setPose(toPoseMessage(result.getPose()));
return result;
}
public boolean almostEquals(Transform other, double epsilon) {
return translation.almostEquals(other.translation, epsilon)
&& rotationAndScale.almostEquals(other.rotationAndScale, epsilon);
}
@VisibleForTesting
Vector3 getTranslation() {
return translation;
}
@VisibleForTesting
Quaternion getRotationAndScale() {
return rotationAndScale;
}
@Override
public String toString() {
return String.format("Transform<%s, %s>", translation, rotationAndScale);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((rotationAndScale == null) ? 0 : rotationAndScale.hashCode());
result = prime * result + ((translation == null) ? 0 : translation.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;
Transform other = (Transform) obj;
if (rotationAndScale == null) {
if (other.rotationAndScale != null)
return false;
} else if (!rotationAndScale.equals(other.rotationAndScale))
return false;
if (translation == null) {
if (other.translation != null)
return false;
} else if (!translation.equals(other.translation))
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.rosjava_geometry;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import geometry_msgs.TransformStamped;
import org.ros.concurrent.CircularBlockingDeque;
import org.ros.message.Time;
import org.ros.namespace.GraphName;
import org.ros.namespace.NameResolver;
import java.util.Map;
/**
* A tree of {@link FrameTransform}s.
* <p>
* {@link FrameTransformTree} does not currently support time travel. Lookups
* always use the newest {@link TransformStamped}.
*
* @author damonkohler@google.com (Damon Kohler)
* @author moesenle@google.com (Lorenz Moesenlechner)
*/
public class FrameTransformTree {
private static final int TRANSFORM_QUEUE_CAPACITY = 16;
private final NameResolver nameResolver;
private final Object mutex;
/**
* A {@link Map} of the most recent {@link LazyFrameTransform} by source
* frame. Lookups by target frame or by the pair of source and target are both
* unnecessary because every frame can only have exactly one target.
*/
private final Map<GraphName, CircularBlockingDeque<LazyFrameTransform>> transforms;
public FrameTransformTree(NameResolver nameResolver) {
Preconditions.checkNotNull(nameResolver);
this.nameResolver = nameResolver;
mutex = new Object();
transforms = Maps.newConcurrentMap();
}
/**
* Updates the tree with the provided {@link geometry_msgs.TransformStamped}
* message.
* <p>
* Note that the tree is updated lazily. Modifications to the provided
* {@link geometry_msgs.TransformStamped} message may cause unpredictable
* results.
*
* @param transformStamped
* the {@link geometry_msgs.TransformStamped} message to update with
*/
public void update(geometry_msgs.TransformStamped transformStamped) {
Preconditions.checkNotNull(transformStamped);
GraphName resolvedSource = nameResolver.resolve(transformStamped.getChildFrameId());
LazyFrameTransform lazyFrameTransform = new LazyFrameTransform(transformStamped);
add(resolvedSource, lazyFrameTransform);
}
@VisibleForTesting
void update(FrameTransform frameTransform) {
Preconditions.checkNotNull(frameTransform);
GraphName resolvedSource = frameTransform.getSourceFrame();
LazyFrameTransform lazyFrameTransform = new LazyFrameTransform(frameTransform);
add(resolvedSource, lazyFrameTransform);
}
private void add(GraphName resolvedSource, LazyFrameTransform lazyFrameTransform) {
if (!transforms.containsKey(resolvedSource)) {
transforms.put(resolvedSource, new CircularBlockingDeque<LazyFrameTransform>(
TRANSFORM_QUEUE_CAPACITY));
}
synchronized (mutex) {
transforms.get(resolvedSource).addFirst(lazyFrameTransform);
}
}
/**
* Returns the most recent {@link FrameTransform} for target {@code source}.
*
* @param source
* the frame to look up
* @return the most recent {@link FrameTransform} for {@code source} or
* {@code null} if no transform for {@code source} is available
*/
public FrameTransform lookUp(GraphName source) {
Preconditions.checkNotNull(source);
GraphName resolvedSource = nameResolver.resolve(source);
return getLatest(resolvedSource);
}
private FrameTransform getLatest(GraphName resolvedSource) {
CircularBlockingDeque<LazyFrameTransform> deque = transforms.get(resolvedSource);
if (deque == null) {
return null;
}
LazyFrameTransform lazyFrameTransform = deque.peekFirst();
if (lazyFrameTransform == null) {
return null;
}
return lazyFrameTransform.get();
}
/**
* @see #lookUp(GraphName)
*/
public FrameTransform get(String source) {
Preconditions.checkNotNull(source);
return lookUp(GraphName.of(source));
}
/**
* Returns the {@link FrameTransform} for {@code source} closest to
* {@code time}.
*
* @param source
* the frame to look up
* @param time
* the transform for {@code frame} closest to this {@link Time} will
* be returned
* @return the most recent {@link FrameTransform} for {@code source} or
* {@code null} if no transform for {@code source} is available
*/
public FrameTransform lookUp(GraphName source, Time time) {
Preconditions.checkNotNull(source);
Preconditions.checkNotNull(time);
GraphName resolvedSource = nameResolver.resolve(source);
return get(resolvedSource, time);
}
// TODO(damonkohler): Use an efficient search.
private FrameTransform get(GraphName resolvedSource, Time time) {
CircularBlockingDeque<LazyFrameTransform> deque = transforms.get(resolvedSource);
if (deque == null) {
return null;
}
LazyFrameTransform result = null;
synchronized (mutex) {
long offset = 0;
for (LazyFrameTransform lazyFrameTransform : deque) {
if (result == null) {
result = lazyFrameTransform;
offset = Math.abs(time.subtract(result.get().getTime()).totalNsecs());
continue;
}
long newOffset = Math.abs(time.subtract(lazyFrameTransform.get().getTime()).totalNsecs());
if (newOffset < offset) {
result = lazyFrameTransform;
offset = newOffset;
}
}
}
if (result == null) {
return null;
}
return result.get();
}
/**
* @see #lookUp(GraphName, Time)
*/
public FrameTransform get(String source, Time time) {
Preconditions.checkNotNull(source);
return lookUp(GraphName.of(source), time);
}
/**
* @return the {@link FrameTransform} from source the frame to the target
* frame, or {@code null} if no {@link FrameTransform} could be found
*/
public FrameTransform transform(GraphName source, GraphName target) {
Preconditions.checkNotNull(source);
Preconditions.checkNotNull(target);
GraphName resolvedSource = nameResolver.resolve(source);
GraphName resolvedTarget = nameResolver.resolve(target);
if (resolvedSource.equals(resolvedTarget)) {
return new FrameTransform(Transform.identity(), resolvedSource, resolvedTarget, null);
}
FrameTransform sourceToRoot = transformToRoot(resolvedSource);
FrameTransform targetToRoot = transformToRoot(resolvedTarget);
if (sourceToRoot == null && targetToRoot == null) {
return null;
}
if (sourceToRoot == null) {
if (targetToRoot.getTargetFrame().equals(resolvedSource)) {
// resolvedSource is root.
return targetToRoot.invert();
} else {
return null;
}
}
if (targetToRoot == null) {
if (sourceToRoot.getTargetFrame().equals(resolvedTarget)) {
// resolvedTarget is root.
return sourceToRoot;
} else {
return null;
}
}
if (sourceToRoot.getTargetFrame().equals(targetToRoot.getTargetFrame())) {
// Neither resolvedSource nor resolvedTarget is root and both share the
// same root.
Transform transform =
targetToRoot.getTransform().invert().multiply(sourceToRoot.getTransform());
return new FrameTransform(transform, resolvedSource, resolvedTarget, sourceToRoot.getTime());
}
// No known transform.
return null;
}
/**
* @see #transform(GraphName, GraphName)
*/
public FrameTransform transform(String source, String target) {
Preconditions.checkNotNull(source);
Preconditions.checkNotNull(target);
return transform(GraphName.of(source), GraphName.of(target));
}
/**
* @param resolvedSource
* the resolved source frame
* @return the {@link Transform} from {@code source} to root
*/
@VisibleForTesting
FrameTransform transformToRoot(GraphName resolvedSource) {
FrameTransform result = getLatest(resolvedSource);
if (result == null) {
return null;
}
while (true) {
FrameTransform resultToParent = lookUp(result.getTargetFrame(), result.getTime());
if (resultToParent == null) {
return result;
}
// Now resultToParent.getSourceFrame() == result.getTargetFrame()
Transform transform = resultToParent.getTransform().multiply(result.getTransform());
GraphName resolvedTarget = resultToParent.getTargetFrame();
result = new FrameTransform(transform, resolvedSource, resolvedTarget, result.getTime());
}
}
}
| 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.rosjava_geometry;
import com.google.common.base.Preconditions;
import org.ros.message.Time;
import org.ros.namespace.GraphName;
/**
* Describes a {@link Transform} from data in the source frame to data in the
* target frame at a specified {@link Time}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class FrameTransform {
private final Transform transform;
private final GraphName source;
private final GraphName target;
private final Time time;
public static FrameTransform fromTransformStampedMessage(
geometry_msgs.TransformStamped transformStamped) {
Transform transform = Transform.fromTransformMessage(transformStamped.getTransform());
String target = transformStamped.getHeader().getFrameId();
String source = transformStamped.getChildFrameId();
Time stamp = transformStamped.getHeader().getStamp();
return new FrameTransform(transform, GraphName.of(source), GraphName.of(target), stamp);
}
/**
* Allocates a new {@link FrameTransform}.
*
* @param transform
* the {@link Transform} that transforms data in the {@code source}
* frame to data in the {@code target} frame
* @param source
* the source frame
* @param target
* the target frame
* @param time
* the time associated with this {@link FrameTransform}, can be
* {@null}
*/
public FrameTransform(Transform transform, GraphName source, GraphName target, Time time) {
Preconditions.checkNotNull(transform);
Preconditions.checkNotNull(source);
Preconditions.checkNotNull(target);
this.transform = transform;
this.source = source;
this.target = target;
this.time = time;
}
public Transform getTransform() {
return transform;
}
public GraphName getSourceFrame() {
return source;
}
public GraphName getTargetFrame() {
return target;
}
public FrameTransform invert() {
return new FrameTransform(transform.invert(), target, source, time);
}
/**
* @return the time associated with the {@link FrameTransform} or {@code null}
* if there is no associated time
*/
public Time getTime() {
return time;
}
public geometry_msgs.TransformStamped toTransformStampedMessage(
geometry_msgs.TransformStamped result) {
Preconditions.checkNotNull(time);
result.getHeader().setFrameId(target.toString());
result.getHeader().setStamp(time);
result.setChildFrameId(source.toString());
transform.toTransformMessage(result.getTransform());
return result;
}
@Override
public String toString() {
return String.format("FrameTransform<Source: %s, Target: %s, %s, Time: %s>", source, target,
transform, time);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((source == null) ? 0 : source.hashCode());
result = prime * result + ((target == null) ? 0 : target.hashCode());
result = prime * result + ((time == null) ? 0 : time.hashCode());
result = prime * result + ((transform == null) ? 0 : transform.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;
FrameTransform other = (FrameTransform) obj;
if (source == null) {
if (other.source != null)
return false;
} else if (!source.equals(other.source))
return false;
if (target == null) {
if (other.target != null)
return false;
} else if (!target.equals(other.target))
return false;
if (time == null) {
if (other.time != null)
return false;
} else if (!time.equals(other.time))
return false;
if (transform == null) {
if (other.transform != null)
return false;
} else if (!transform.equals(other.transform))
return false;
return true;
}
}
| 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.metadata;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcHandler;
import org.apache.xmlrpc.server.AbstractReflectiveHandlerMapping;
/** A metadata handler is able to provide metadata about
* itself, as specified
* <a href="http://scripts.incutio.com/xmlrpc/introspection.html">
* here</a>.<br>
*
* @see <a href="http://scripts.incutio.com/xmlrpc/introspection.html">
* Specification of XML-RPC introspection</a>
*/
public interface XmlRpcMetaDataHandler extends XmlRpcHandler {
/** <p>This method may be used to implement
* {@link XmlRpcListableHandlerMapping#getMethodSignature(String)}.
* Typically, the handler mapping will pick up the
* matching handler, invoke its method
* {@link #getSignatures()}, and return the result.</p>
* <p>Method handlers, which are created by the
* {@link AbstractReflectiveHandlerMapping}, will typically
* return a single signature only.</p>
* @return An array of arrays. Any element in the outer
* array is a signature. The elements in the inner array
* are being concatenated with commas. The inner arrays
* first element is the return type, followed by the
* parameter types.
*/
String[][] getSignatures() throws XmlRpcException;
/** <p>This method may be used to implement
* {@link XmlRpcListableHandlerMapping#getMethodHelp(String)}.
* Typically, the handler mapping will pick up the
* matching handler, invoke its method
* {@link #getMethodHelp()}, and return the result.</p>
*/
String getMethodHelp() throws XmlRpcException;
}
| 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.metadata;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.xmlrpc.XmlRpcException;
import org.w3c.dom.Node;
/** Utility class, which provides services to meta data
* handlers and handler mappings.
*/
public class Util {
/** This field should solve the problem, that we do not
* want to depend on the presence of JAXB. However, if
* it is available, we want to support it.
*/
private static final Class jaxbElementClass;
static {
Class c;
try {
c = Class.forName("javax.xml.bind.Element");
} catch (ClassNotFoundException e) {
c = null;
}
jaxbElementClass = c;
}
/** Returns a signature for the given return type or
* parameter class.
* @param pType The class for which a signature is being
* queried.
* @return Signature, if known, or null.
*/
public static String getSignatureType(Class pType) {
if (pType == Integer.TYPE || pType == Integer.class)
return "int";
if (pType == Double.TYPE || pType == Double.class)
return "double";
if (pType == Boolean.TYPE || pType == Boolean.class)
return "boolean";
if (pType == String.class)
return "string";
if (Object[].class.isAssignableFrom(pType)
|| List.class.isAssignableFrom(pType))
return "array";
if (Map.class.isAssignableFrom(pType))
return "struct";
if (Date.class.isAssignableFrom(pType)
|| Calendar.class.isAssignableFrom(pType))
return "dateTime.iso8601";
if (pType == byte[].class)
return "base64";
// extension types
if (pType == void.class)
return "ex:nil";
if (pType == Byte.TYPE || pType == Byte.class)
return "ex:i1";
if (pType == Short.TYPE || pType == Short.class)
return "ex:i2";
if (pType == Long.TYPE || pType == Long.class)
return "ex:i8";
if (pType == Float.TYPE || pType == Float.class)
return "ex:float";
if (Node.class.isAssignableFrom(pType))
return "ex:node";
if (jaxbElementClass != null
&& jaxbElementClass.isAssignableFrom(pType)) {
return "ex:jaxbElement";
}
if (Serializable.class.isAssignableFrom(pType))
return "base64";
// give up
return null;
}
/** Returns a signature for the given methods.
* @param pMethods Methods, for which a signature is
* being queried.
* @return Signature string, or null, if no signature
* is available.
*/
public static String[][] getSignature(Method[] pMethods) {
final List result = new ArrayList();
for (int i = 0; i < pMethods.length; i++) {
String[] sig = getSignature(pMethods[i]);
if (sig != null) {
result.add(sig);
}
}
return (String[][]) result.toArray(new String[result.size()][]);
}
/** Returns a signature for the given methods.
* @param pMethod Method, for which a signature is
* being queried.
* @return Signature string, or null, if no signature
* is available.
*/
public static String[] getSignature(Method pMethod) {
Class[] paramClasses = pMethod.getParameterTypes();
String[] sig = new String[paramClasses.length + 1];
String s = getSignatureType(pMethod.getReturnType());
if (s == null) {
return null;
}
sig[0] = s;
for (int i = 0; i < paramClasses.length; i++) {
s = getSignatureType(paramClasses[i]);
if (s == null) {
return null;
}
sig[i+1] = s;
}
return sig;
}
/** Returns a help string for the given method, which
* is applied to the given class.
*/
public static String getMethodHelp(Class pClass, Method[] pMethods) {
final List result = new ArrayList();
for (int i = 0; i < pMethods.length; i++) {
String help = getMethodHelp(pClass, pMethods[i]);
if (help != null) {
result.add(help);
}
}
switch (result.size()) {
case 0:
return null;
case 1:
return (String) result.get(0);
default:
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.size(); i++) {
sb.append(i+1);
sb.append(": ");
sb.append(result.get(i));
sb.append("\n");
}
return sb.toString();
}
}
/** Returns a help string for the given method, which
* is applied to the given class.
*/
public static String getMethodHelp(Class pClass, Method pMethod) {
StringBuffer sb = new StringBuffer();
sb.append("Invokes the method ");
sb.append(pClass.getName());
sb.append(".");
sb.append(pMethod.getName());
sb.append("(");
Class[] paramClasses = pMethod.getParameterTypes();
for (int i = 0; i < paramClasses.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(paramClasses[i].getName());
}
sb.append(").");
return sb.toString();
}
/** Returns a signature for the given parameter set. This is used
* in error messages.
*/
public static String getSignature(Object[] args) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < args.length; i++) {
if (i > 0) {
sb.append(", ");
}
if (args[i] == null) {
sb.append("null");
} else {
sb.append(args[i].getClass().getName());
}
}
return sb.toString();
}
/**
* Creates a new instance of <code>pClass</code>.
*/
public static Object newInstance(Class pClass) throws XmlRpcException {
try {
return pClass.newInstance();
} catch (InstantiationException e) {
throw new XmlRpcException("Failed to instantiate class " + pClass.getName(), e);
} catch (IllegalAccessException e) {
throw new XmlRpcException("Illegal access when instantiating class " + pClass.getName(), e);
}
}
}
| 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.metadata;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.server.PropertyHandlerMapping;
import org.apache.xmlrpc.server.RequestProcessorFactoryFactory;
/** This class implements the various "system" calls,
* as specifies by {@link XmlRpcListableHandlerMapping}.
* Suggested use is to create an instance and add it to
* the handler mapping with the "system" prefix.
*/
public class XmlRpcSystemImpl {
private XmlRpcListableHandlerMapping mapping;
/** Creates a new instance, which provides meta data
* for the given handler mappings methods.
*/
public XmlRpcSystemImpl(XmlRpcListableHandlerMapping pMapping) {
mapping = pMapping;
}
/** Implements the "system.methodSignature" call.
* @see XmlRpcListableHandlerMapping#getMethodSignature(String)
*/
public String[][] methodSignature(String methodName) throws XmlRpcException {
return mapping.getMethodSignature(methodName);
}
/** Implements the "system.methodHelp" call.
* @see XmlRpcListableHandlerMapping#getMethodHelp(String)
*/
public String methodHelp(String methodName) throws XmlRpcException {
return mapping.getMethodHelp(methodName);
}
/** Implements the "system.listMethods" call.
* @see XmlRpcListableHandlerMapping#getListMethods()
*/
public String[] listMethods() throws XmlRpcException {
return mapping.getListMethods();
}
/**
* Adds an instance of this class to the given handler
* mapping.
*/
public static void addSystemHandler(final PropertyHandlerMapping pMapping)
throws XmlRpcException {
final RequestProcessorFactoryFactory factory = pMapping.getRequestProcessorFactoryFactory();
final XmlRpcSystemImpl systemHandler = new XmlRpcSystemImpl(pMapping);
pMapping.setRequestProcessorFactoryFactory(new RequestProcessorFactoryFactory(){
public RequestProcessorFactory getRequestProcessorFactory(Class pClass)
throws XmlRpcException {
if (XmlRpcSystemImpl.class.equals(pClass)) {
return new RequestProcessorFactory(){
public Object getRequestProcessor(XmlRpcRequest request)
throws XmlRpcException {
return systemHandler;
}
};
} else {
return factory.getRequestProcessorFactory(pClass);
}
}
});
pMapping.addHandler("system", XmlRpcSystemImpl.class);
}
}
| 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.metadata;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcHandler;
import org.apache.xmlrpc.server.XmlRpcHandlerMapping;
/** A listable handler mapping is able to provide support for
* XML-RPC meta data, as specified
* <a href="http://scripts.incutio.com/xmlrpc/introspection.html">
* here</a>.<br>
*
* @see <a href="http://scripts.incutio.com/xmlrpc/introspection.html">
* Specification of XML-RPC introspection</a>
*/
public interface XmlRpcListableHandlerMapping extends XmlRpcHandlerMapping {
/** This method implements the introspection method
* <code>system.listMethods</code>, which is specified
* as follows:
* <cite>
* <p>This method may be used to enumerate the methods implemented
* by the XML-RPC server.</p>
* <p>The <code>system.listMethods</code> method requires no
* parameters. It returns an array of strings, each of which is
* the name of a method implemented by the server.
* </cite>
* <p>Note, that the specification doesn't require that the list
* must be exhaustive. We conclude, that a valid method
* "handlerName" doesn't need to be in the list. For example,
* a handler, which implements {@link XmlRpcHandler}, but not
* {@link XmlRpcMetaDataHandler}, should possibly excluded:
* Otherwise, the listable handler mapping could not provide
* meaningful replies to <code>system.methodSignature</code>,
* and <code>system.methodHelp</code>.
*
* @throws XmlRpcException An internal error occurred.
*/
String[] getListMethods() throws XmlRpcException;
/** This method implements the introspection method
* <code>system.methodSignature</code>, which is specified
* as follows:
* <cite>
* <p>This method takes one parameter, the name of a method
* implemented by the XML-RPC server. It returns an array
* of possible signatures for this method. A signature is
* an array of types. The first of these types is the return
* type of the method, the rest are parameters.</p>
* <p>Multiple signatures (ie. overloading) are permitted:
* this is the reason that an array of signatures are returned
* by this method.</p>
* <p>Signatures themselves are restricted to the top level
* parameters expected by a method. For instance if a method
* expects one array of structs as a parameter, and it returns
* a string, its signature is simply "string, array". If it
* expects three integers, its signature is
* "string, int, int, int".</p>
* <p>If no signature is defined for the method, a none-array
* value is returned. Therefore this is the way to test for a
* non-signature, if $resp below is the response object from
* a method call to system.methodSignature:
* <pre>
* $v=$resp->value();
* if ($v->kindOf()!="array") {
* // then the method did not have a signature defined
* }
* </pre>
* See the introspect.php demo included in this distribution
* for an example of using this method.</p>
* </cite>
* @see XmlRpcMetaDataHandler#getSignatures()
*/
String[][] getMethodSignature(String pHandlerName) throws XmlRpcException;
/** This method implements the introspection method
* <code>system.methodSignature</code>, which is specified
* as follows:
* <cite>
* <p>This method takes one parameter, the name of a
* method implemented by the XML-RPC server. It
* returns a documentation string describing the
* use of that method. If no such string is available,
* an empty string is returned.</p>
* <p>The documentation string may contain HTML markup.</p>
* </cite>
*/
String getMethodHelp(String pHandlerName) throws XmlRpcException;
}
| 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.metadata;
import java.lang.reflect.Method;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.common.TypeConverterFactory;
import org.apache.xmlrpc.server.AbstractReflectiveHandlerMapping;
import org.apache.xmlrpc.server.ReflectiveXmlRpcHandler;
import org.apache.xmlrpc.server.RequestProcessorFactoryFactory.RequestProcessorFactory;
/** Default implementation of {@link XmlRpcMetaDataHandler}.
*/
public class ReflectiveXmlRpcMetaDataHandler extends ReflectiveXmlRpcHandler
implements XmlRpcMetaDataHandler {
private final String[][] signatures;
private final String methodHelp;
/** Creates a new instance.
* @param pMapping The mapping, which creates this handler.
* @param pClass The class, which has been inspected to create
* this handler. Typically, this will be the same as
* <pre>pInstance.getClass()</pre>. It is used for diagnostic
* messages only.
* @param pMethods The method, which will be invoked for
* executing the handler.
* @param pSignatures The signature, which will be returned by
* {@link #getSignatures()}.
* @param pMethodHelp The help string, which will be returned
* by {@link #getMethodHelp()}.
*/
public ReflectiveXmlRpcMetaDataHandler(AbstractReflectiveHandlerMapping pMapping,
TypeConverterFactory pTypeConverterFactory,
Class pClass, RequestProcessorFactory pFactory, Method[] pMethods,
String[][] pSignatures, String pMethodHelp) {
super(pMapping, pTypeConverterFactory, pClass, pFactory, pMethods);
signatures = pSignatures;
methodHelp = pMethodHelp;
}
public String[][] getSignatures() throws XmlRpcException {
return signatures;
}
public String getMethodHelp() throws XmlRpcException {
return methodHelp;
}
}
| 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.server;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcHandler;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.common.TypeConverterFactory;
import org.apache.xmlrpc.common.TypeConverterFactoryImpl;
import org.apache.xmlrpc.metadata.ReflectiveXmlRpcMetaDataHandler;
import org.apache.xmlrpc.metadata.Util;
import org.apache.xmlrpc.metadata.XmlRpcListableHandlerMapping;
import org.apache.xmlrpc.metadata.XmlRpcMetaDataHandler;
import org.apache.xmlrpc.server.RequestProcessorFactoryFactory.RequestProcessorFactory;
/** Abstract base class of handler mappings, which are
* using reflection.
*/
public abstract class AbstractReflectiveHandlerMapping
implements XmlRpcListableHandlerMapping {
/** An object implementing this interface may be used
* to validate user names and passwords.
*/
public interface AuthenticationHandler {
/** Returns, whether the user is authenticated and
* authorized to perform the request.
*/
boolean isAuthorized(XmlRpcRequest pRequest)
throws XmlRpcException;
}
private TypeConverterFactory typeConverterFactory = new TypeConverterFactoryImpl();
protected Map handlerMap = new HashMap();
private AuthenticationHandler authenticationHandler;
private RequestProcessorFactoryFactory requestProcessorFactoryFactory = new RequestProcessorFactoryFactory.RequestSpecificProcessorFactoryFactory();
private boolean voidMethodEnabled;
/**
* Sets the mappings {@link TypeConverterFactory}.
*/
public void setTypeConverterFactory(TypeConverterFactory pFactory) {
typeConverterFactory = pFactory;
}
/**
* Returns the mappings {@link TypeConverterFactory}.
*/
public TypeConverterFactory getTypeConverterFactory() {
return typeConverterFactory;
}
/** Sets the mappings {@link RequestProcessorFactoryFactory}. Note, that this doesn't
* affect already registered handlers.
*/
public void setRequestProcessorFactoryFactory(RequestProcessorFactoryFactory pFactory) {
requestProcessorFactoryFactory = pFactory;
}
/** Returns the mappings {@link RequestProcessorFactoryFactory}.
*/
public RequestProcessorFactoryFactory getRequestProcessorFactoryFactory() {
return requestProcessorFactoryFactory;
}
/** Returns the authentication handler, if any, or null.
*/
public AuthenticationHandler getAuthenticationHandler() {
return authenticationHandler;
}
/** Sets the authentication handler, if any, or null.
*/
public void setAuthenticationHandler(AuthenticationHandler pAuthenticationHandler) {
authenticationHandler = pAuthenticationHandler;
}
protected boolean isHandlerMethod(Method pMethod) {
if (!Modifier.isPublic(pMethod.getModifiers())) {
return false; // Ignore methods, which aren't public
}
if (Modifier.isStatic(pMethod.getModifiers())) {
return false; // Ignore methods, which are static
}
if (!isVoidMethodEnabled() && pMethod.getReturnType() == void.class) {
return false; // Ignore void methods.
}
if (pMethod.getDeclaringClass() == Object.class) {
return false; // Ignore methods from Object.class
}
return true;
}
/** Searches for methods in the given class. For any valid
* method, it creates an instance of {@link XmlRpcHandler}.
* Valid methods are defined as follows:
* <ul>
* <li>They must be public.</li>
* <li>They must not be static.</li>
* <li>The return type must not be void.</li>
* <li>The declaring class must not be
* {@link java.lang.Object}.</li>
* <li>If multiple methods with the same name exist,
* which meet the above conditins, then an attempt is
* made to identify a method with a matching signature.
* If such a method is found, then this method is
* invoked. If multiple such methods are found, then
* the first one is choosen. (This may be the case,
* for example, if there are methods with a similar
* signature, but varying subclasses.) Note, that
* there is no concept of the "most matching" method.
* If no matching method is found at all, then an
* exception is thrown.</li>
* </ul>
* @param pKey Suffix for building handler names. A dot and
* the method name are being added.
* @param pType The class being inspected.
*/
protected void registerPublicMethods(String pKey,
Class pType) throws XmlRpcException {
Map map = new HashMap();
Method[] methods = pType.getMethods();
for (int i = 0; i < methods.length; i++) {
final Method method = methods[i];
if (!isHandlerMethod(method)) {
continue;
}
String name = (pKey.length() > 0 ? pKey + "." : "") + method.getName();
Method[] mArray;
Method[] oldMArray = (Method[]) map.get(name);
if (oldMArray == null) {
mArray = new Method[]{method};
} else {
mArray = new Method[oldMArray.length+1];
System.arraycopy(oldMArray, 0, mArray, 0, oldMArray.length);
mArray[oldMArray.length] = method;
}
map.put(name, mArray);
}
for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
String name = (String) entry.getKey();
Method[] mArray = (Method[]) entry.getValue();
handlerMap.put(name, newXmlRpcHandler(pType, mArray));
}
}
/** Creates a new instance of {@link XmlRpcHandler}.
* @param pClass The class, which was inspected for handler
* methods. This is used for error messages only. Typically,
* it is the same than <pre>pInstance.getClass()</pre>.
* @param pMethods The method being invoked.
*/
protected XmlRpcHandler newXmlRpcHandler(final Class pClass,
final Method[] pMethods) throws XmlRpcException {
String[][] sig = getSignature(pMethods);
String help = getMethodHelp(pClass, pMethods);
RequestProcessorFactory factory = requestProcessorFactoryFactory.getRequestProcessorFactory(pClass);
if (sig == null || help == null) {
return new ReflectiveXmlRpcHandler(this, typeConverterFactory,
pClass, factory, pMethods);
}
return new ReflectiveXmlRpcMetaDataHandler(this, typeConverterFactory,
pClass, factory, pMethods, sig, help);
}
/** Creates a signature for the given method.
*/
protected String[][] getSignature(Method[] pMethods) {
return Util.getSignature(pMethods);
}
/** Creates a help string for the given method, when applied
* to the given class.
*/
protected String getMethodHelp(Class pClass, Method[] pMethods) {
return Util.getMethodHelp(pClass, pMethods);
}
/** Returns the {@link XmlRpcHandler} with the given name.
* @param pHandlerName The handlers name
* @throws XmlRpcNoSuchHandlerException A handler with the given
* name is unknown.
*/
public XmlRpcHandler getHandler(String pHandlerName)
throws XmlRpcNoSuchHandlerException, XmlRpcException {
XmlRpcHandler result = (XmlRpcHandler) handlerMap.get(pHandlerName);
if (result == null) {
throw new XmlRpcNoSuchHandlerException("No such handler: " + pHandlerName);
}
return result;
}
public String[] getListMethods() throws XmlRpcException {
List list = new ArrayList();
for (Iterator iter = handlerMap.entrySet().iterator();
iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
if (entry.getValue() instanceof XmlRpcMetaDataHandler) {
list.add(entry.getKey());
}
}
return (String[]) list.toArray(new String[list.size()]);
}
public String getMethodHelp(String pHandlerName) throws XmlRpcException {
XmlRpcHandler h = getHandler(pHandlerName);
if (h instanceof XmlRpcMetaDataHandler)
return ((XmlRpcMetaDataHandler)h).getMethodHelp();
throw new XmlRpcNoSuchHandlerException("No help available for method: "
+ pHandlerName);
}
public String[][] getMethodSignature(String pHandlerName) throws XmlRpcException {
XmlRpcHandler h = getHandler(pHandlerName);
if (h instanceof XmlRpcMetaDataHandler)
return ((XmlRpcMetaDataHandler)h).getSignatures();
throw new XmlRpcNoSuchHandlerException("No metadata available for method: "
+ pHandlerName);
}
/**
* Returns, whether void methods are enabled. By default, null values
* aren't supported by XML-RPC and void methods are in fact returning
* null (at least from the perspective of reflection).
*/
public boolean isVoidMethodEnabled() {
return voidMethodEnabled;
}
/**
* Sets, whether void methods are enabled. By default, null values
* aren't supported by XML-RPC and void methods are in fact returning
* null (at least from the perspective of reflection).
*/
public void setVoidMethodEnabled(boolean pVoidMethodEnabled) {
voidMethodEnabled = pVoidMethodEnabled;
}
}
| 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.server;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcHandler;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.common.TypeConverter;
import org.apache.xmlrpc.common.TypeConverterFactory;
import org.apache.xmlrpc.common.XmlRpcInvocationException;
import org.apache.xmlrpc.common.XmlRpcNotAuthorizedException;
import org.apache.xmlrpc.metadata.Util;
import org.apache.xmlrpc.server.AbstractReflectiveHandlerMapping.AuthenticationHandler;
import org.apache.xmlrpc.server.RequestProcessorFactoryFactory.RequestProcessorFactory;
/** Default implementation of {@link XmlRpcHandler}.
*/
public class ReflectiveXmlRpcHandler implements XmlRpcHandler {
private static class MethodData {
final Method method;
final TypeConverter[] typeConverters;
MethodData(Method pMethod, TypeConverterFactory pTypeConverterFactory) {
method = pMethod;
Class[] paramClasses = method.getParameterTypes();
typeConverters = new TypeConverter[paramClasses.length];
for (int i = 0; i < paramClasses.length; i++) {
typeConverters[i] = pTypeConverterFactory.getTypeConverter(paramClasses[i]);
}
}
}
private final AbstractReflectiveHandlerMapping mapping;
private final MethodData[] methods;
private final Class clazz;
private final RequestProcessorFactory requestProcessorFactory;
/** Creates a new instance.
* @param pMapping The mapping, which creates this handler.
* @param pClass The class, which has been inspected to create
* this handler. Typically, this will be the same as
* <pre>pInstance.getClass()</pre>. It is used for diagnostic
* messages only.
* @param pMethods The method, which will be invoked for
* executing the handler.
*/
public ReflectiveXmlRpcHandler(AbstractReflectiveHandlerMapping pMapping,
TypeConverterFactory pTypeConverterFactory,
Class pClass, RequestProcessorFactory pFactory, Method[] pMethods) {
mapping = pMapping;
clazz = pClass;
methods = new MethodData[pMethods.length];
requestProcessorFactory = pFactory;
for (int i = 0; i < methods.length; i++) {
methods[i] = new MethodData(pMethods[i], pTypeConverterFactory);
}
}
private Object getInstance(XmlRpcRequest pRequest) throws XmlRpcException {
return requestProcessorFactory.getRequestProcessor(pRequest);
}
public Object execute(XmlRpcRequest pRequest) throws XmlRpcException {
AuthenticationHandler authHandler = mapping.getAuthenticationHandler();
if (authHandler != null && !authHandler.isAuthorized(pRequest)) {
throw new XmlRpcNotAuthorizedException("Not authorized");
}
Object[] args = new Object[pRequest.getParameterCount()];
for (int j = 0; j < args.length; j++) {
args[j] = pRequest.getParameter(j);
}
Object instance = getInstance(pRequest);
for (int i = 0; i < methods.length; i++) {
MethodData methodData = methods[i];
TypeConverter[] converters = methodData.typeConverters;
if (args.length == converters.length) {
boolean matching = true;
for (int j = 0; j < args.length; j++) {
if (!converters[j].isConvertable(args[j])) {
matching = false;
break;
}
}
if (matching) {
for (int j = 0; j < args.length; j++) {
args[j] = converters[j].convert(args[j]);
}
return invoke(instance, methodData.method, args);
}
}
}
throw new XmlRpcException("No method " + pRequest.getMethodName() + " matching arguments: " + Util.getSignature(args));
}
private Object invoke(Object pInstance, Method pMethod, Object[] pArgs) throws XmlRpcException {
try {
return pMethod.invoke(pInstance, pArgs);
} catch (IllegalAccessException e) {
throw new XmlRpcException("Illegal access to method "
+ pMethod.getName() + " in class "
+ clazz.getName(), e);
} catch (IllegalArgumentException e) {
throw new XmlRpcException("Illegal argument for method "
+ pMethod.getName() + " in class "
+ clazz.getName(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof XmlRpcException) {
throw (XmlRpcException) t;
}
throw new XmlRpcInvocationException("Failed to invoke method "
+ pMethod.getName() + " in class "
+ clazz.getName() + ": "
+ t.getMessage(), t);
}
}
}
| 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.server;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.xmlrpc.XmlRpcException;
/**
* A handler mapping based on a property file. The property file
* contains a set of properties. The property key is taken as the
* handler name. The property value is taken as the name of a
* class being instantiated. For any non-void, non-static, and
* public method in the class, an entry in the handler map is
* generated. A typical use would be, to specify interface names
* as the property keys and implementations as the values.
*/
public class PropertyHandlerMapping extends AbstractReflectiveHandlerMapping {
/**
* Reads handler definitions from a resource file.
* @param pClassLoader The class loader being used to load
* handler classes.
* @param pResource The resource being used, for example
* "org/apache/xmlrpc/webserver/XmlRpcServlet.properties"
* @throws IOException Loading the property file failed.
* @throws XmlRpcException Initializing the handlers failed.
*/
public void load(ClassLoader pClassLoader, String pResource)
throws IOException, XmlRpcException {
URL url = pClassLoader.getResource(pResource);
if (url == null) {
throw new IOException("Unable to locate resource " + pResource);
}
load(pClassLoader, url);
}
/**
* Reads handler definitions from a property file.
* @param pClassLoader The class loader being used to load
* handler classes.
* @param pURL The URL from which to load the property file
* @throws IOException Loading the property file failed.
* @throws XmlRpcException Initializing the handlers failed.
*/
public void load(ClassLoader pClassLoader, URL pURL) throws IOException, XmlRpcException {
Properties props = new Properties();
props.load(pURL.openStream());
load(pClassLoader, props);
}
/**
* Reads handler definitions from an existing Map.
* @param pClassLoader The class loader being used to load
* handler classes.
* @param pMap The existing Map to read from
* @throws XmlRpcException Initializing the handlers failed.
*/
public void load(ClassLoader pClassLoader, Map pMap) throws XmlRpcException {
for (Iterator iter = pMap.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
Class c = newHandlerClass(pClassLoader, value);
registerPublicMethods(key, c);
}
}
protected Class newHandlerClass(ClassLoader pClassLoader, String pClassName)
throws XmlRpcException {
final Class c;
try {
c = pClassLoader.loadClass(pClassName);
} catch (ClassNotFoundException e) {
throw new XmlRpcException("Unable to load class: " + pClassName, e);
}
if (c == null) {
throw new XmlRpcException(0, "Loading class " + pClassName + " returned null.");
}
return c;
}
/** Adds handlers for the given object to the mapping.
* The handlers are build by invoking
* {@link #registerPublicMethods(String, Class)}.
* @param pKey The class key, which is passed
* to {@link #registerPublicMethods(String, Class)}.
* @param pClass Class, which is responsible for handling the request.
*/
public void addHandler(String pKey, Class pClass) throws XmlRpcException {
registerPublicMethods(pKey, pClass);
}
/** Removes all handlers with the given class key.
*/
public void removeHandler(String pKey) {
for (Iterator i = handlerMap.keySet().iterator(); i.hasNext();) {
String k = (String)i.next();
if (k.startsWith(pKey)) i.remove();
}
}
}
| 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.server;
import org.apache.xmlrpc.common.ServerStreamConnection;
/** Interface of a {@link ServerStreamConnection} for HTTP
* response transport.
*/
public interface ServerHttpConnection extends ServerStreamConnection {
/** Sets a response header.
*/
void setResponseHeader(String pKey, String pValue);
/** Sets the content length.
*/
void setContentLength(int pContentLength);
}
| 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.server;
import org.apache.xmlrpc.XmlRpcConfigImpl;
/** Default implementation of {@link org.apache.xmlrpc.server.XmlRpcServerConfig}.
*/
public class XmlRpcServerConfigImpl extends XmlRpcConfigImpl
implements XmlRpcServerConfig, XmlRpcHttpServerConfig {
private boolean isKeepAliveEnabled;
private boolean isEnabledForExceptions;
/** Sets, whether HTTP keepalive is enabled for this server.
* @param pKeepAliveEnabled True, if keepalive is enabled. False otherwise.
*/
public void setKeepAliveEnabled(boolean pKeepAliveEnabled) {
isKeepAliveEnabled = pKeepAliveEnabled;
}
public boolean isKeepAliveEnabled() { return isKeepAliveEnabled; }
/** Sets, whether the server may create a "faultCause" element in an error
* response. Note, that this may be a security issue!
*/
public void setEnabledForExceptions(boolean pEnabledForExceptions) {
isEnabledForExceptions = pEnabledForExceptions;
}
public boolean isEnabledForExceptions() { return isEnabledForExceptions; }
}
| 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.server;
import org.apache.xmlrpc.common.XmlRpcHttpConfig;
/** HTTP servers configuration.
*/
public interface XmlRpcHttpServerConfig extends XmlRpcServerConfig, XmlRpcHttpConfig {
/** Returns, whether HTTP keepalive is being enabled.
* @return True, if keepalive is enabled, false otherwise.
*/
boolean isKeepAliveEnabled();
/** Returns, whether the server may create a "faultCause" element in an error
* response. Note, that this may be a security issue!
*/
boolean isEnabledForExceptions();
}
| 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.server;
import org.apache.xmlrpc.XmlRpcException;
/** This exception is thrown, if an unknown handler is called.
*/
public class XmlRpcNoSuchHandlerException extends XmlRpcException {
private static final long serialVersionUID = 3257002138218344501L;
/** Creates a new instance with the given message.
* @param pMessage The error details.
*/
public XmlRpcNoSuchHandlerException(String pMessage) {
super(0, pMessage);
}
}
| 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.server;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.common.XmlRpcRequestProcessor;
import org.apache.xmlrpc.common.XmlRpcRequestProcessorFactory;
/** Server part of a local stream transport.
*/
public class XmlRpcLocalStreamServer extends XmlRpcStreamServer {
public Object execute(XmlRpcRequest pRequest) throws XmlRpcException {
XmlRpcRequestProcessor server = ((XmlRpcRequestProcessorFactory) pRequest.getConfig()).getXmlRpcServer();
return server.execute(pRequest);
}
} | 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.server;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.metadata.Util;
/**
* <p>The request processor is the object, which is actually performing
* the request. There is nothing magic about the request processor:
* It may very well be a POJO. The {@link RequestProcessorFactoryFactory}
* is passed to the {@link AbstractReflectiveHandlerMapping} at startup.
* The mapping uses this factory to create instances of
* {@link RequestProcessorFactory}, which are used to initialize
* the {@link ReflectiveXmlRpcHandler}. The handler in turn uses its
* factory to create the actual request processor when a request comes
* in.</p>
* <p>However, the question arises, when and how the request processor
* is created and whether it needs request specific initialization.
* The {@link RequestProcessorFactoryFactory} is an object, which makes
* that logic pluggable. Unfortunately, we aren't done with a single
* factory: We even need a factory for factories. The rationale is
* best explained by looking at the different use cases and how to
* implement them.</p>
* <p>The default {@link RequestProcessorFactoryFactory} is the
* {@link RequestSpecificProcessorFactoryFactory}. It creates a new
* processor instance for any request. In other words, it allows the
* request processor to have some state. This is fine, if the request
* processor is a lightweight object or needs request specific
* initialization. In this case, the actual request processor is
* created and invoked when
* calling {@link RequestProcessorFactory#getRequestProcessor(XmlRpcRequest)}.</p>
* <p>An alternative implementation is the
* {@link StatelessProcessorFactoryFactory}, which may be used to
* create stateless request processors. Stateless request processors
* are typically heavyweight objects, which have an expensive
* initialization phase. The processor factory, which is created by
* {@link #getRequestProcessorFactory(Class pClass)} contains an
* initialized singleton, which is returned by
* {@link RequestProcessorFactory#getRequestProcessor(XmlRpcRequest)}.</p>
* <p>Other alternatives might be a
* {@link RequestProcessorFactoryFactory}, which maintains a pool
* of {@link RequestProcessorFactory} instances. The instances are
* configured by calling
* {@link RequestProcessorFactory#getRequestProcessor(XmlRpcRequest)}.</p>
*/
public interface RequestProcessorFactoryFactory {
/**
* This is the factory for request processors. This factory is itself
* created by a call to
* {@link RequestProcessorFactoryFactory#getRequestProcessorFactory(Class)}.
*/
public interface RequestProcessorFactory {
/**
* This method is invoked for any request in order to create and
* configure the request processor. The returned object is an
* instance of the class parameter in
* {@link RequestProcessorFactoryFactory#getRequestProcessorFactory(Class)}.
*/
public Object getRequestProcessor(XmlRpcRequest pRequest) throws XmlRpcException;
}
/**
* This method is invoked at startup. It creates a factory for instances of
* <code>pClass</code>.
*/
public RequestProcessorFactory getRequestProcessorFactory(Class pClass) throws XmlRpcException;
/**
* This is the default implementation of {@link RequestProcessorFactoryFactory}.
* A new instance is created and initialized for any request. The instance may
* be configured by overwriting {@link #getRequestProcessor(Class, XmlRpcRequest)}.
*/
public static class RequestSpecificProcessorFactoryFactory
implements RequestProcessorFactoryFactory {
/**
* Subclasses may override this method for request specific configuration.
* A typical subclass will look like this:
* <pre>
* public class MyRequestProcessorFactoryFactory
* extends RequestProcessorFactoryFactory {
* protected Object getRequestProcessor(Class pClass, XmlRpcRequest pRequest) {
* Object result = super.getRequestProcessor(pClass, pRequest);
* // Configure the object here
* ...
* return result;
* }
* }
* </pre>
* @param pRequest The request object.
*/
protected Object getRequestProcessor(Class pClass, XmlRpcRequest pRequest) throws XmlRpcException {
return Util.newInstance(pClass);
}
public RequestProcessorFactory getRequestProcessorFactory(final Class pClass) throws XmlRpcException {
return new RequestProcessorFactory(){
public Object getRequestProcessor(XmlRpcRequest pRequest) throws XmlRpcException {
return RequestSpecificProcessorFactoryFactory.this.getRequestProcessor(pClass, pRequest);
}
};
}
}
/**
* This is an alternative implementation of {@link RequestProcessorFactoryFactory}.
* It creates stateless request processors, which are able to process concurrent
* requests without request specific initialization.
*/
public static class StatelessProcessorFactoryFactory
implements RequestProcessorFactoryFactory {
/**
* Subclasses may override this method for class specific configuration. Note,
* that this method will be called at startup only! A typical subclass will
* look like this:
* <pre>
* public class MyRequestProcessorFactoryFactory
* extends StatelessProcessorFactoryFactory {
* protected Object getRequestProcessor(Class pClass) {
* Object result = super.getRequestProcessor(pClass);
* // Configure the object here
* ...
* return result;
* }
* }
* </pre>
*/
protected Object getRequestProcessor(Class pClass) throws XmlRpcException {
return Util.newInstance(pClass);
}
public RequestProcessorFactory getRequestProcessorFactory(Class pClass)
throws XmlRpcException {
final Object processor = getRequestProcessor(pClass);
return new RequestProcessorFactory(){
public Object getRequestProcessor(XmlRpcRequest pRequest) throws XmlRpcException {
return processor;
}
};
}
}
}
| 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.server;
import org.apache.xmlrpc.common.XmlRpcWorker;
import org.apache.xmlrpc.common.XmlRpcWorkerFactory;
/** Server specific worker factory.
*/
public class XmlRpcServerWorkerFactory extends XmlRpcWorkerFactory {
/** Creates a new factory with the given controller.
* @param pServer The factory controller.
*/
public XmlRpcServerWorkerFactory(XmlRpcServer pServer) {
super(pServer);
}
protected XmlRpcWorker newWorker() {
return new XmlRpcServerWorker(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.server;
import org.apache.xmlrpc.XmlRpcConfig;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.common.TypeConverterFactory;
import org.apache.xmlrpc.common.TypeConverterFactoryImpl;
import org.apache.xmlrpc.common.XmlRpcController;
import org.apache.xmlrpc.common.XmlRpcRequestProcessor;
import org.apache.xmlrpc.common.XmlRpcWorker;
import org.apache.xmlrpc.common.XmlRpcWorkerFactory;
/** A multithreaded, reusable XML-RPC server object. The name may
* be misleading because this does not open any server sockets.
* Instead it is fed by passing instances of
* {@link org.apache.xmlrpc.XmlRpcRequest} from
* a transport.
*/
public class XmlRpcServer extends XmlRpcController
implements XmlRpcRequestProcessor {
private XmlRpcHandlerMapping handlerMapping;
private TypeConverterFactory typeConverterFactory = new TypeConverterFactoryImpl();
private XmlRpcServerConfig config = new XmlRpcServerConfigImpl();
protected XmlRpcWorkerFactory getDefaultXmlRpcWorkerFactory() {
return new XmlRpcServerWorkerFactory(this);
}
/** Sets the servers {@link TypeConverterFactory}.
*/
public void setTypeConverterFactory(TypeConverterFactory pFactory) {
typeConverterFactory = pFactory;
}
public TypeConverterFactory getTypeConverterFactory() {
return typeConverterFactory;
}
/** Sets the servers configuration.
* @param pConfig The new server configuration.
*/
public void setConfig(XmlRpcServerConfig pConfig) { config = pConfig; }
public XmlRpcConfig getConfig() { return config; }
/** Sets the servers handler mapping.
* @param pMapping The servers handler mapping.
*/
public void setHandlerMapping(XmlRpcHandlerMapping pMapping) {
handlerMapping = pMapping;
}
/** Returns the servers handler mapping.
* @return The servers handler mapping.
*/
public XmlRpcHandlerMapping getHandlerMapping() {
return handlerMapping;
}
/** Performs the given request.
* @param pRequest The request being executed.
* @return The result object.
* @throws XmlRpcException The request failed.
*/
public Object execute(XmlRpcRequest pRequest) throws XmlRpcException {
final XmlRpcWorkerFactory factory = getWorkerFactory();
final XmlRpcWorker worker = factory.getWorker();
try {
return worker.execute(pRequest);
} finally {
factory.releaseWorker(worker);
}
}
}
| 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.server;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Instances of this class can be used to customize the servers
* error logging.
*/
public class XmlRpcErrorLogger {
private static final Log log = LogFactory.getLog(XmlRpcErrorLogger.class);
/**
* Called to log the given error.
*/
public void log(String pMessage, Throwable pThrowable) {
log.error(pMessage, pThrowable);
}
/**
* Called to log the given error message.
*/
public void log(String pMessage) {
log.error(pMessage);
}
}
| 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.server;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.xmlrpc.common.ServerStreamConnection;
import org.apache.xmlrpc.common.XmlRpcStreamRequestConfig;
/** Abstract extension of {@link XmlRpcStreamServer} for deriving
* HTTP servers.
*/
public abstract class XmlRpcHttpServer extends XmlRpcStreamServer {
protected abstract void setResponseHeader(ServerStreamConnection pConnection, String pHeader, String pValue);
protected OutputStream getOutputStream(ServerStreamConnection pConnection, XmlRpcStreamRequestConfig pConfig, OutputStream pStream) throws IOException {
if (pConfig.isEnabledForExtensions() && pConfig.isGzipRequesting()) {
setResponseHeader(pConnection, "Content-Encoding", "gzip");
}
return super.getOutputStream(pConnection, pConfig, pStream);
}
}
| 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.server;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcHandler;
/** Maps from a handler name to a handler object.
* @since 1.2
*/
public interface XmlRpcHandlerMapping {
/** Return the handler for the specified handler name.
* @param handlerName The name of the handler to retrieve.
* @return Object The desired handler. Never null, an exception
* is thrown if no such handler is available.
* @throws XmlRpcNoSuchHandlerException The handler is not available.
* @throws XmlRpcException An internal error occurred.
*/
public XmlRpcHandler getHandler(String handlerName)
throws XmlRpcNoSuchHandlerException, XmlRpcException;
}
| 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.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.XmlRpcRequestConfig;
import org.apache.xmlrpc.common.ServerStreamConnection;
import org.apache.xmlrpc.common.XmlRpcStreamRequestConfig;
import org.apache.xmlrpc.common.XmlRpcStreamRequestProcessor;
import org.apache.xmlrpc.parser.XmlRpcRequestParser;
import org.apache.xmlrpc.serializer.DefaultXMLWriterFactory;
import org.apache.xmlrpc.serializer.XmlRpcWriter;
import org.apache.xmlrpc.serializer.XmlWriterFactory;
import org.apache.xmlrpc.util.SAXParsers;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/** Extension of {@link XmlRpcServer} with support for reading
* requests from a stream and writing the response to another
* stream.
*/
public abstract class XmlRpcStreamServer extends XmlRpcServer
implements XmlRpcStreamRequestProcessor {
private static final Log log = LogFactory.getLog(XmlRpcStreamServer.class);
private XmlWriterFactory writerFactory = new DefaultXMLWriterFactory();
private static final XmlRpcErrorLogger theErrorLogger = new XmlRpcErrorLogger();
private XmlRpcErrorLogger errorLogger = theErrorLogger;
protected XmlRpcRequest getRequest(final XmlRpcStreamRequestConfig pConfig,
InputStream pStream) throws XmlRpcException {
final XmlRpcRequestParser parser = new XmlRpcRequestParser(pConfig, getTypeFactory());
final XMLReader xr = SAXParsers.newXMLReader();
xr.setContentHandler(parser);
try {
xr.parse(new InputSource(pStream));
} catch (SAXException e) {
Exception ex = e.getException();
if (ex != null && ex instanceof XmlRpcException) {
throw (XmlRpcException) ex;
}
throw new XmlRpcException("Failed to parse XML-RPC request: " + e.getMessage(), e);
} catch (IOException e) {
throw new XmlRpcException("Failed to read XML-RPC request: " + e.getMessage(), e);
}
final List params = parser.getParams();
return new XmlRpcRequest(){
public XmlRpcRequestConfig getConfig() { return pConfig; }
public String getMethodName() { return parser.getMethodName(); }
public int getParameterCount() { return params == null ? 0 : params.size(); }
public Object getParameter(int pIndex) { return params.get(pIndex); }
};
}
protected XmlRpcWriter getXmlRpcWriter(XmlRpcStreamRequestConfig pConfig,
OutputStream pStream)
throws XmlRpcException {
ContentHandler w = getXMLWriterFactory().getXmlWriter(pConfig, pStream);
return new XmlRpcWriter(pConfig, w, getTypeFactory());
}
protected void writeResponse(XmlRpcStreamRequestConfig pConfig, OutputStream pStream,
Object pResult) throws XmlRpcException {
try {
getXmlRpcWriter(pConfig, pStream).write(pConfig, pResult);
} catch (SAXException e) {
throw new XmlRpcException("Failed to write XML-RPC response: " + e.getMessage(), e);
}
}
/**
* This method allows to convert the error into another error. For example, this
* may be an error, which could be deserialized by the client.
*/
protected Throwable convertThrowable(Throwable pError) {
return pError;
}
protected void writeError(XmlRpcStreamRequestConfig pConfig, OutputStream pStream,
Throwable pError)
throws XmlRpcException {
final Throwable error = convertThrowable(pError);
final int code;
final String message;
if (error instanceof XmlRpcException) {
XmlRpcException ex = (XmlRpcException) error;
code = ex.code;
} else {
code = 0;
}
message = error.getMessage();
try {
getXmlRpcWriter(pConfig, pStream).write(pConfig, code, message, error);
} catch (SAXException e) {
throw new XmlRpcException("Failed to write XML-RPC response: " + e.getMessage(), e);
}
}
/** Sets the XML Writer factory.
* @param pFactory The XML Writer factory.
*/
public void setXMLWriterFactory(XmlWriterFactory pFactory) {
writerFactory = pFactory;
}
/** Returns the XML Writer factory.
* @return The XML Writer factory.
*/
public XmlWriterFactory getXMLWriterFactory() {
return writerFactory;
}
protected InputStream getInputStream(XmlRpcStreamRequestConfig pConfig,
ServerStreamConnection pConnection) throws IOException {
InputStream istream = pConnection.newInputStream();
if (pConfig.isEnabledForExtensions() && pConfig.isGzipCompressing()) {
istream = new GZIPInputStream(istream);
}
return istream;
}
/** Called to prepare the output stream. Typically used for enabling
* compression, or similar filters.
* @param pConnection The connection object.
*/
protected OutputStream getOutputStream(ServerStreamConnection pConnection,
XmlRpcStreamRequestConfig pConfig, OutputStream pStream) throws IOException {
if (pConfig.isEnabledForExtensions() && pConfig.isGzipRequesting()) {
return new GZIPOutputStream(pStream);
} else {
return pStream;
}
}
/** Called to prepare the output stream, if content length is
* required.
* @param pConfig The configuration object.
* @param pSize The requests size.
*/
protected OutputStream getOutputStream(XmlRpcStreamRequestConfig pConfig,
ServerStreamConnection pConnection,
int pSize) throws IOException {
return pConnection.newOutputStream();
}
/** Returns, whether the requests content length is required.
* @param pConfig The configuration object.
*/
protected boolean isContentLengthRequired(XmlRpcStreamRequestConfig pConfig) {
return false;
}
/** Returns, whether the
/** Processes a "connection". The "connection" is an opaque object, which is
* being handled by the subclasses.
* @param pConfig The request configuration.
* @param pConnection The "connection" being processed.
* @throws XmlRpcException Processing the request failed.
*/
public void execute(XmlRpcStreamRequestConfig pConfig,
ServerStreamConnection pConnection)
throws XmlRpcException {
log.debug("execute: ->");
try {
Object result;
Throwable error;
InputStream istream = null;
try {
istream = getInputStream(pConfig, pConnection);
XmlRpcRequest request = getRequest(pConfig, istream);
result = execute(request);
istream.close();
istream = null;
error = null;
log.debug("execute: Request performed successfully");
} catch (Throwable t) {
logError(t);
result = null;
error = t;
} finally {
if (istream != null) { try { istream.close(); } catch (Throwable ignore) {} }
}
boolean contentLengthRequired = isContentLengthRequired(pConfig);
ByteArrayOutputStream baos;
OutputStream ostream;
if (contentLengthRequired) {
baos = new ByteArrayOutputStream();
ostream = baos;
} else {
baos = null;
ostream = pConnection.newOutputStream();
}
ostream = getOutputStream(pConnection, pConfig, ostream);
try {
if (error == null) {
writeResponse(pConfig, ostream, result);
} else {
writeError(pConfig, ostream, error);
}
ostream.close();
ostream = null;
} finally {
if (ostream != null) { try { ostream.close(); } catch (Throwable ignore) {} }
}
if (baos != null) {
OutputStream dest = getOutputStream(pConfig, pConnection, baos.size());
try {
baos.writeTo(dest);
dest.close();
dest = null;
} finally {
if (dest != null) { try { dest.close(); } catch (Throwable ignore) {} }
}
}
pConnection.close();
pConnection = null;
} catch (IOException e) {
throw new XmlRpcException("I/O error while processing request: "
+ e.getMessage(), e);
} finally {
if (pConnection != null) { try { pConnection.close(); } catch (Throwable ignore) {} }
}
log.debug("execute: <-");
}
protected void logError(Throwable t) {
final String msg = t.getMessage() == null ? t.getClass().getName() : t.getMessage();
errorLogger.log(msg, t);
}
/**
* Returns the error logger.
*/
public XmlRpcErrorLogger getErrorLogger() {
return errorLogger;
}
/**
* Sets the error logger.
*/
public void setErrorLogger(XmlRpcErrorLogger pErrorLogger) {
errorLogger = pErrorLogger;
}
}
| 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.server;
import org.apache.xmlrpc.XmlRpcConfig;
/** Server specific extension of {@link org.apache.xmlrpc.XmlRpcConfig}.
*/
public interface XmlRpcServerConfig extends XmlRpcConfig {
}
| 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.server;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcHandler;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.common.XmlRpcController;
import org.apache.xmlrpc.common.XmlRpcWorker;
/** Server specific implementation of {@link XmlRpcWorker}.
*/
public class XmlRpcServerWorker implements XmlRpcWorker {
private final XmlRpcServerWorkerFactory factory;
/** Creates a new instance.
* @param pFactory The factory creating the worker.
*/
public XmlRpcServerWorker(XmlRpcServerWorkerFactory pFactory) {
factory = pFactory;
}
public XmlRpcController getController() { return factory.getController(); }
public Object execute(XmlRpcRequest pRequest) throws XmlRpcException {
XmlRpcServer server = (XmlRpcServer) getController();
XmlRpcHandlerMapping mapping = server.getHandlerMapping();
XmlRpcHandler handler = mapping.getHandler(pRequest.getMethodName());
return handler.execute(pRequest);
}
}
| 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.webserver;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.SocketException;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.xmlrpc.common.ServerStreamConnection;
import org.apache.xmlrpc.common.XmlRpcHttpRequestConfig;
import org.apache.xmlrpc.common.XmlRpcNotAuthorizedException;
import org.apache.xmlrpc.server.XmlRpcHttpServerConfig;
import org.apache.xmlrpc.server.XmlRpcStreamServer;
import org.apache.xmlrpc.util.HttpUtil;
import org.apache.xmlrpc.util.LimitedInputStream;
import org.apache.xmlrpc.util.ThreadPool;
/** Handler for a single clients connection. This implementation
* is able to do HTTP keepalive. In other words, it can serve
* multiple requests via a single, physical connection.
*/
public class Connection implements ThreadPool.InterruptableTask, ServerStreamConnection {
private static final String US_ASCII = "US-ASCII";
private static final byte[] ctype = toHTTPBytes("Content-Type: text/xml\r\n");
private static final byte[] clength = toHTTPBytes("Content-Length: ");
private static final byte[] newline = toHTTPBytes("\r\n");
private static final byte[] doubleNewline = toHTTPBytes("\r\n\r\n");
private static final byte[] conkeep = toHTTPBytes("Connection: Keep-Alive\r\n");
private static final byte[] conclose = toHTTPBytes("Connection: close\r\n");
private static final byte[] ok = toHTTPBytes(" 200 OK\r\n");
private static final byte[] serverName = toHTTPBytes("Server: Apache XML-RPC 1.0\r\n");
private static final byte[] wwwAuthenticate = toHTTPBytes("WWW-Authenticate: Basic realm=XML-RPC\r\n");
private static abstract class RequestException extends IOException {
private static final long serialVersionUID = 2113732921468653309L;
private final RequestData requestData;
RequestException(RequestData pData, String pMessage) {
super(pMessage);
requestData = pData;
}
RequestData getRequestData() { return requestData; }
}
private static class BadEncodingException extends RequestException {
private static final long serialVersionUID = -2674424938251521248L;
BadEncodingException(RequestData pData, String pTransferEncoding) {
super(pData, pTransferEncoding);
}
}
private static class BadRequestException extends RequestException {
private static final long serialVersionUID = 3257848779234554934L;
BadRequestException(RequestData pData, String pTransferEncoding) {
super(pData, pTransferEncoding);
}
}
/** Returns the US-ASCII encoded byte representation of text for
* HTTP use (as per section 2.2 of RFC 2068).
*/
private static final byte[] toHTTPBytes(String text) {
try {
return text.getBytes(US_ASCII);
} catch (UnsupportedEncodingException e) {
throw new Error(e.getMessage() +
": HTTP requires US-ASCII encoding");
}
}
private final WebServer webServer;
private final Socket socket;
private final InputStream input;
private final OutputStream output;
private final XmlRpcStreamServer server;
private byte[] buffer;
private Map headers;
private RequestData requestData;
private boolean shuttingDown;
private boolean firstByte;
/** Creates a new webserver connection on the given socket.
* @param pWebServer The webserver maintaining this connection.
* @param pServer The server being used to execute requests.
* @param pSocket The server socket to handle; the <code>Connection</code>
* is responsible for closing this socket.
* @throws IOException
*/
public Connection(WebServer pWebServer, XmlRpcStreamServer pServer, Socket pSocket)
throws IOException {
webServer = pWebServer;
server = pServer;
socket = pSocket;
input = new BufferedInputStream(socket.getInputStream()){
/** It may happen, that the XML parser invokes close().
* Closing the input stream must not occur, because
* that would close the whole socket. So we suppress it.
*/
public void close() throws IOException {
}
};
output = new BufferedOutputStream(socket.getOutputStream());
}
/** Returns the connections request configuration by
* merging the HTTP request headers and the servers configuration.
* @return The connections request configuration.
* @throws IOException Reading the request headers failed.
*/
private RequestData getRequestConfig() throws IOException {
requestData = new RequestData(this);
if (headers != null) {
headers.clear();
}
firstByte = true;
XmlRpcHttpServerConfig serverConfig = (XmlRpcHttpServerConfig) server.getConfig();
requestData.setBasicEncoding(serverConfig.getBasicEncoding());
requestData.setContentLengthOptional(serverConfig.isContentLengthOptional());
requestData.setEnabledForExtensions(serverConfig.isEnabledForExtensions());
requestData.setEnabledForExceptions(serverConfig.isEnabledForExceptions());
// reset user authentication
String line = readLine();
if (line == null && firstByte) {
return null;
}
// Netscape sends an extra \n\r after bodypart, swallow it
if (line != null && line.length() == 0) {
line = readLine();
if (line == null || line.length() == 0) {
return null;
}
}
// tokenize first line of HTTP request
StringTokenizer tokens = new StringTokenizer(line);
String method = tokens.nextToken();
if (!"POST".equalsIgnoreCase(method)) {
throw new BadRequestException(requestData, method);
}
requestData.setMethod(method);
tokens.nextToken(); // Skip URI
String httpVersion = tokens.nextToken();
requestData.setHttpVersion(httpVersion);
requestData.setKeepAlive(serverConfig.isKeepAliveEnabled()
&& WebServer.HTTP_11.equals(httpVersion));
do {
line = readLine();
if (line != null) {
String lineLower = line.toLowerCase();
if (lineLower.startsWith("content-length:")) {
String cLength = line.substring("content-length:".length());
requestData.setContentLength(Integer.parseInt(cLength.trim()));
} else if (lineLower.startsWith("connection:")) {
requestData.setKeepAlive(serverConfig.isKeepAliveEnabled()
&& lineLower.indexOf("keep-alive") > -1);
} else if (lineLower.startsWith("authorization:")) {
String credentials = line.substring("authorization:".length());
HttpUtil.parseAuthorization(requestData, credentials);
} else if (lineLower.startsWith("transfer-encoding:")) {
String transferEncoding = line.substring("transfer-encoding:".length());
String nonIdentityEncoding = HttpUtil.getNonIdentityTransferEncoding(transferEncoding);
if (nonIdentityEncoding != null) {
throw new BadEncodingException(requestData, nonIdentityEncoding);
}
}
}
}
while (line != null && line.length() != 0);
return requestData;
}
public void run() {
try {
for (int i = 0; ; i++) {
RequestData data = getRequestConfig();
if (data == null) {
break;
}
server.execute(data, this);
output.flush();
if (!data.isKeepAlive() || !data.isSuccess()) {
break;
}
}
} catch (RequestException e) {
webServer.log(e.getClass().getName() + ": " + e.getMessage());
try {
writeErrorHeader(e.requestData, e, -1);
output.flush();
} catch (IOException e1) {
/* Ignore me */
}
} catch (Throwable t) {
if (!shuttingDown) {
webServer.log(t);
}
} finally {
try { output.close(); } catch (Throwable ignore) {}
try { input.close(); } catch (Throwable ignore) {}
try { socket.close(); } catch (Throwable ignore) {}
}
}
private String readLine() throws IOException {
if (buffer == null) {
buffer = new byte[2048];
}
int next;
int count = 0;
for (;;) {
try {
next = input.read();
firstByte = false;
} catch (SocketException e) {
if (firstByte) {
return null;
} else {
throw e;
}
}
if (next < 0 || next == '\n') {
break;
}
if (next != '\r') {
buffer[count++] = (byte) next;
}
if (count >= buffer.length) {
throw new IOException("HTTP Header too long");
}
}
return new String(buffer, 0, count, US_ASCII);
}
/** Writes the response header and the response to the
* output stream.
* @param pData The request data.
* @param pBuffer The {@link ByteArrayOutputStream} holding the response.
* @throws IOException Writing the response failed.
*/
public void writeResponse(RequestData pData, OutputStream pBuffer)
throws IOException {
ByteArrayOutputStream response = (ByteArrayOutputStream) pBuffer;
writeResponseHeader(pData, response.size());
response.writeTo(output);
}
/** Writes the response header to the output stream. *
* @param pData The request data
* @param pContentLength The content length, if known, or -1.
* @throws IOException Writing the response failed.
*/
public void writeResponseHeader(RequestData pData, int pContentLength)
throws IOException {
output.write(toHTTPBytes(pData.getHttpVersion()));
output.write(ok);
output.write(serverName);
output.write(pData.isKeepAlive() ? conkeep : conclose);
output.write(ctype);
if (headers != null) {
for (Iterator iter = headers.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
String header = (String) entry.getKey();
String value = (String) entry.getValue();
output.write(toHTTPBytes(header + ": " + value + "\r\n"));
}
}
if (pContentLength != -1) {
output.write(clength);
output.write(toHTTPBytes(Integer.toString(pContentLength)));
output.write(doubleNewline);
} else {
output.write(newline);
}
pData.setSuccess(true);
}
/** Writes an error response to the output stream.
* @param pData The request data.
* @param pError The error being reported.
* @param pStream The {@link ByteArrayOutputStream} with the error response.
* @throws IOException Writing the response failed.
*/
public void writeError(RequestData pData, Throwable pError, ByteArrayOutputStream pStream)
throws IOException {
writeErrorHeader(pData, pError, pStream.size());
pStream.writeTo(output);
output.flush();
}
/** Writes an error responses headers to the output stream.
* @param pData The request data.
* @param pError The error being reported.
* @param pContentLength The response length, if known, or -1.
* @throws IOException Writing the response failed.
*/
public void writeErrorHeader(RequestData pData, Throwable pError, int pContentLength)
throws IOException {
if (pError instanceof BadRequestException) {
final byte[] content = toHTTPBytes("Method " + pData.getMethod()
+ " not implemented (try POST)\r\n");
output.write(toHTTPBytes(pData.getHttpVersion()));
output.write(toHTTPBytes(" 400 Bad Request"));
output.write(newline);
output.write(serverName);
writeContentLengthHeader(content.length);
output.write(newline);
output.write(content);
} else if (pError instanceof BadEncodingException) {
final byte[] content = toHTTPBytes("The Transfer-Encoding " + pError.getMessage()
+ " is not implemented.\r\n");
output.write(toHTTPBytes(pData.getHttpVersion()));
output.write(toHTTPBytes(" 501 Not Implemented"));
output.write(newline);
output.write(serverName);
writeContentLengthHeader(content.length);
output.write(newline);
output.write(content);
} else if (pError instanceof XmlRpcNotAuthorizedException) {
final byte[] content = toHTTPBytes("Method " + pData.getMethod()
+ " requires a " + "valid user name and password.\r\n");
output.write(toHTTPBytes(pData.getHttpVersion()));
output.write(toHTTPBytes(" 401 Unauthorized"));
output.write(newline);
output.write(serverName);
writeContentLengthHeader(content.length);
output.write(wwwAuthenticate);
output.write(newline);
output.write(content);
} else {
output.write(toHTTPBytes(pData.getHttpVersion()));
output.write(ok);
output.write(serverName);
output.write(conclose);
output.write(ctype);
writeContentLengthHeader(pContentLength);
output.write(newline);
}
}
private void writeContentLengthHeader(int pContentLength) throws IOException {
if (pContentLength == -1) {
return;
}
output.write(clength);
output.write(toHTTPBytes(Integer.toString(pContentLength)));
output.write(newline);
}
/** Sets a response header value.
*/
public void setResponseHeader(String pHeader, String pValue) {
headers.put(pHeader, pValue);
}
public OutputStream newOutputStream() throws IOException {
boolean useContentLength;
useContentLength = !requestData.isEnabledForExtensions()
|| !((XmlRpcHttpRequestConfig) requestData).isContentLengthOptional();
if (useContentLength) {
return new ByteArrayOutputStream();
} else {
return output;
}
}
public InputStream newInputStream() throws IOException {
int contentLength = requestData.getContentLength();
if (contentLength == -1) {
return input;
} else {
return new LimitedInputStream(input, contentLength);
}
}
public void close() throws IOException {
}
public void shutdown() throws Throwable {
shuttingDown = true;
socket.close();
}
}
| 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.webserver;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.common.ServerStreamConnection;
import org.apache.xmlrpc.common.XmlRpcStreamRequestConfig;
import org.apache.xmlrpc.server.XmlRpcHttpServer;
class ConnectionServer extends XmlRpcHttpServer {
protected void writeError(XmlRpcStreamRequestConfig pConfig, OutputStream pStream,
Throwable pError) throws XmlRpcException {
RequestData data = (RequestData) pConfig;
try {
if (data.isByteArrayRequired()) {
super.writeError(pConfig, pStream, pError);
data.getConnection().writeError(data, pError, (ByteArrayOutputStream) pStream);
} else {
data.getConnection().writeErrorHeader(data, pError, -1);
super.writeError(pConfig, pStream, pError);
pStream.flush();
}
} catch (IOException e) {
throw new XmlRpcException(e.getMessage(), e);
}
}
protected void writeResponse(XmlRpcStreamRequestConfig pConfig, OutputStream pStream, Object pResult) throws XmlRpcException {
RequestData data = (RequestData) pConfig;
try {
if (data.isByteArrayRequired()) {
super.writeResponse(pConfig, pStream, pResult);
data.getConnection().writeResponse(data, pStream);
} else {
data.getConnection().writeResponseHeader(data, -1);
super.writeResponse(pConfig, pStream, pResult);
pStream.flush();
}
} catch (IOException e) {
throw new XmlRpcException(e.getMessage(), e);
}
}
protected void setResponseHeader(ServerStreamConnection pConnection, String pHeader, String pValue) {
((Connection) pConnection).setResponseHeader(pHeader, pValue);
}
} | 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.webserver;
import org.apache.xmlrpc.common.XmlRpcHttpRequestConfigImpl;
/** Web servers extension of
* {@link org.apache.xmlrpc.common.XmlRpcHttpRequestConfig},
* which allows to store additional per request data.
*/
public class RequestData extends XmlRpcHttpRequestConfigImpl {
private final Connection connection;
private boolean keepAlive;
private String method, httpVersion;
private int contentLength = -1;
private boolean success;
/** Creates a new instance.
* @param pConnection The connection, which is serving the request.
*/
public RequestData(Connection pConnection) {
connection = pConnection;
}
/** Returns the connection, which is serving the request.
* @return The request connection.
*/
public Connection getConnection() { return connection; }
/** Returns, whether HTTP keepAlive is enabled for this
* connection.
* @return True, if keepAlive is enabled, false otherwise.
*/
public boolean isKeepAlive() { return keepAlive; }
/** Sets, whether HTTP keepAlive is enabled for this
* connection.
* @param pKeepAlive True, if keepAlive is enabled, false otherwise.
*/
public void setKeepAlive(boolean pKeepAlive) {
keepAlive = pKeepAlive;
}
/** Returns the requests HTTP version.
* @return HTTP version, for example "1.0"
*/
public String getHttpVersion() { return httpVersion; }
/** Sets the requests HTTP version.
* @param pHttpVersion HTTP version, for example "1.0"
*/
public void setHttpVersion(String pHttpVersion) {
httpVersion = pHttpVersion;
}
/** Returns the requests content length.
* @return Content length, if known, or -1, if unknown.
*/
public int getContentLength() { return contentLength; }
/** Sets the requests content length.
* @param pContentLength Content length, if known, or -1, if unknown.
*/
public void setContentLength(int pContentLength) {
contentLength = pContentLength;
}
/** Returns, whether a byte array for buffering the output is
* required.
* @return True, if the byte array is required, false otherwise.
*/
public boolean isByteArrayRequired() {
return isKeepAlive() || !isEnabledForExtensions() || !isContentLengthOptional();
}
/** Returns the request method.
* @return The request method, should be "POST".
*/
public String getMethod() { return method; }
/** Sets the request method.
* @param pMethod The request method, should be "POST".
*/
public void setMethod(String pMethod) {
method = pMethod;
}
/** Returns, whether the request was executed successfull.
* @return True for success, false, if an error occurred.
*/
public boolean isSuccess() { return success; }
/** Sets, whether the request was executed successfull.
* @param pSuccess True for success, false, if an error occurred.
*/
public void setSuccess(boolean pSuccess) {
success = pSuccess;
}
}
| 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.webserver;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.xmlrpc.server.XmlRpcStreamServer;
import org.apache.xmlrpc.util.ThreadPool;
/**
* <p>The {@link WebServer} is a minimal HTTP server, that might be used
* as an embedded web server.</p>
* <p>Use of the {@link WebServer} has grown very popular amongst users
* of Apache XML-RPC. Why this is the case, can hardly be explained,
* because the {@link WebServer} is at best a workaround, compared to
* full blown servlet engines like Tomcat or Jetty. For example, under
* heavy load it will almost definitely be slower than a real servlet
* engine, because it does neither support proper keepalive (multiple
* requests per physical connection) nor chunked mode (in other words,
* it cannot stream requests).</p>
* <p>If you still insist in using the {@link WebServer}, it is
* recommended to use its subclass, the {@link ServletWebServer} instead,
* which offers a minimal subset of the servlet API. In other words,
* you keep yourself the option to migrate to a real servlet engine
* later.</p>
* <p>Use of the {@link WebServer} goes roughly like this: First of all,
* create a property file (for example "MyHandlers.properties") and
* add it to your jar file. The property keys are handler names and
* the property values are the handler classes. Once that is done,
* create an instance of WebServer:
* <pre>
* final int port = 8088;
* final String propertyFile = "MyHandler.properties";
*
* PropertyHandlerMapping mapping = new PropertyHandlerMapping();
* ClassLoader cl = Thread.currentThread().getContextClassLoader();
* mapping.load(cl, propertyFile);
* WebServer webServer = new WebServer(port);
* XmlRpcServerConfigImpl config = new XmlRpcServerConfigImpl();
* XmlRpcServer server = webServer.getXmlRpcServer();
* server.setConfig(config);
* server.setHandlerMapping(mapping);
* webServer.start();
* </pre>
*/
public class WebServer implements Runnable {
private class AddressMatcher {
private final int pattern[];
AddressMatcher(String pAddress) {
try {
pattern = new int[4];
StringTokenizer st = new StringTokenizer(pAddress, ".");
if (st.countTokens() != 4) {
throw new IllegalArgumentException();
}
for (int i = 0; i < 4; i++) {
String next = st.nextToken();
if ("*".equals(next)) {
pattern[i] = 256;
} else {
/* Note: *Not* pattern[i] = Integer.parseInt(next);
* See XMLRPC-145
*/
pattern[i] = (byte) Integer.parseInt(next);
}
}
} catch (Exception e) {
throw new IllegalArgumentException("\"" + pAddress
+ "\" does not represent a valid IP address");
}
}
boolean matches(byte[] pAddress) {
for (int i = 0; i < 4; i++) {
if (pattern[i] > 255) {
continue; // Wildcard
}
if (pattern[i] != pAddress[i]) {
return false;
}
}
return true;
}
}
protected ServerSocket serverSocket;
private Thread listener;
private ThreadPool pool;
protected final List accept = new ArrayList();
protected final List deny = new ArrayList();
protected final XmlRpcStreamServer server = newXmlRpcStreamServer();
protected XmlRpcStreamServer newXmlRpcStreamServer(){
return new ConnectionServer();
}
// Inputs to setupServerSocket()
private InetAddress address;
private int port;
private boolean paranoid;
static final String HTTP_11 = "HTTP/1.1";
/** Creates a web server at the specified port number.
* @param pPort Port number; 0 for a random port, choosen by the
* operating system.
*/
public WebServer(int pPort) {
this(pPort, null);
}
/** Creates a web server at the specified port number and IP address.
* @param pPort Port number; 0 for a random port, choosen by the
* operating system.
* @param pAddr Local IP address; null for all available IP addresses.
*/
public WebServer(int pPort, InetAddress pAddr) {
address = pAddr;
port = pPort;
}
/**
* Factory method to manufacture the server socket. Useful as a
* hook method for subclasses to override when they desire
* different flavor of socket (i.e. a <code>SSLServerSocket</code>).
*
* @param pPort Port number; 0 for a random port, choosen by the operating
* system.
* @param backlog
* @param addr If <code>null</code>, binds to
* <code>INADDR_ANY</code>, meaning that all network interfaces on
* a multi-homed host will be listening.
* @exception IOException Error creating listener socket.
*/
protected ServerSocket createServerSocket(int pPort, int backlog, InetAddress addr)
throws IOException {
return new ServerSocket(pPort, backlog, addr);
}
/**
* Initializes this server's listener socket with the specified
* attributes, assuring that a socket timeout has been set. The
* {@link #createServerSocket(int, int, InetAddress)} method can
* be overridden to change the flavor of socket used.
*
* @see #createServerSocket(int, int, InetAddress)
*/
private synchronized void setupServerSocket(int backlog) throws IOException {
// Since we can't reliably set SO_REUSEADDR until JDK 1.4 is
// the standard, try to (re-)open the server socket several
// times. Some OSes (Linux and Solaris, for example), hold on
// to listener sockets for a brief period of time for security
// reasons before relinquishing their hold.
for (int i = 1; ; i++) {
try {
serverSocket = createServerSocket(port, backlog, address);
// A socket timeout must be set.
if (serverSocket.getSoTimeout() <= 0) {
serverSocket.setSoTimeout(4096);
}
return;
} catch (BindException e) {
if (i == 10) {
throw e;
} else {
long waitUntil = System.currentTimeMillis() + 1000;
for (;;) {
long l = waitUntil - System.currentTimeMillis();
if (l > 0) {
try {
Thread.sleep(l);
} catch (InterruptedException ex) {
}
} else {
break;
}
}
}
}
}
}
/**
* Spawns a new thread which binds this server to the port it's
* configured to accept connections on.
*
* @see #run()
* @throws IOException Binding the server socket failed.
*/
public void start() throws IOException {
setupServerSocket(50);
// The listener reference is released upon shutdown().
if (listener == null) {
listener = new Thread(this, "XML-RPC Weblistener");
// Not marked as daemon thread since run directly via main().
listener.start();
}
}
/**
* Switch client filtering on/off.
* @param pParanoid True to enable filtering, false otherwise.
* @see #acceptClient(java.lang.String)
* @see #denyClient(java.lang.String)
*/
public void setParanoid(boolean pParanoid) {
paranoid = pParanoid;
}
/**
* Returns the client filtering state.
* @return True, if client filtering is enabled, false otherwise.
* @see #acceptClient(java.lang.String)
* @see #denyClient(java.lang.String)
*/
protected boolean isParanoid() {
return paranoid;
}
/** Add an IP address to the list of accepted clients. The parameter can
* contain '*' as wildcard character, e.g. "192.168.*.*". You must call
* setParanoid(true) in order for this to have any effect.
* @param pAddress The IP address being enabled.
* @see #denyClient(java.lang.String)
* @see #setParanoid(boolean)
* @throws IllegalArgumentException Parsing the address failed.
*/
public void acceptClient(String pAddress) {
accept.add(new AddressMatcher(pAddress));
}
/**
* Add an IP address to the list of denied clients. The parameter can
* contain '*' as wildcard character, e.g. "192.168.*.*". You must call
* setParanoid(true) in order for this to have any effect.
* @param pAddress The IP address being disabled.
* @see #acceptClient(java.lang.String)
* @see #setParanoid(boolean)
* @throws IllegalArgumentException Parsing the address failed.
*/
public void denyClient(String pAddress) {
deny.add(new AddressMatcher(pAddress));
}
/**
* Checks incoming connections to see if they should be allowed.
* If not in paranoid mode, always returns true.
*
* @param s The socket to inspect.
* @return Whether the connection should be allowed.
*/
protected boolean allowConnection(Socket s) {
if (!paranoid) {
return true;
}
int l = deny.size();
byte addr[] = s.getInetAddress().getAddress();
for (int i = 0; i < l; i++) {
AddressMatcher match = (AddressMatcher) deny.get(i);
if (match.matches(addr))
{
return false;
}
}
l = accept.size();
for (int i = 0; i < l; i++) {
AddressMatcher match = (AddressMatcher) accept.get(i);
if (match.matches(addr)) {
return true;
}
}
return false;
}
protected ThreadPool.Task newTask(WebServer pServer, XmlRpcStreamServer pXmlRpcServer,
Socket pSocket) throws IOException {
return new Connection(pServer, pXmlRpcServer, pSocket);
}
/**
* Listens for client requests until stopped. Call {@link
* #start()} to invoke this method, and {@link #shutdown()} to
* break out of it.
*
* @throws RuntimeException Generally caused by either an
* <code>UnknownHostException</code> or <code>BindException</code>
* with the vanilla web server.
*
* @see #start()
* @see #shutdown()
*/
public void run() {
pool = newThreadPool();
try {
while (listener != null) {
try {
Socket socket = serverSocket.accept();
try {
socket.setTcpNoDelay(true);
} catch (SocketException socketOptEx) {
log(socketOptEx);
}
try {
if (allowConnection(socket)) {
// set read timeout to 30 seconds
socket.setSoTimeout(30000);
final ThreadPool.Task task = newTask(this, server, socket);
if (pool.startTask(task)) {
socket = null;
} else {
log("Maximum load of " + pool.getMaxThreads()
+ " exceeded, rejecting client");
}
}
} finally {
if (socket != null) { try { socket.close(); } catch (Throwable ignore) {} }
}
} catch (InterruptedIOException checkState) {
// Timeout while waiting for a client (from
// SO_TIMEOUT)...try again if still listening.
} catch (Throwable t) {
log(t);
}
}
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
log(e);
}
}
// Shutdown our Runner-based threads
pool.shutdown();
}
}
protected ThreadPool newThreadPool() {
return new ThreadPool(server.getMaxThreads(), "XML-RPC");
}
/**
* Stop listening on the server port. Shutting down our {@link
* #listener} effectively breaks it out of its {@link #run()}
* loop.
*
* @see #run()
*/
public synchronized void shutdown() {
// Stop accepting client connections
if (listener != null) {
Thread l = listener;
listener = null;
l.interrupt();
if (pool != null) {
pool.shutdown();
}
}
}
/** Returns the port, on which the web server is running.
* This method may be invoked after {@link #start()} only.
* @return Servers port number
*/
public int getPort() { return serverSocket.getLocalPort(); }
/** Logs an error.
* @param pError The error being logged.
*/
public void log(Throwable pError) {
final String msg = pError.getMessage() == null ? pError.getClass().getName() : pError.getMessage();
server.getErrorLogger().log(msg, pError);
}
/** Logs a message.
* @param pMessage The being logged.
*/
public void log(String pMessage) {
server.getErrorLogger().log(pMessage);
}
/** Returns the {@link org.apache.xmlrpc.server.XmlRpcServer}.
* @return The server object.
*/
public XmlRpcStreamServer getXmlRpcServer() {
return server;
}
}
| Java |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.ros.rosjava_tutorial_services;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.NodeMain;
import org.ros.node.service.ServiceResponseBuilder;
import org.ros.node.service.ServiceServer;
/**
* This is a simple {@link ServiceServer} {@link NodeMain}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class Server extends AbstractNodeMain {
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("rosjava_tutorial_services/server");
}
@Override
public void onStart(ConnectedNode connectedNode) {
connectedNode.newServiceServer("add_two_ints", test_ros.AddTwoInts._TYPE,
new ServiceResponseBuilder<test_ros.AddTwoIntsRequest, test_ros.AddTwoIntsResponse>() {
@Override
public void
build(test_ros.AddTwoIntsRequest request, test_ros.AddTwoIntsResponse response) {
response.setSum(request.getA() + request.getB());
}
});
}
}
| 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.rosjava_tutorial_services;
import org.ros.exception.RemoteException;
import org.ros.exception.RosRuntimeException;
import org.ros.exception.ServiceNotFoundException;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.NodeMain;
import org.ros.node.service.ServiceClient;
import org.ros.node.service.ServiceResponseListener;
/**
* A simple {@link ServiceClient} {@link NodeMain}.
*
* @author damonkohler@google.com (Damon Kohler)
*/
public class Client extends AbstractNodeMain {
@Override
public GraphName getDefaultNodeName() {
return GraphName.of("rosjava_tutorial_services/client");
}
@Override
public void onStart(final ConnectedNode connectedNode) {
ServiceClient<test_ros.AddTwoIntsRequest, test_ros.AddTwoIntsResponse> serviceClient;
try {
serviceClient = connectedNode.newServiceClient("add_two_ints", test_ros.AddTwoInts._TYPE);
} catch (ServiceNotFoundException e) {
throw new RosRuntimeException(e);
}
final test_ros.AddTwoIntsRequest request = serviceClient.newMessage();
request.setA(2);
request.setB(2);
serviceClient.call(request, new ServiceResponseListener<test_ros.AddTwoIntsResponse>() {
@Override
public void onSuccess(test_ros.AddTwoIntsResponse response) {
connectedNode.getLog().info(
String.format("%d + %d = %d", request.getA(), request.getB(), response.getSum()));
}
@Override
public void onFailure(RemoteException e) {
throw new RosRuntimeException(e);
}
});
}
}
| 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.serializer;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/** Abstract base implementation of a type serializer.
*/
public abstract class TypeSerializerImpl implements TypeSerializer {
protected static final Attributes ZERO_ATTRIBUTES = new AttributesImpl();
/** Tag name of a value element.
*/
public static final String VALUE_TAG = "value";
protected void write(ContentHandler pHandler, String pTagName, String pValue) throws SAXException {
write(pHandler, pTagName, pValue.toCharArray());
}
protected void write(ContentHandler pHandler, String pTagName, char[] pValue) throws SAXException {
pHandler.startElement("", TypeSerializerImpl.VALUE_TAG, TypeSerializerImpl.VALUE_TAG, ZERO_ATTRIBUTES);
if (pTagName != null) {
pHandler.startElement("", pTagName, pTagName, ZERO_ATTRIBUTES);
}
pHandler.characters(pValue, 0, pValue.length);
if (pTagName != null) {
pHandler.endElement("", pTagName, pTagName);
}
pHandler.endElement("", TypeSerializerImpl.VALUE_TAG, TypeSerializerImpl.VALUE_TAG);
}
protected void write(ContentHandler pHandler, String pLocalName, String pQName,
String pValue) throws SAXException {
pHandler.startElement("", TypeSerializerImpl.VALUE_TAG, TypeSerializerImpl.VALUE_TAG, ZERO_ATTRIBUTES);
pHandler.startElement(XmlRpcWriter.EXTENSIONS_URI, pLocalName, pQName, ZERO_ATTRIBUTES);
char[] value = pValue.toCharArray();
pHandler.characters(value, 0, value.length);
pHandler.endElement(XmlRpcWriter.EXTENSIONS_URI, pLocalName, pQName);
pHandler.endElement("", TypeSerializerImpl.VALUE_TAG, TypeSerializerImpl.VALUE_TAG);
}
} | 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.serializer;
import java.io.OutputStream;
import org.apache.ws.commons.serialize.XMLWriter;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.common.XmlRpcStreamConfig;
import org.xml.sax.ContentHandler;
/** This factory is responsible for creating instances of
* {@link org.apache.ws.commons.serialize.XMLWriter}.
*/
public interface XmlWriterFactory {
/** Creates a new instance of {@link ContentHandler},
* writing to the given {@link java.io.OutputStream}.
* @return A SAX handler, typically an instance of
* {@link XMLWriter}.
* @param pStream The destination stream.
* @param pConfig The request or response configuration.
* @throws XmlRpcException Creating the handler failed.
*/
public ContentHandler getXmlWriter(XmlRpcStreamConfig pConfig,
OutputStream pStream) throws XmlRpcException;
}
| 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.serializer;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A {@link TypeSerializer} for longs.
*/
public class I8Serializer extends TypeSerializerImpl {
/** Tag name of an i8 value.
*/
public static final String I8_TAG = "i8";
/** Fully qualified name of an i8 value.
*/
public static final String EX_I8_TAG = "ex:i8";
public void write(ContentHandler pHandler, Object pObject) throws SAXException {
write(pHandler, I8_TAG, EX_I8_TAG, pObject.toString());
}
}
| 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.serializer;
import java.util.List;
import org.apache.xmlrpc.common.TypeFactory;
import org.apache.xmlrpc.common.XmlRpcStreamConfig;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A {@link TypeSerializer} for lists.
*/
public class ListSerializer extends ObjectArraySerializer {
/** Creates a new instance.
* @param pTypeFactory The factory being used for creating serializers.
* @param pConfig The configuration being used for creating serializers.
*/
public ListSerializer(TypeFactory pTypeFactory, XmlRpcStreamConfig pConfig) {
super(pTypeFactory, pConfig);
}
protected void writeData(ContentHandler pHandler, Object pObject) throws SAXException {
List data = (List) pObject;
for (int i = 0; i < data.size(); i++) {
writeObject(pHandler, data.get(i));
}
}
} | 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.serializer;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A {@link TypeSerializer} for BigDecimal.
*/
public class BigDecimalSerializer extends TypeSerializerImpl {
/** Tag name of a BigDecimal value.
*/
public static final String BIGDECIMAL_TAG = "bigdecimal";
private static final String EX_BIGDECIMAL_TAG = "ex:" + BIGDECIMAL_TAG;
public void write(ContentHandler pHandler, Object pObject) throws SAXException {
write(pHandler, BIGDECIMAL_TAG, EX_BIGDECIMAL_TAG, pObject.toString());
}
}
| 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.serializer;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A {@link TypeSerializer} for bytes.
*/
public class I1Serializer extends TypeSerializerImpl {
/** Tag name of an i1 value.
*/
public static final String I1_TAG = "i1";
/** Fully qualified name of an i1 value.
*/
public static final String EX_I1_TAG = "ex:i1";
public void write(ContentHandler pHandler, Object pObject) throws SAXException {
write(pHandler, I1_TAG, EX_I1_TAG, pObject.toString());
}
}
| 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.serializer;
import org.apache.ws.commons.serialize.DOMSerializer;
import org.w3c.dom.Node;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** The node serializer is serializing a DOM node.
*/
public class NodeSerializer extends ExtSerializer {
private static final DOMSerializer ser = new DOMSerializer();
static {
ser.setStartingDocument(false);
}
/** The local name of a dom tag.
*/
public static final String DOM_TAG = "dom";
protected String getTagName() { return DOM_TAG; }
protected void serialize(ContentHandler pHandler, Object pObject) throws SAXException {
ser.serialize((Node) pObject, pHandler);
}
}
| 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.serializer;
import org.apache.ws.commons.util.XsDateTimeFormat;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A {@link TypeSerializer} for date values.
*/
public class CalendarSerializer extends TypeSerializerImpl {
private static final XsDateTimeFormat format = new XsDateTimeFormat();
/** Tag name of a BigDecimal value.
*/
public static final String CALENDAR_TAG = "dateTime";
private static final String EX_CALENDAR_TAG = "ex:" + CALENDAR_TAG;
/** Tag name of a date value.
*/
public static final String DATE_TAG = "dateTime.iso8601";
public void write(ContentHandler pHandler, Object pObject) throws SAXException {
write(pHandler, CALENDAR_TAG, EX_CALENDAR_TAG, format.format(pObject));
}
}
| 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.serializer;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A <code>TypeSerializer</code> is able to write a parameter
* or result object to the XML RPC request or response.
*/
public interface TypeSerializer {
/** Writes the object <code>pObject</code> to the SAX handler
* <code>pHandler</code>.
* @param pHandler The destination handler.
* @param pObject The object being written.
* @throws SAXException Writing the object failed.
*/
void write(ContentHandler pHandler, Object pObject) throws SAXException;
}
| 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.serializer;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A {@link TypeSerializer} for BigInteger.
*/
public class BigIntegerSerializer extends TypeSerializerImpl {
/** Tag name of a BigDecimal value.
*/
public static final String BIGINTEGER_TAG = "biginteger";
private static final String EX_BIGINTEGER_TAG = "ex:" + BIGINTEGER_TAG;
public void write(ContentHandler pHandler, Object pObject) throws SAXException {
write(pHandler, BIGINTEGER_TAG, EX_BIGINTEGER_TAG, pObject.toString());
}
}
| 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.serializer;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import org.apache.ws.commons.serialize.XMLWriter;
import org.apache.ws.commons.serialize.XMLWriterImpl;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.common.XmlRpcStreamConfig;
import org.xml.sax.ContentHandler;
/** The default instance of {@link XmlWriterFactory} creates
* instances of {@link org.apache.ws.commons.serialize.XMLWriterImpl}.
* This works for any Java version since 1.2
*/
public class BaseXmlWriterFactory implements XmlWriterFactory {
protected XMLWriter newXmlWriter() {
return new XMLWriterImpl();
}
public ContentHandler getXmlWriter(XmlRpcStreamConfig pConfig, OutputStream pStream)
throws XmlRpcException {
XMLWriter xw = newXmlWriter();
xw.setDeclarating(true);
String enc = pConfig.getEncoding();
if (enc == null) {
enc = XmlRpcStreamConfig.UTF8_ENCODING;
}
xw.setEncoding(enc);
xw.setIndenting(false);
xw.setFlushing(true);
try {
xw.setWriter(new BufferedWriter(new OutputStreamWriter(pStream, enc)));
} catch (UnsupportedEncodingException e) {
throw new XmlRpcException("Unsupported encoding: " + enc, e);
}
return xw;
}
}
| 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.serializer;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A {@link TypeSerializer} for doubles.
*/
public class DoubleSerializer extends TypeSerializerImpl {
/** Tag name of a double value.
*/
public static final String DOUBLE_TAG = "double";
public void write(ContentHandler pHandler, Object pObject) throws SAXException {
write(pHandler, DOUBLE_TAG, pObject.toString());
}
} | 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.serializer;
import org.apache.ws.commons.serialize.CharSetXMLWriter;
import org.apache.ws.commons.serialize.XMLWriter;
/** An implementation of {@link org.apache.xmlrpc.serializer.XmlWriterFactory},
* which creates instances of
* {@link org.apache.ws.commons.serialize.CharSetXMLWriter}.
*/
public class CharSetXmlWriterFactory extends BaseXmlWriterFactory {
protected XMLWriter newXmlWriter() {
return new CharSetXMLWriter();
}
}
| 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.serializer;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A {@link TypeSerializer} for floats.
*/
public class FloatSerializer extends TypeSerializerImpl {
/** Tag name of a float value.
*/
public static final String FLOAT_TAG = "float";
/** Fully qualified name of a float value.
*/
public static final String EX_FLOAT_TAG = "ex:float";
public void write(ContentHandler pHandler, Object pObject) throws SAXException {
write(pHandler, FLOAT_TAG, EX_FLOAT_TAG, pObject.toString());
}
}
| 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.serializer;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A {@link TypeSerializer} for integers.
*/
public class I4Serializer extends TypeSerializerImpl {
/** Tag name of an int value.
*/
public static final String INT_TAG = "int";
/** Tag name of an i4 value.
*/
public static final String I4_TAG = "i4";
public void write(ContentHandler pHandler, Object pObject) throws SAXException {
write(pHandler, I4_TAG, pObject.toString());
}
} | 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.serializer;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A {@link TypeSerializer} for shorts.
*/
public class I2Serializer extends TypeSerializerImpl {
/** Tag name of an i2 value.
*/
public static final String I2_TAG = "i2";
/** Fully qualified name of an i2 value.
*/
public static final String EX_I2_TAG = "ex:i2";
public void write(ContentHandler pHandler, Object pObject) throws SAXException {
write(pHandler, I2_TAG, EX_I2_TAG, pObject.toString());
}
}
| 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.serializer;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/** A {@link TypeSerializer} for null values.
*/
public class NullSerializer extends TypeSerializerImpl {
/** Tag name of a nil value.
*/
public static final String NIL_TAG = "nil";
/** Qualified tag name of a nil value.
*/
public static final String EX_NIL_TAG = "ex:nil";
public void write(ContentHandler pHandler, Object pObject) throws SAXException {
pHandler.startElement("", VALUE_TAG, VALUE_TAG, ZERO_ATTRIBUTES);
pHandler.startElement(XmlRpcWriter.EXTENSIONS_URI, NIL_TAG, EX_NIL_TAG, ZERO_ATTRIBUTES);
pHandler.endElement(XmlRpcWriter.EXTENSIONS_URI, NIL_TAG, EX_NIL_TAG);
pHandler.endElement("", VALUE_TAG, VALUE_TAG);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.