Junos Space SDK > Developer Guides > Junos Space Application Developer Guide > Programming with the Junos Space SDK > Reference Applications > HelloSpace > HelloSpace Code Walk-Through

HTTP GET Method - HelloSpace


This topic explains the REST GET method. In the HelloSpace application, the "getAllDevices" method is RESTified to get all the devices. Firstly, an EJB method is created and, then the same method is RESTified. The method is validated by invoking the REST API and generating results through the REST client. The procedure for the EJB implementation and for RESTification, and validation of the method using the REST client is given below.

Step 1: Examine the EJB method for "getAllDevices".

This step creates an EJB method "getAllDevices" to get all the devices. It shows how to invoke the Junos Space API and retrieve the data using the REST methods. You need to pass your user credentials at the EJB instance creation of the HTTPClient and issue a "GET" request.

Example of an EJB Interface

public interface HelloSpace {
	/**
	* Returns list of devices listing their ID ,IP and Name
	*
	* @param apic Reference of ApiContext
	* 
	* @param ctx Reference of PagingContext
	* 
	* @param queryString Reference of query String
	* 
	* @return PagingResult<Device> paging result of list of Devices
	*/
	public PagingResult<Device> getAllDevices(ApiContext apic, PagingContext ctx, String queryString);
 
}

Example of an EJB Implementation (using Jersey Client)

public class HelloSpaceImpl implements HelloSpace {
	private static final int CONNECT_TIMEOUT = 5000; 
	private static final int READ_TIMEOUT = 300000; 
	private static Client jerseyClient;
	private static final String USER = "super";
	private static final String PASSWORD = "juniper123";
	/**
	* Description: This method returns a list of devices listing their
	* ID, IP and Name with pagination applied on the result
	* 
	* @param apic Reference of ApiContext
	* 
	* @param ctx Reference of PagingContext
	* 
	* @param queryString Reference of query String
	* 
	* @return PagingResult<Device> paging result of list of devices
	* 
	*/
	public PagingResult<Device> getAllDevices(ApiContext apiCtx,
			PagingContext pagingCtx, String queryString) {
		// Set up user credentials
		setupHttpClient(apiCtx);
		InternalApiContext iac = (InternalApiContext) apiCtx;
		String url = iac.getBaseUrl() + DEVICES_URL;
		if (queryString != null && queryString.length() > 0)
			url = url + "?" + queryString;
		// Get response from the service
		ClientResponse response = get(url, JSON_DEVICES);
		if (response != null) {
			int status = response.getClientResponseStatus().getStatusCode();
			if (status == Response.Status.BAD_REQUEST.getStatusCode()
					|| status == Response.Status.NOT_FOUND.getStatusCode()
					|| status == Response.Status.NO_CONTENT.getStatusCode()) {

				return null;
			} else {
				return getJSONDeviceObject(iac.getBaseUrl(), response,
						pagingCtx);
			}
		}
		return null;
	}

	/**
	* This method is used to create a JSServiceClient instance. 
	* The APIContext will provide the User credentials.
	* @param apiCtx
	* Reference of ApiContext - used for passing in user credentials
	* and base url.
	* 				
	*/
 	private void setupHttpClient(ApiContext apic) {
		// Create an instance of JSServiceClient using ApiContext
		try {
			JSServiceClient client = new JSServiceClient(apic);
			// Get an instance of Jersey Client
			jerseyClient = client.jerseyClient();
		} catch (Exception exc) {
			logger.error(ERROR_INITCLIENT);
			logger.error(exc);
		}
	}
}

Note: For more information about Jersey Client libraries, refer to the Consuming REST Services Using Jersey Client section.

Step 2: Examine the RESTified code generated by the EJB-REST Wizard for "getAllDevices".

REST Interface for GET Method

@Path("devices")
@GET
@RBAC(type = { CRUDEnum.READ }, capability = { "HelloSpaceCap" })
@Produces({
         VendorConstants.APP_DATATYPE_PREFIX + ".devices+xml;version=1",
         VendorConstants.APP_DATATYPE_PREFIX + ".devices+json;version=1" })
public vnd.jssdk.hellospace.rest.v1.Devices getAllDevices(
                @Context UriContext param0);

REST Implementation for GET Method

/**
 * Method:getAllDevices
 * 
 * Description: This is an  auto generated method with stub
 * implementation which uses the net.juniper.jmp.hellospace.ejb.HelloSpace EJB bean and exposes
 * it's method with Rest web services interface.
 * @return net.juniper.jmp.hellospace.ejb.v1.Devices
 */
 
