View Javadoc
1   package ejava.examples.ejbwar.customer.client;
2   
3   import java.net.URI;
4   
5   import javax.ws.rs.client.Client;
6   import javax.ws.rs.client.Entity;
7   import javax.ws.rs.client.Invocation;
8   import javax.ws.rs.client.ResponseProcessingException;
9   import javax.ws.rs.client.WebTarget;
10  import javax.ws.rs.core.MediaType;
11  import javax.ws.rs.core.Response;
12  import javax.ws.rs.core.Response.Status;
13  import javax.ws.rs.core.UriBuilder;
14  
15  import org.slf4j.Logger;
16  import org.slf4j.LoggerFactory;
17  
18  import ejava.examples.ejbwar.customer.bo.Customer;
19  import ejava.examples.ejbwar.customer.bo.Customers;
20  
21  /**
22   * This class implements a JAX-RS Client interface to the customer 
23   * web application. All commands are through HTTP POST, GET, PUT, and DELETE
24   * methods to specific resource URIs for customers.
25   */
26  public class CustomerJaxRSClientImpl implements CustomerClient {
27  	private static final Logger logger = LoggerFactory.getLogger(CustomerJaxRSClientImpl.class);
28      public static final String CUSTOMERS_PATH = "customers";
29      public static final String CUSTOMER_PATH = "customers/{id}";
30  	private Client client;
31  	/**
32  	 * Defines the HTTP URL for the WAR that hosts the JAX-RS resources.
33  	 */
34  	private URI baseUrl;
35      
36      /**
37       * Defines the protocol between the client and server.
38       */
39      private MediaType mediaType=MediaType.APPLICATION_XML_TYPE;
40  
41  	public void setClient(Client client) {
42  		this.client = client;
43  	}
44      public void setBaseUrl(URI baseUrl) {
45          this.baseUrl = baseUrl;
46      }
47      
48      public void setMediaType(String mediaType) {
49          this.mediaType = MediaType.valueOf(mediaType);
50      }
51  	
52  
53      /**
54       * Helper class to build the base URI for a client call.
55       * @param resourcePath
56       * @return uri builder ready to accept path parameter values
57       */
58      private UriBuilder getBaseUri(String...resourcePath) {
59          UriBuilder b = UriBuilder.fromUri(baseUrl).path("api");
60          if (resourcePath!=null) {
61              for (String p: resourcePath) {
62                  b = b.path(p);
63              }
64          }
65          return b;
66      }
67  
68  	@Override
69  	public Customer addCustomer(Customer customer) {
70  		URI uri = getBaseUri(CUSTOMERS_PATH)
71  				.build();
72  			
73  		//build overall request
74  		Invocation request = client.target(uri)
75  		        .request(mediaType)
76  		        .buildPost(Entity.entity(customer, mediaType, customer.getClass().getAnnotations()));
77  		
78  		//issue request and look for OK with entity
79  		try (Response response=request.invoke()) {
80              logger.debug("POST {}, {} returned {}", uri, mediaType, response.getStatusInfo());
81  	        if (Status.Family.SUCCESSFUL==response.getStatusInfo().getFamily()) {
82  	            return response.readEntity(Customer.class);
83  	        } else {
84  	            String payload = response.hasEntity() ? response.readEntity(String.class) 
85  	                    : response.getStatusInfo().toString();
86  	            logger.warn(payload);
87  	            throw new ResponseProcessingException(response, payload);
88  	        }
89  		}
90  	}
91  
92  	@Override
93  	public Customers findCustomersByName(String firstName, String lastName, int offset, int limit) {
94  		//build a URI to the specific method that is hosted within the app
95  		URI uri = getBaseUri(CUSTOMERS_PATH)
96  				.build();
97  		
98  		//build the overall request 
99  		Invocation request = client.target(uri)
100 	              //marshall @QueryParams into URI
101                 .queryParam("firstName", firstName)
102                 .queryParam("lastName", lastName)
103                 .queryParam("offset", offset)
104                 .queryParam("limit", limit)
105 		        .request(mediaType)
106 		        .buildGet();
107 		
108 		//issue request and look for an OK response with entity
109 		try (Response response = request.invoke()) {
110             logger.debug("GET {}, {} returned {}", uri, mediaType, response.getStatusInfo());
111             if (Status.Family.SUCCESSFUL==response.getStatusInfo().getFamily()) {
112                 return response.readEntity(Customers.class);
113             } else {
114                 String payload = response.hasEntity() ? response.readEntity(String.class) 
115                         : response.getStatusInfo().toString();
116                 logger.warn(payload);
117                 throw new ResponseProcessingException(response, payload);
118             }		    
119 		}
120 	}
121 	
122 	@Override
123 	public Customer getCustomer(int id) {
124 		URI uri = getBaseUri(CUSTOMER_PATH)
125 				//marshall @PathParm into the URI
126 				.build(id);
127 		
128 		//build the overall request
129 		Invocation request = client.target(uri)
130 		        .request(mediaType)
131 		        .buildGet();
132 
133 		//execute request and look for an OK response without an entity
134 		try (Response response = request.invoke()) {
135             logger.debug("GET {}, {} returned {}", uri, mediaType, response.getStatusInfo());
136             if (Status.Family.SUCCESSFUL==response.getStatusInfo().getFamily()) {
137                 return response.readEntity(Customer.class);
138             } else {
139                 String payload = response.hasEntity() ? response.readEntity(String.class) 
140                         : response.getStatusInfo().toString();
141                 logger.warn(payload);
142                 throw new ResponseProcessingException(response, payload);
143             }           
144 		}
145 	}
146 
147 	@Override
148 	public boolean deleteCustomer(int id) {
149 		URI uri = getBaseUri(CUSTOMER_PATH)
150 				//marshall @PathParm into the URI
151 				.build(id);
152 		
153 		//build the overall request
154 		Invocation request = client.target(uri)
155 		        .request()
156 		        .buildDelete();
157 
158 		//execute request and look for an OK response without an entity
159 		try (Response response=request.invoke()) {
160             logger.debug("GET {}, {} returned {}", uri, mediaType, response.getStatusInfo());
161             if (Status.Family.SUCCESSFUL==response.getStatusInfo().getFamily()) {
162                 return true;
163             } else {
164                 String payload = response.hasEntity() ? response.readEntity(String.class) 
165                         : response.getStatusInfo().toString();
166                 logger.warn(payload);
167                 throw new ResponseProcessingException(response, payload);
168             }           		    
169 		}
170 	}
171 }