The Client Application
Having deployed and registered the Service Type, we are now ready to use it. There are two different techniques we can use to access this Service from a client:
| • | The Service API |
| • | GridServer-generated proxy |
Let us first demonstrate accessing the Service using the Service API in Java. Refer to the Javadocs on the Documentation panel in the top navigation bar of the Administration Tool. The Service class is used to access the Service either synchronously or asynchronously. This section consists largely of small code snippets. All of the code can be found in a single class, example.adder.client.AdderClient.
Only a few lines of code are needed to use the JavaAdder Service:
// Create a Service instance of JavaAdderExample
Service s = ServiceFactory.getInstance().createService("JavaAdderExample");
// Perform Synchronous add
Object[] arguments = new Object[] { new Double(5), new Double(6) };
Double sum = (Double)s.execute("add", arguments);
System.out.println("Result of add: " + sum);
The first line gets an instance of the ServiceFactory class and calls its createService method to create a Service instance for the Service. If you try to create a Service Type whose name was not registered, createService throws a GridServerException.
The second line prepares the arguments to be submitted to the Service, two Doubles (note the use of the primitive wrapper object). The third line executes the add method with the given argument list and blocks until the method completes and its return value makes its way back to the client. If the remote method throws an exception, or an error occurs in the course of processing the request, an exception is thrown. GridServerException might wrap another exception; use its getCause method to obtain the wrapped exception.
A Java client does not stop automatically, and pends after submitting Services and collecting results. Instead of calling System.exit() to stop the client, you can set a property to change this behavior. Add this to your code:
DriverManager.setProperty(DriverManager.IS_DAEMON,
Boolean.TRUE.toString());
When this property is set to true, all client threads are daemon threads, meaning that the allow the process to shut down when all threads have shut down.