public net.juniper.jmp.hellospace.ejb.v1.Devices getAllDevices(UriContext param0, HttpServletRequest servletRequest) {
    net.juniper.jmp.hellospace.ejb.v1.Devices devices = null;
    net.juniper.jmp.PagingContext ctx = param0.getPagingCtxt();
    try {
        devices = new net.juniper.jmp.hellospace.ejb.v1.Devices();
        java.util.ArrayList 
restDevices = new java.util.ArrayList(); String urlStr; String queryStr = servletRequest.getQueryString(); if (queryStr != null) { urlStr = HOST_URL + DEVICE_URL + "?" + queryStr; } else { urlStr = HOST_URL + DEVICE_URL; } net.juniper.jmp.PagingResult ejbDeviceList = getBean().getAllDevices(ctx, urlStr); if (ejbDeviceList == null || ejbDeviceList.size() == 0) { logger.warn("No Devices found"); return null; } for (net.juniper.jmp.hellospace.ejb.Device device : ejbDeviceList) { net.juniper.jmp.hellospace.ejb.v1.Devices.Device restDevice = new net.juniper.jmp.hellospace.ejb.v1.Devices.Device(); copyComplexPropEjbToRestForDevices(restDevice, device); restDevices.add(restDevice); } devices.setDevices(restDevices); devices.setTotalSize(ejbDeviceList.getPagingContext().getTotalRecords()); } catch (WebApplicationException e) { throw e; } catch (Exception e) { throw new WebApplicationException(e); } finally { } return devices; }

DTO for "getAllDevices"

/*******************************************************************************
 * FILE NAME: Devices.java
 * PURPOSE:   These comments are auto generated
 *
 *
 * Revision History: 
 * DATE:                                                                  AUTHOR:              CHANGE:  
 * Thu Mar 24 10:56:03 IST 2011               Auto generated       Initial Version  
 * 
 * 
 ******************************************************************************/
/**
 * Class:Devices 
* Description:This type provides a collection of Devices. * * @MediaType * application/vnd.net.juniper.space.hello-space.devices+json;version=1 * * application/vnd.net.juniper.space.hello-space.devices+xml;version=1 * * */ @XmlType(name = "devices", propOrder = { "totalSize", "devices", "uri" }) @XmlRootElement(name = "devices") @XmlAccessorType(XmlAccessType.NONE) public class Devices { /** * Total number of results. This number may vary between calls. * */ @XmlAttribute(name = "size") private Integer totalSize; public Integer getTotalSize() { return totalSize; } public void setTotalSize(Integer totalSize) { this.totalSize = totalSize; } /** * This type is used in a collection of devices. */ @HATEOAS(uri = "/{id}") @XmlElement(name = "device") private java.util.Collection devices = null; /** * Link to Devices */ @HATEOAS(uri = "") @XmlAttribute(name = "uri") private String uri = null; /** * @param devices */ public void setDevices(java.util.Collection devices) { this.devices = devices; } /** * @return devices */ public java.util.Collection getDevices() { return devices; } /** * @param uri */ public void setUri(String uri) { this.uri = uri; } /** * @return uri */ public String getUri() { return uri; } /** * Class:Device
* Description:This type is used in a collection of Devices. * */ @XmlType(name = "device", propOrder = { "id", "platform", "uri", "ipAddr", "name" }) @XmlRootElement(name = "device") @XmlAccessorType(XmlAccessType.NONE) public static class Device { /** * Link to Device */ @HATEOAS(uri = "") @XmlAttribute(name = "uri") private String uri = null; /** * Device ID */ @XmlElement(name = "id") int id; /** * Device platform * * @Sortable * @Filterable */ @XmlElement(name = "platform") String platform; /** * Device IP * * @Sortable */ @XmlElement(name = "ipAddr") String ipAddr; /** * Device name * * @Sortable * @Filterable */ @XmlElement(name = "name") String name; /** * @param uri */ public void setUri(String uri) { this.uri = uri; } /** * @return uri */ public String getUri() { return uri; } /** * @param id */ public void setId(int id) { this.id = id; } /** * @return int */ public int getId() { return id; } /** * @param platform */ public void setPlatform(String platform) { this.platform = platform; } /** * @return String */ @Sortable(moAttrName = "platform") @Filterable(moAttrName = "platform") public String getPlatform() { return platform; } /** * @param ipAddr */ public void setIpAddr(String ipAddr) { this.ipAddr = ipAddr; } /** * @return String */ @Sortable(moAttrName = "ipAddr") public String getIpAddr() { return ipAddr; } /** * @param name */ public void setName(String name) { this.name = name; } /** * @return String */ @Sortable(moAttrName = "name") @Filterable(moAttrName = "name") public String getName() { return name; } } }

Step 3: Invoke the REST API using REST Client

You have to use the REST Client to invoke the REST API created in Step 2. It is assumed that the application is built and deployed on the Junos Space SDK. For building and deploying applications, refer to the Building and Deploying HelloSpace section.

HTTP GET Request

GET http://127.0.0.1:8080/api/hello-space/devices?sort=name&dir=DESC 
HTTP/1.1 Host: <host-name&gt:<port> 
Authorization: Basic c3VwZXI6anVuaXBlcjEyMw==
Accept: application/vnd.net.juniper.space.hello-space.devices+xml;version=1

HTTP GET Response


<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<devices uri="/api/hello-space/devices" size="3">
<device uri="/api/hello-space/devices/229379">
        <id>229379</id>
        <platform>SRX210-HM</platform>
        <ipAddr>192.168.1.1</ipAddr>
        <name>Veera-Srx210hm-61.61</name>
        </device>
<device uri="/api/hello-space/devices/229383">
        <id>229383</id>
        <platform>EX</platform>
        <ipAddr>192.168.1.3</ipAddr>
        <name>junos-host</name>
</device>
<device uri="/api/hello-space/devices/229387">
        <id>229387</id>
        <platform>M10</platform>
        <ipAddr>192.168.1.2</ipAddr>
        <name>junos-host</name>
</device>
</devices>