uCosminexus Application Server, Web Service Development Guide
Create Implementation Class of the client that uses client APIs for RESTful Web Services.
An example is as follows:
package com.sample.client;
import java.net.URI;
import java.net.URLEncoder;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import com.cosminexus.jersey.api.client.Client;
import com.cosminexus.jersey.api.client.WebResource;
import com.cosminexus.jersey.api.client.ClientRequest;
import com.cosminexus.jersey.api.client.ClientResponse;
import com.cosminexus.jersey.api.client.config.ClientConfig;
import com.cosminexus.jersey.api.client.config.DefaultClientConfig;
import com.cosminexus.jersey.api.client.ClientHandlerException;
import com.cosminexus.jersey.api.json.JSONConfiguration;
import javax.ws.rs.core.Cookie;
//Sample: Executing the Web resource client
public class SampleClient {
public static void main(String[] args) {
final String HOST = args[0];
final String PORT = args[1];
SampleClient sampleClient = new SampleClient();
try{
sampleClient.demonstration13(HOST, PORT);
sampleClient.demonstration14(HOST, PORT);
sampleClient.demonstration15(HOST, PORT);
System.out.println("\n----- Successfully Ended -----");
}catch(Exception e){
//Display a detailed exception message
System.out.println(e.getMessage());
}
}
private void demonstration13(String HOST, String PORT) {
System.out.println("\n Demonstration 13 started.");
System.out.println(" This demonstrates how to use Client API " +
"to receive a response as a ClientResponse.");
System.out.println(" This demonstrates usage of @Encoded at " +
"@CookieParam. \n Automatic URI decoding should be disabled.");
String url = null;
Client client = null;
ClientResponse response = null;
String responseEntity = "";
Map<String, List<String>> headers = null;
int status;
//Call the Web resource
try {
//Set a URI of the Web resource to be called
url = new String("http://" + HOST + ":" + PORT+
"/tutorial/root/getCookieParam");
Cookie cookie = new Cookie("cookie", "cookie%20value");
//Create a client object to use client APIs
client = Client.create();
//Create and send an HTTP request and receive an HTTP response
//- Create a WebResource object from the Client object
//- Set "cookie=cookie%20value" to the Cookie header
//- Send an HTTP GET request and
// receive an HTTP response as ClientResponse
response = client.resource(url)
.cookie(cookie)
.get(ClientResponse.class);
//Acquire headers of the HTTP response
headers = response.getHeaders();
//Acquire the status code of the HTTP response
status = response.getStatus();
//Acquire the entity of the HTTP response
responseEntity = response.getEntity(String.class);
}catch (Exception e) {
System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
//Display stack trace
e.printStackTrace();
throw new RuntimeException(" Demonstration 13 failed.");
}
System.out.println(" The target URL is \"" + url + "\".");
System.out.println(" The HTTP method is " + "\"GET\"" + ".");
System.out.println(" Connection and interaction ended successfully.");
//Set the expected value of the status code and entity
int statusExpect = 200;
String responseEntityExpect = "CookieParam: cookie%20value";
//Check if the status code and the entity have the expected values
if (status == statusExpect
& responseEntity.equals(responseEntityExpect)) {
//Display the header of the HTTP response
System.out.println(" Response headers are " + headers.toString() + ".");
//Display the entity of the HTTP response
System.out.println(" Response entity is " + responseEntity + ",");
System.out.println(" which means target resource completed " +
"the process described above without any problem.");
System.out.println(" Demonstration 13 ended successfully.");
}else {
System.out.println(" The response is not as expected.");
throw new RuntimeException(" Demonstration 13 failed.");
}
}
private void demonstration14(String HOST, String PORT) {
System.out.println("\n Demonstration 14 started.");
System.out.println(" This demonstrates how to send a ClientRequest " +
"and receive a ClientResponse by using " +
"Client#handle(ClientRequest request).");
System.out.println(" This demonstrates usage of @Consumes and " +
"@Produces.");
URI url = null;
Client client = null;
ClientRequest.Builder requestBuilder = null;
ClientRequest request = null;
ClientResponse response = null;
String responseEntity = "";
Map<String, List<String>> headers = null;
int status;
//call the Web resource
try {
//Set the URI of the Web resource to be called
url = new URI("http://" + HOST + ":" + PORT+ "/tutorial/root");
//Create an entity of the HTTP request
String data = URLEncoder.encode("form", "UTF-8") + "="
+ URLEncoder.encode("formValue", "UTF-8");
//crate a Client object to use the client APIs
client = Client.create();
//Create a ClientRequest.Builder object
requestBuilder = ClientRequest.create();
// Set "application/x-www-form-urlencoded"
//to the "Content-Type" header of the HTTP request
//- Set the entity of the HTTP request
requestBuilder.type("application/x-www-form-urlencoded")
.entity(data);
//Create ClientRequest from ClientRequest.Builder
request = requestBuilder.build(url, "POST");
//Call the Client#handle() method and send the HTTP POST //request
//Receive an HTTP response as ClientResponse
response = client.handle(request);
//Acquire headers of the HTTP response
headers = response.getHeaders();
//Acquire the status code of the HTTP response
status = response.getStatus();
//Acquire the entity of the HTTP response
responseEntity = response.getEntity(String.class);
}catch (ClientHandlerException e) {
System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
//Display stack trace
e.printStackTrace();
throw new RuntimeException(" Demonstration 14 failed.");
}catch (Exception e) {
System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
// Display stack trace
e.printStackTrace();
throw new RuntimeException(" Demonstration 14 failed.");
}
System.out.println(" The target URL is \"" + url + "\".");
System.out.println(" The HTTP method is " + "\"POST\"" + ".");
System.out.println(" Connection and interaction ended successfully.");
//Set the expected values of the status code and the entity
int statusExpect = 200;
String responseEntityExpect = "<FormParam>formValue</FormParam>";
//Check if the status code and the entity have the expected values
if (status == statusExpect
& responseEntity.equals(responseEntityExpect)) {
//Display headers of the HTTP response
System.out.println(" Response headers are " + headers.toString() + ".");
//Display the entity of the HTTP response
System.out.println(" Response entity is " + responseEntity + ",");
System.out.println(" which means target resource completed " +
"the process described above without any problem.");
System.out.println(" Demonstration 14 ended successfully.");
}else {
System.out.println(" The response is not as expected.");
throw new RuntimeException(" Demonstration 14 failed.");
}
}
private void demonstration15(String HOST, String PORT) {
System.out.println("\n Demonstration 15 started.");
System.out.println(" This demonstrates JSON support of CJR.");
System.out.println(" This demonstrates POJO and JSON mapping.");
String url = null;
Client client = null;
CustomType response = null;
//Call the Web resource
try {
//Set the URI of the Web resource to be called
url = new String("http://" + HOST + ":" + PORT +
"/tutorial/root/PojoJsonMapping");
//Specify settings to enable JSON POJO mapping
ClientConfig cc = new DefaultClientConfig();
cc.getFeatures()
.put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
//Create a Client object to use client APIs
//(Pass the ClientConfig object to enable the settings)
client = Client.create(cc);
//Create a CustomType object
CustomType record = new CustomType();
record.setName("Old Record Name");
List<Integer> grades = new ArrayList<Integer>();
grades.add(1);
grades.add(2);
grades.add(3);
record.setGrades(grades);
//Create an HTTP request
//-Create a WebResource object from the Client object
//-Set "application/json" to the Content-Type header
//-Set CustomType object to the entity
//-Send HTTP POST request and
//receive HTTP response as CustomType
response = client.resource(url)
.type("application/json")
.entity(record)
.post(CustomType.class);
}catch (Exception e) {
System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
//Display the stack trace
e.printStackTrace();
throw new RuntimeException(" Demonstration 15 failed.");
}
System.out.println(" The target URL is \"" + url + "\".");
System.out.println(" The HTTP method is " + "\"POST\"" + ".");
System.out.println(" Connection and interaction ended successfully.");
//Set the expected value of the entity
String responseNameExpect = "New Record Name";
List<Integer> responseGradesExpect = new ArrayList<Integer>();
responseGradesExpect.add(5);
responseGradesExpect.add(6);
responseGradesExpect.add(7);
//Check if the entity has the expected value
if (response.getName().equals(responseNameExpect)
& response.getGrades().equals(responseGradesExpect)) {
//Display the entity of the HTTP response
System.out.println(" Response is " + response.toString() + ",");
System.out.println(" which means target resource completed " +
"the process described above without any problem.");
System.out.println(" Demonstration 15 ended successfully.");
}else {
System.out.println(" The response is not as expected.");
throw new RuntimeException(" Demonstration 15 failed.");
}
}
private static class CustomType {
private String name;
private List<Integer> grade;
public CustomType() {
}
public CustomType (String name, List<Integer> grades){
this.name = name;
this.grade = grades;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Integer> getGrades() {
return grade;
}
public void setGrades(List<Integer> grades) {
this.grade = grades;
}
@Override
public String toString() {
return "Record [Name=" + name + ", Grades=" + grade.toString() + "]";
}
}
}
|
Save the created SampleClient.java in the c:\temp\jaxrs\works\tutorial\client\src\com\sample\client\ directory in the UTF-8 format.
All Rights Reserved. Copyright (C) 2013, Hitachi, Ltd.