Initial code import
[msb/apigateway.git] / apiroute / apiroute-service / src / main / java / org / openo / msb / wrapper / consul / util / ClientUtil.java
1 /**
2 * Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.openo.msb.wrapper.consul.util;
18
19 import com.google.common.base.Optional;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.ImmutableMap;
22
23 import javax.ws.rs.ServerErrorException;
24 import javax.ws.rs.WebApplicationException;
25 import javax.ws.rs.client.InvocationCallback;
26 import javax.ws.rs.client.WebTarget;
27 import javax.ws.rs.core.GenericType;
28 import javax.ws.rs.core.MediaType;
29 import javax.ws.rs.core.Response;
30
31 import org.openo.msb.wrapper.consul.ConsulException;
32 import org.openo.msb.wrapper.consul.async.ConsulResponseCallback;
33 import org.openo.msb.wrapper.consul.model.ConsulResponse;
34 import org.openo.msb.wrapper.consul.option.CatalogOptions;
35 import org.openo.msb.wrapper.consul.option.ParamAdder;
36 import org.openo.msb.wrapper.consul.option.QueryOptions;
37
38 import java.math.BigInteger;
39 import java.util.List;
40 import java.util.Map;
41
42 /**
43  * A collection of stateless utility methods for use in constructing
44  * requests and responses to the Consul HTTP API.
45  */
46 public class ClientUtil {
47
48     /**
49      * Applies all key/values from the params map to query string parameters.
50      *
51      * @param webTarget The JAX-RS target to apply the query parameters.
52      * @param params Map of parameters.
53      * @return The new target with the parameters applied.
54      */
55     public static WebTarget queryParams(WebTarget webTarget, Map<String, String> params) {
56         WebTarget target = webTarget;
57
58         if(params != null) {
59             for(Map.Entry<String, String> entry : params.entrySet()) {
60                 target = target.queryParam(entry.getKey(), entry.getValue());
61             }
62         }
63
64         return target;
65     }
66
67     /**
68      * Given a {@link org.openo.msb.wrapper.consul.option.ParamAdder} object, adds the
69      * appropriate query string parameters to the request being built.
70      *
71      * @param webTarget The base {@link javax.ws.rs.client.WebTarget}.
72      * @param  paramAdder will add specific params to the target.
73      * @return A {@link javax.ws.rs.client.WebTarget} with all appropriate query
74      *  string parameters.
75      */
76     public static WebTarget addParams(WebTarget webTarget, ParamAdder paramAdder) {
77         return paramAdder == null ? webTarget : paramAdder.apply(webTarget);
78     }
79
80     /**
81      * Generates a {@link org.openo.msb.wrapper.consul.model.ConsulResponse} for a specific datacenter,
82      * set of {@link org.openo.msb.wrapper.consul.option.QueryOptions}, and a result type.
83      *
84      * @param target The base {@link javax.ws.rs.client.WebTarget}.
85      * @param catalogOptions Catalog specific options to use.
86      * @param queryOptions The Query Options to use.
87      * @param type The generic type to marshall the resulting data to.
88      * @param <T> The result type.
89      * @return A {@link org.openo.msb.wrapper.consul.model.ConsulResponse}.
90      */
91     public static <T> ConsulResponse<T> response(WebTarget target, CatalogOptions catalogOptions,
92                                                  QueryOptions queryOptions,
93                                                  GenericType<T> type) {
94         target = addParams(target, catalogOptions);
95         target = addParams(target, queryOptions);
96
97         return response(target, type);
98     }
99
100     /**
101      * Generates a {@link org.openo.msb.wrapper.consul.model.ConsulResponse} for a specific datacenter,
102      * set of {@link org.openo.msb.wrapper.consul.option.QueryOptions}, and a result type.
103      *
104      * @param target The base {@link javax.ws.rs.client.WebTarget}.
105      * @param catalogOptions Catalog specific options to use.
106      * @param queryOptions The Query Options to use.
107      * @param type The generic type to marshall the resulting data to.
108      * @param <T> The result type.
109      */
110     public static <T> void response(WebTarget target, CatalogOptions catalogOptions,
111                                                  QueryOptions queryOptions,
112                                                  GenericType<T> type,
113                                                  ConsulResponseCallback<T> callback) {
114
115         target = addParams(target, catalogOptions);
116         target = addParams(target, queryOptions);
117
118         response(target, type, callback);
119     }
120
121     /**
122      * Given a {@link javax.ws.rs.client.WebTarget} object and a type to marshall
123      * the result JSON into, complete the HTTP GET request.
124      *
125      * @param webTarget The JAX-RS target.
126      * @param responseType The class to marshall the JSON into.
127      * @param <T> The class to marshall the JSON into.
128      * @return A {@link org.openo.msb.wrapper.consul.model.ConsulResponse} containing the result.
129      */
130     public static <T> ConsulResponse<T> response(WebTarget webTarget, GenericType<T> responseType) {
131         Response response = webTarget.request().accept(MediaType.APPLICATION_JSON_TYPE).get();
132
133         return consulResponse(responseType, response);
134     }
135
136     /**
137      * Given a {@link javax.ws.rs.client.WebTarget} object and a type to marshall
138      * the result JSON into, complete the HTTP GET request.
139      *
140      * @param webTarget The JAX-RS target.
141      * @param responseType The class to marshall the JSON into.
142      * @param callback The callback object to handle the result on a different thread.
143      * @param <T> The class to marshall the JSON into.
144      */
145     public static <T> void response(WebTarget webTarget, final GenericType<T> responseType,
146                                     final ConsulResponseCallback<T> callback) {
147         webTarget.request().accept(MediaType.APPLICATION_JSON_TYPE).async().get(new InvocationCallback<Response>() {
148
149             @Override
150             public void completed(Response response) {
151                 try {
152                     callback.onComplete(consulResponse(responseType, response));
153                 } catch (Exception ex) {
154                     callback.onFailure(ex);
155                 }
156             }
157
158             @Override
159             public void failed(Throwable throwable) {
160                 callback.onFailure(throwable);
161             }
162         });
163     }
164
165     /**
166      * Extracts Consul specific headers and adds them to a {@link org.openo.msb.wrapper.consul.model.ConsulResponse}
167      * object, which also contains the returned JSON entity.
168      *
169      * @param responseType The class to marshall the JSON to.
170      * @param response The HTTP response.
171      * @param <T> The class to marshall the JSON to.
172      * @return A {@link org.openo.msb.wrapper.consul.model.ConsulResponse} object.
173      */
174     private static <T> ConsulResponse<T> consulResponse(GenericType<T> responseType, Response response) {
175         handleErrors(response);
176
177         String indexHeaderValue = response.getHeaderString("X-Consul-Index");
178         String lastContactHeaderValue = response.getHeaderString("X-Consul-Lastcontact");
179         String knownLeaderHeaderValue = response.getHeaderString("X-Consul-Knownleader");
180
181         BigInteger index = new BigInteger(indexHeaderValue);
182         long lastContact = lastContactHeaderValue == null ? -1 : Long.valueOf(lastContactHeaderValue);
183         boolean knownLeader = knownLeaderHeaderValue == null ? false : Boolean.valueOf(knownLeaderHeaderValue);
184
185         ConsulResponse<T> consulResponse = new ConsulResponse<T>(readResponse(response, responseType), lastContact, knownLeader, index);
186
187         response.close();
188
189         return consulResponse;
190     }
191
192     /**
193      * Converts a {@link Response} object to the generic type provided, or an empty
194      * representation if appropriate
195      *
196      * @param response response
197      * @param responseType response type
198      * @param <T>
199      * @return the re
200      */
201     private static <T> T readResponse(Response response, GenericType<T> responseType) {
202         if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
203             // would be nice I knew a better way to do this
204             if (responseType.getRawType() == List.class) {
205                 return (T) ImmutableList.of();
206             } else if (responseType.getRawType() == Optional.class) {
207                 return (T) Optional.absent();
208             } else if(responseType.getRawType() == Map.class) {
209                 return (T) ImmutableMap.of();
210             } else {
211                 // Not sure if this case will be reached, but if it is it'll be nice to know
212                 throw new IllegalStateException("Cannot determine empty representation for " + responseType.getRawType());
213             }
214         }
215         return response.readEntity(responseType);
216     }
217
218     /**
219      * Since Consul returns plain text when an error occurs, check for
220      * unsuccessful HTTP status code, and throw an exception with the text
221      * from Consul as the message.
222      *
223      * @param response The HTTP response.
224      */
225     public static void handleErrors(Response response) {
226
227         if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL
228                 || response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
229             // not an error
230             return;
231         }
232
233         try {
234             final String message = response.hasEntity() ? response.readEntity(String.class) : null;
235             if (response.getStatusInfo().getFamily() ==  Response.Status.Family.SERVER_ERROR) {
236                 throw new ServerErrorException(message, response);
237             } else {
238                 throw new WebApplicationException(message, response);
239             }
240         } catch (Exception e) {
241             throw new ConsulException(e.getLocalizedMessage(), e);
242         } finally {
243             response.close();
244         }
245     }
246 }