Example: Implementing a client-side adapter
The CommandTarget interface declares one method, executeCommand, which the client implements. The executeCommand method takes a TargetableCommand object as input; it also returns a TargetableCommand.
A client-side implementation of the executeCommand method
This example shows the implementation of the method used in the client-side adapter. This implementation does the following:
- Serializes the command it receives
- Creates an HTTP connection to the servlet
- Creates input and output streams, to handle the command as it is sent to the server and returned
- Places the command on the output stream
- Sends the command to the server
- Retrieves the returned command from the input stream
- Returns the returned command to the caller of the executeCommand method
public TargetableCommand executeCommand(TargetableCommand command) throws CommandException { try { // Serialize the command byte[] array = serialize(command); // Create a connection to the servlet URL url = new URL ("http://" + hostName + "/servlet/com.ibm.websphere.command.servlet.CommandServlet"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); // Set the properties of the connection ... // Put the serialized command on the output stream OutputStream outputStream = httpURLConnection.getOutputStream(); outputStream.write(array); // Create a return stream InputStream inputStream = httpURLConnection.getInputStream(); // Send the command to the servlet httpURLConnection.connect(); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); // Retrieve the command returned from the servlet Object object = objectInputStream.readObject(); if (object instanceof CommandException) { throw ((CommandException) object); } // Pass the returned command back to the calling method return (TargetableCommand) object; } // Handle exceptions .... }
Related tasks
Use a command
Related Reference
Example: Running the command in the servlet
Example: Writing a command target (client-side adapter)
Reference topic
  Â