View Javadoc
1   package ejava.examples.ejbwar.customer.client;
2   
3   import java.net.URI;
4   
5   
6   import javax.ws.rs.core.HttpHeaders;
7   import javax.ws.rs.core.MediaType;
8   import javax.ws.rs.core.Response;
9   import javax.ws.rs.core.UriBuilder;
10  
11  import org.apache.commons.logging.Log;
12  import org.apache.commons.logging.LogFactory;
13  import org.apache.http.HttpResponse;
14  import org.apache.http.client.HttpClient;
15  import org.apache.http.client.methods.HttpDelete;
16  import org.apache.http.client.methods.HttpGet;
17  import org.apache.http.client.methods.HttpPost;
18  import org.apache.http.entity.StringEntity;
19  import org.apache.http.util.EntityUtils;
20  
21  import ejava.examples.ejbwar.customer.bo.Customer;
22  import ejava.examples.ejbwar.customer.bo.CustomerRepresentation;
23  import ejava.examples.ejbwar.customer.bo.Customers;
24  import ejava.examples.ejbwar.customer.rs.CustomersResource;
25  
26  /**
27   * This class implements an HTTP Client interface to the customer 
28   * web application. All commands are through HTTP POST, GET, PUT, and DELETE
29   * methods to specific resource URIs for products and categories.
30   */
31  public class CustomerClientImpl implements CustomerClient {
32  	private static final Log log = LogFactory.getLog(CustomerClientImpl.class);
33  	private HttpClient client;
34  	/**
35  	 * Defines the HTTP URL for the WAR that hosts the JAX-RS resources.
36  	 */
37  	private URI appURI;
38  
39  	public void setHttpClient(HttpClient client) {
40  		this.client = client;
41  	}
42  	public void setAppURI(URI appURI) {
43  		this.appURI = appURI;
44  	}	
45  	
46  	/**
47  	 * Helper method that returns a URIBuilder fully initialized to point
48  	 * to the URI that will reach the specified method within the inventory
49  	 * resource classes.
50  	 * @param resourceClass
51  	 * @param method
52  	 * @return
53  	 */
54  	protected <T> UriBuilder buildURI(Class<T> resourceClass, String method) {
55  		//start with the URI for the WAR deployed to the server 
56  		//that ends with the context-root
57  		return UriBuilder.fromUri(appURI)
58  				//add path info from the 
59  				//javax.ws.rs.core.Application @ApplicationPath
60  				.path("rest")
61  				//add in @Path added by resource class
62  				.path(resourceClass)
63  				//add in @Path added by resource class' method
64  				.path(resourceClass,method);
65  				//the result will be a URI template that 
66  				//must be passed arguments by the caller during build()
67  	}
68  
69  	@Override
70  	public Customer addCustomer(Customer customer) throws Exception {
71  		URI uri = buildURI(CustomersResource.class,"addCustomer")
72  				.build();
73  			
74  		//build overall request
75  		HttpPost post = new HttpPost(uri);
76  		post.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML);
77  		post.setEntity(new StringEntity(customer.toString(), "UTF-8"));
78  		
79  		//issue request and look for OK with entity
80  		HttpResponse response = client.execute(post);
81  		log.info(String.format("%s %s", post.getURI(), response));
82  		if (Response.Status.CREATED.getStatusCode() == response.getStatusLine().getStatusCode()) {
83  			return CustomerRepresentation.unmarshall(Customer.class,
84  					response.getEntity().getContent());
85  		}
86  		log.warn(EntityUtils.toString(response.getEntity()));
87  		return null;
88  	}
89  
90  	@Override
91  	public Customers findCustomersByName(String firstName, String lastName, int offset, int limit) throws Exception {
92  		//build a URI to the specific method that is hosted within the app
93  		URI uri = buildURI(CustomersResource.class,"findCustomersByName")
94  				//marshall @QueryParams into URI
95  				.queryParam("firstName", firstName)
96  				.queryParam("lastName", lastName)
97  				.queryParam("offset", offset)
98  				.queryParam("limit", limit)
99  				.build();
100 		
101 		//build the overall request 
102 		HttpGet get = new HttpGet(uri);
103 		get.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML);
104 		
105 		//issue request and look for an OK response with entity
106 		HttpResponse response = client.execute(get);
107 		log.info(String.format("%s %s", get.getURI(), response));
108 		if (Response.Status.OK.getStatusCode() == response.getStatusLine().getStatusCode()) {
109 			return CustomerRepresentation.unmarshall(Customers.class,
110 					response.getEntity().getContent());
111 		}
112 		log.warn(EntityUtils.toString(response.getEntity()));
113 		return null;
114 	}
115 	
116 	@Override
117 	public Customer getCustomer(int id) throws Exception {
118 		URI uri = buildURI(CustomersResource.class,"getCustomer")
119 				//marshall @PathParm into the URI
120 				.build(id);
121 		
122 		//build the overall request
123 		HttpGet get = new HttpGet(uri);
124 
125 		//execute request and look for an OK response without an entity
126 		HttpResponse response = client.execute(get);
127 		log.info(String.format("%s %s", get.getURI(), response));
128 		if (Response.Status.OK.getStatusCode() == response.getStatusLine().getStatusCode()) {
129 			return CustomerRepresentation.unmarshall(Customer.class,
130 					response.getEntity().getContent());
131 		}
132 		log.warn(EntityUtils.toString(response.getEntity()));
133 		return null;
134 	}
135 
136 	@Override
137 	public boolean deleteCustomer(int id) throws Exception {
138 		URI uri = buildURI(CustomersResource.class,"deleteCustomer")
139 				//marshall @PathParm into the URI
140 				.build(id);
141 		
142 		//build the overall request
143 		HttpDelete delete = new HttpDelete(uri);
144 
145 		//execute request and look for an OK response without an entity
146 		HttpResponse response = client.execute(delete);
147 		log.info(String.format("%s %s", delete.getURI(), response));
148 		if (Response.Status.OK.getStatusCode() == response.getStatusLine().getStatusCode()) {
149 			EntityUtils.consume(response.getEntity());
150 			return true;
151 		}
152 		log.warn(EntityUtils.toString(response.getEntity()));
153 		return false;
154 	}
155 }