WAS v8.5 > End-to-end paths > Communications enabled applications

Share data across two sessions with REST APIs


Overview

We can build cobrowsing into applications using REST APIs. A cobrowsing session allows two web users to share the same browsing session using side-by-side modal windows. One user controls the session; the other user has no control, but can view the activity of the other user.

An understanding of the Representational State Transfer (REST) interface is needed to perform this task. REST is a network architecture that defines how resources on the Internet are accessed. REST is not a standard, but uses common Internet standards such as HTTP and HTML.

See the information on REST APIs in CEA for a complete reference to the REST API.

Communications enabled applications (CEA) enables application developers to add web interaction features into new and existing applications. Cobrowsing refers to two web users sharing the same browsing session.

It is not the same as screen sharing, but does have some similarities.

After a cobrowsing session is established, modal windows are displayed in both web browsers. The user controlling the session has the ability to scroll the web page, highlight and point to text, and enter data into forms. The other user has no control, but can see everything the other user is doing. This type of web collaboration is ideal for a customer service representative working with a customer, where a quick demonstration would be more effective than an explanation on the phone. This feature provides customizable widgets that allow application developers to are import the web collaboration capability into a new or existing application. The widget communicates with the application server through a REST interface.

  1. Enable the system application.
  2. Develop a new application that calls the REST interface.
  3. Install and start the new application.
  4. Test the new application.


Procedure

  1. Enable the system application.

    The system application owns the REST interface. Update the configuration for each server running CEA.

    1. Access the CEA settings panel in the dmgr console.

      • In a single-server environment, click Servers > Server Types > WebSphere application servers > server_name > CEA.

      • In a clustered environment, click Servers > Clusters > WebSphere application server clusters > server_cluster > CEA.

        Because servers in a cluster are clones of each other, you only need to make configuration changes from the main cluster panel for the cluster, not for each individual server in the cluster.

    2. Ensure the check box labeled Enable communications service is checked.


  2. Develop a new application that calls the REST interface.

    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.

    For another example, we can install the PlantsByWebSphere Ajax Edition for CEA (PlantsByWebSphereAjax) sample application. With this sample application, we 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 provided in the PlantsByWebSphere directory of the CEA samples package that we can download from the 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()));
     }}


  3. Install and start the new application.


  4. Test the new application.

    1. From two separate systems, access the test application that has the ability to interact with the REST interface.

    2. On both systems, call the first REST interface, which enables collaboration.

    3. The response to each will include the URI that can be passed to the other to start the collaboration.

    4. From one system, call the start collaboration REST interface using the service URI returned on the other system.

    5. As a result, the collaboration interface displays in a dual-window browser. The two systems now have linked sessions and can interact.


    Results

    You have developed and deployed an application that is enabled with cobrowsing.


Related

Set up the communications enabled application samples
Samples documentation
REST APIs in CEA


+

Search Tips   |   Advanced Search