2 * Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE)
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.openo.msb.wrapper.consul.util;
19 import com.google.common.base.Optional;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.ImmutableMap;
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;
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;
38 import java.math.BigInteger;
39 import java.util.List;
43 * A collection of stateless utility methods for use in constructing
44 * requests and responses to the Consul HTTP API.
46 public class ClientUtil {
49 * Applies all key/values from the params map to query string parameters.
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.
55 public static WebTarget queryParams(WebTarget webTarget, Map<String, String> params) {
56 WebTarget target = webTarget;
59 for(Map.Entry<String, String> entry : params.entrySet()) {
60 target = target.queryParam(entry.getKey(), entry.getValue());
68 * Given a {@link org.openo.msb.wrapper.consul.option.ParamAdder} object, adds the
69 * appropriate query string parameters to the request being built.
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
76 public static WebTarget addParams(WebTarget webTarget, ParamAdder paramAdder) {
77 return paramAdder == null ? webTarget : paramAdder.apply(webTarget);
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.
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}.
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);
97 return response(target, type);
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.
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.
110 public static <T> void response(WebTarget target, CatalogOptions catalogOptions,
111 QueryOptions queryOptions,
113 ConsulResponseCallback<T> callback) {
115 target = addParams(target, catalogOptions);
116 target = addParams(target, queryOptions);
118 response(target, type, callback);
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.
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.
130 public static <T> ConsulResponse<T> response(WebTarget webTarget, GenericType<T> responseType) {
131 Response response = webTarget.request().accept(MediaType.APPLICATION_JSON_TYPE).get();
133 return consulResponse(responseType, response);
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.
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.
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>() {
150 public void completed(Response response) {
152 callback.onComplete(consulResponse(responseType, response));
153 } catch (Exception ex) {
154 callback.onFailure(ex);
159 public void failed(Throwable throwable) {
160 callback.onFailure(throwable);
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.
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.
174 private static <T> ConsulResponse<T> consulResponse(GenericType<T> responseType, Response response) {
175 handleErrors(response);
177 String indexHeaderValue = response.getHeaderString("X-Consul-Index");
178 String lastContactHeaderValue = response.getHeaderString("X-Consul-Lastcontact");
179 String knownLeaderHeaderValue = response.getHeaderString("X-Consul-Knownleader");
181 BigInteger index = new BigInteger(indexHeaderValue);
182 long lastContact = lastContactHeaderValue == null ? -1 : Long.valueOf(lastContactHeaderValue);
183 boolean knownLeader = knownLeaderHeaderValue == null ? false : Boolean.valueOf(knownLeaderHeaderValue);
185 ConsulResponse<T> consulResponse = new ConsulResponse<T>(readResponse(response, responseType), lastContact, knownLeader, index);
189 return consulResponse;
193 * Converts a {@link Response} object to the generic type provided, or an empty
194 * representation if appropriate
196 * @param response response
197 * @param responseType response type
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();
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());
215 return response.readEntity(responseType);
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.
223 * @param response The HTTP response.
225 public static void handleErrors(Response response) {
227 if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL
228 || response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
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);
238 throw new WebApplicationException(message, response);
240 } catch (Exception e) {
241 throw new ConsulException(e.getLocalizedMessage(), e);