About this task
To simplify building code to interact with the REST API,
JAXB can be run on the schema to automatically generate classes that
represent the REST request, response and other related classes.
Attention: For another example, you can install the PlantsByWebSphere
Ajax Edition for CEA (PlantsByWebSphereAjax) sample application. With
this sample application, you can install, view, and use the CEA widgets
to see how they actually work in an online application. For more
information about the sample application, see the supporting documentation
that is provided in the PlantsByWebSphere directory of the CEA samples
package that you can download from the
WebSphere® Application Server
Samples
page. Additionally,
read about setting up and using the communications enabled application
samples.
package sample.code;
import java.util.Date;
import com.ibm.ws.commsvc.servlet.jaxb.*;
public class SampleCode {
public static final String rootUrl = "http://localhost:9080/CommServlet/";
public void runSample() {
String url = null;
HttpRequest httpRequest = null;
CommRestResponse callerResponse = null;
CommRestResponse calleeResponse = null;
CommRestRequest restRequest = null;
try {
// Enable collaboration for caller.
url = rootUrl + "collaborationSession";
httpRequest = new HttpRequest("PUT", url, null);
callerResponse = httpRequest.send();
// Start up collaboration from the callee using peer uri.
url = rootUrl + callerResponse.getForPeerCollaborationUri();
httpRequest = new HttpRequest("GET", url, null);
calleeResponse = httpRequest.send();
// Wait for collaboration establishment
waitForCollaborationEstablishment(calleeResponse.getCollaborationServiceUri());
waitForCollaborationEstablishment(callerResponse.getCollaborationServiceUri());
// Send data from callee to caller
url = rootUrl + calleeResponse.getEventUri();
restRequest = new CommRestRequest();
restRequest.setCollaborationData("test message");
httpRequest = new HttpRequest("POST", url, restRequest);
calleeResponse = httpRequest.send();
// Fetch data on the caller.
calleeResponse = waitForDataEvent(callerResponse.getEventUri());
if (calleeResponse.getEventList().getEvents().get(0).getData().equals("test message"))
System.out.println("Successfully exchanged collaboration data.");
// End collaboration from caller.
url = rootUrl + callerResponse.getCollaborationServiceUri();
httpRequest = new HttpRequest("DELETE", url, null);
callerResponse = httpRequest.send();
} catch (Exception e) {
System.out.println("Error occurred: " + e);
}
}
// Utility method which waits for a collaboration established event.
public boolean waitForCollaborationEstablishment (String uriExtension) {
String url = null;
HttpRequest request = null;
CommRestResponse response = null;
boolean success = false;
long startTime = System.currentTimeMillis();
while ((success == false) && ((System.currentTimeMillis() - startTime) < 10000)) {
try {
url = rootUrl + uriExtension;
request = new HttpRequest("GET", url, null);
response = request.send();
success = response.getCollaborationStatus().equals("ESTABLISHED");
if (success == false)
Thread.sleep(250);
} catch (Exception e) {
break;
}
}
return success;
}
// Get an event without specifying anything extra in the request.
public CommRestResponse waitForDataEvent(String eventUri) throws Exception {
EventList eventList = null;
Event event = null;
boolean foundEvent = false;
CommRestResponse restResponse = null;
Date startDate = new Date();
String url = rootUrl + eventUri;
HttpRequest httpRequest = new HttpRequest("GET", url, null);
for (int i = 0; i < 5; i++) {
// Fetch status on the call and determine if any events came back.
restResponse = httpRequest.send();
eventList = restResponse.getEventList();
if (eventList != null) {
// Iterate the events looking for a data event.
for (int j=0; j<eventList.getEvents().size(); j++) {
event = eventList.getEvents().get(j);
if (event.getType() == EventType.DATA_EVENT) {
foundEvent = true;
break; // Break out of inner loop of events.
}
}
if (foundEvent)
break; // Break out of outer loop waiting for events.
}
Date currentDate = new Date();
if ((currentDate.getTime() - startDate.getTime()) > 5000)
break;
Thread.sleep(1000);
}
return restResponse;
}
}
package sample.code;
import java.io.*;
import java.net.*;
import javax.xml.bind.*;
import com.ibm.ws.commsvc.servlet.jaxb.*;
public class HttpRequest {
private String method = null;
private URL url = null;
private CommRestRequest restRequest = null;
private String requestBody = "";
public static Unmarshaller xmlResponseUnmarshaller = null;
public static Marshaller xmlRequestMarshaller = null;
// Static block to set up the XML marshalled and unmarshaller.
static {
try {
JAXBContext jc = JAXBContext.newInstance((new CommRestResponse()).getClass().getPackage().getName());
xmlResponseUnmarshaller = jc.createUnmarshaller();
xmlRequestMarshaller = jc.createMarshaller();
} catch (Exception e) {
System.out.println("Error setting up XML marshaller or unmarshaller. " + e);
}
}
// Constructor
public HttpRequest(String inputMethod, String inputUrl, CommRestRequest inputRequest) throws Exception {
method = inputMethod;
url = new URL(inputUrl);
restRequest = inputRequest;
if (restRequest != null)
requestBody = marshalRestRequest(restRequest);
}
// Send the request and return the response in object form.
public CommRestResponse send() throws Exception {
// Set up the connection.
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod(method);
connection.setUseCaches(false);
connection.setDoInput(true);
if (method.equals("POST") || method.equals("PUT")) {
connection.setRequestProperty("Content-Type", "text/html");
connection.setDoOutput(true);
// Send the request.
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(requestBody);
out.flush();
out.close();
} else {
// Must set this to false for GET (or it will default to POST) and DELETE.
connection.setDoOutput(false);
}
// Read the response.
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = new String();
String line = reader.readLine();
while(null != line) {
response += line;
line = reader.readLine();
}
reader.close();
// Convert the string response into an object form.
return unmarshalRestResponse(response);
}
// Marshal the CommRestRequest object into XML formatted text.
public static synchronized String marshalRestRequest(CommRestRequest request) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
xmlRequestMarshaller.marshal(request, outputStream);
return outputStream.toString();
}
// Unmarshal the XML text into a CommRestResponse object.
private static synchronized CommRestResponse unmarshalRestResponse(String text) throws JAXBException {
return (CommRestResponse)xmlResponseUnmarshaller.unmarshal(new ByteArrayInputStream(text.getBytes()));
}
}