Junos Space SDK > Developer Guides > Junos Space Application Developer Guide > Programming with the Junos Space SDK > Developing Junos Space Applications > Creating REST Services

Calling Internal and External REST Services from EJBs

This topic describes how to call REST Web services from EJBs hosted on or outside the Junos Space platform. Therefore, REST services can be categorized as:

You can call an application's REST API from an EJB using the JSServiceClient class. This class is responsible for constructing the HTTP request and carries the authorization and authentication credentials of the user invoking this REST API. For information about the JSServiceClient authentication, refer to the JSServiceClient Authentication Scenarios section of the "Calling a REST Service from REST APIs" topic.

Usage Example

Calling an Internal REST API from an EJB

/* The following API is part of the TestEJB stateless session bean.
 * This API demonstrates how to consume an Internal REST Web Service.
 */

public String getDevices(ApiContext apic, final String devices_url) {
  // Note: ApiContext is required for any service which uses JSServiceClient
  // to forward http
  // requests to other Junos Space URL's from EJB layer.
  InternalApiContext iac = (InternalApiContext) apic;

  // InternalApiContext provides method to get the base URL
  String url = iac.getBaseUrl() + devices_url;

  // Create an instance of JSServiceClient using ApiContext
  JSServiceClient client = new JSServiceClient(apic);

  // There is no need to set the credentials manually,
  // because they are handled automatically by the Client framework being used
  // here.

  /**
   * ApiContext provides an API to get username and password. The API Usage is
   * AuthorizationContext actxt = iac.getAuthCtx(); 
   * actxt.getUsername(); // Get Username
  /**Note that the password is always either null or blank for any Junos Space hosted application**/  
   * actxt.getPassword(); // Get password
   */

  // Create an HttpMethod instance.
  HttpMethod method = new GetMethod(url);

  // Provide custom retry handler if necessary
  method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
      new DefaultHttpMethodRetryHandler(3, false));

  String devicesCollection = null;
  try {
      // Execute the method using the JSServiceClient.
      int statusCode = client.httpClient().executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        logger.error("Method failed: " + method.getStatusLine());
      }
      // Read the response body.
      byte[] responseBody = method.getResponseBody();
      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      devicesCollection = new String(responseBody);
      logger.debug(devicesCollection);
  } catch (HttpException e) {
      logger.error("Fatal protocol violation: " + e.getMessage());
  } catch (IOException e) {
      logger.error("Fatal transport error: " + e.getMessage());
  } finally {
      // Release the connection.
      method.releaseConnection();
  }
  return devicesCollection;
}

Calling an External REST API from an EJB

/* The following API is part of the TestEJB stateless session bean.
 * This API demonstrates how to set up URL and credentials to consume an External REST Web Service.
 */

public String getDevices(ApiContext apic) {
  // Note: ApiContext is required for any service which uses JSServiceClient
  // to forward http
  // requests to other Junos Space URL's from EJB layer. 	
  InternalApiContext iac = (InternalApiContext) apic; 
  /**
   * InternalApiContext is used here to set the URL and the credentials e.g.
   * Suppose the EJB can be accessed via the URL
   * http://space.com:8080/api/space/TESTRest using the credentials:
   * space/pass2345 And you want to invoke a service via the URL
   * http://myspace.com:8080/api/myspace/MyRest using the credentials:
   * myspace/pass1234
   * 
   */

  // 1. Set up AuthorizationContext 	
  AuthorizationContext actxt = new AuthorizationContext();
  actxt.setUsername("myspace");
  actxt.setPassword("pass1234"); 	

  // 2. Set up base Url 	
  String baseUrl = "http://myspace.com:8080"; 	
  iac.setAuthDetailsAndBaseUrl(actxt, baseUrl);
  String url = iac.getBaseUrl() + "/api/myspace/MyRest";

  // Create an instance of JSServiceClient using ApiContext 
  JSServiceClient client = new JSServiceClient(apic); 

  // Create an HttpMethod instance. 
  HttpMethod method = new GetMethod(url); 

  // Provide custom retry handler if necessary 
  method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
      new DefaultHttpMethodRetryHandler(3, false)); 
  String myCollection = null;
  try {
      // Execute the method using the JSServiceClient. 
      int statusCode = client.httpClient().executeMethod(method); 
      if (statusCode != HttpStatus.SC_OK) {
        logger.error("Method failed: " + method.getStatusLine());
      }
      // Read the response body. 
      byte[] responseBody = method.getResponseBody(); 
      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      myCollection = new String(responseBody);
      logger.debug(myCollection);
  } catch (HttpException e) {
      logger.error("Fatal protocol violation: " + e.getMessage());
  } catch (IOException e) {
      logger.error("Fatal transport error: " + e.getMessage());
  } finally {
      // Release the connection. 
      method.releaseConnection(); 
  }
  return myCollection;
}

Note: For more information on ApiContext, refer to the ApiContext section.

Passing the API Context When Calling the EJB from the REST API.

public String getDevices() {
 UriContext uric = RestEasyProviderFactory.getContextData(UriContext.class);

 ApiContext apic = uric.getApicontext();

 final String DEVICES_URL = "/api/space/device-management/devices";
 //TestEJB is a stateless session bean having getDevices API 
 TestEJB tejb = JxServiceLocator.lookup("TestEJB");
 return tejb.getDevices(apic,DEVICES_URL);  
}