ThingWorx Edge Java SDK > Application Details > VirtualThing Component > Remote Services > Adding a Service Definition
  
Adding a Service Definition
To add a service definition, call the defineService method of the base VirtualThing. There are two defineService methods. One that takes a ServiceDefinition and one that takes the essential parameters of a ServiceDefinition.
defineService(ServiceDefinition serviceDefinition)
defineService(String name, String description, FieldDefinitionCollection parameterTypes,
FieldDefinition resultType, AspectCollection aspects)
The code for the following examples should be in the constructor of the extended VirtualThing (or a method called from the constructor). You can see from the examples below that the annotation methodology is much cleaner. Note that you need to override the processServiceRequest of the VirtualThing to check the name of the incoming ServiceDefinition and call the corresponding method. Here is code that does this:
public InfoTable processServiceRequest(ServiceDefinition serviceDefinition,
ValueCollection parameters) throws Exception {

InfoTable result = null;

if (serviceDefinition.getName().equals("Add")) {
Double sum = Add((Double)parameters.getValue("p1"),
(Double)parameters.getValue("p2"));
result = InfoTableUtilities.createInfoTableFromPrimitive(serviceDefinition.
getResultType().getName(), new NumberPrimitive(sum));
}

return result;
}
//Put this code in the constructor (or a method
//called from the constructor)

ServiceDefinition serviceDef = new ServiceDefinition(
"Add",
"Add two numbers");
FieldDefinitionCollection parameterFields =
new FieldDefinitionCollection();
parameterFields.addFieldDefinition(
new FieldDefinition(

"p1",
"The first addend of the operation",
BaseTypes.NUMBER)
);
parameterFields.addFieldDefinition(
new FieldDefinition(

"p2",
"The second addend of the operation",
BaseTypes.NUMBER)
);

FieldDefinition resultField = new FieldDefinition(
CommonPropertyNames.PROP_RESULT,
"The sum of the two parameters",
BaseTypes.NUMBER);

serviceDef.setParameters(parameterFields);
serviceDef.setResultType(resultField);
super.defineService(serviceDef);

The implementation of the ServiceDefinition will be just like any other method that is defined on the extended VirtualThing:
//Actual service definition

public Double Add(Double p1, Double p2) throws Exception
{ return p1 + p2; }
The processServiceRequest of the VirtualThing will need to be overridden in the extended VirtualThing to check the name of the incoming ServiceDefinition and call the appropriate method. There is no need to call the processServiceRequest of the VirtualThing since it only throws an exception.