2 * Copyright 2016 ZTE, Inc. and others.
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.
16 package org.onap.msb.sdclient.wrapper.consul.util;
18 import com.google.common.base.Optional;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMap;
22 import javax.ws.rs.ServerErrorException;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.client.InvocationCallback;
25 import javax.ws.rs.client.WebTarget;
26 import javax.ws.rs.core.GenericType;
27 import javax.ws.rs.core.MediaType;
28 import javax.ws.rs.core.Response;
30 import org.onap.msb.sdclient.wrapper.consul.ConsulException;
31 import org.onap.msb.sdclient.wrapper.consul.async.ConsulResponseCallback;
32 import org.onap.msb.sdclient.wrapper.consul.model.ConsulResponse;
33 import org.onap.msb.sdclient.wrapper.consul.option.CatalogOptions;
34 import org.onap.msb.sdclient.wrapper.consul.option.ParamAdder;
35 import org.onap.msb.sdclient.wrapper.consul.option.QueryOptions;
37 import java.math.BigInteger;
38 import java.util.List;
42 * A collection of stateless utility methods for use in constructing
43 * requests and responses to the Consul HTTP API.
45 public class ClientUtil {
48 * Applies all key/values from the params map to query string parameters.
50 * @param webTarget The JAX-RS target to apply the query parameters.
51 * @param params Map of parameters.
52 * @return The new target with the parameters applied.
54 public static WebTarget queryParams(WebTarget webTarget, Map<String, String> params) {
55 WebTarget target = webTarget;
58 for(Map.Entry<String, String> entry : params.entrySet()) {
59 target = target.queryParam(entry.getKey(), entry.getValue());
67 * Given a {@link org.onap.msb.sdclient.wrapper.consul.option.ParamAdder} object, adds the
68 * appropriate query string parameters to the request being built.
70 * @param webTarget The base {@link javax.ws.rs.client.WebTarget}.
71 * @param paramAdder will add specific params to the target.
72 * @return A {@link javax.ws.rs.client.WebTarget} with all appropriate query
75 public static WebTarget addParams(WebTarget webTarget, ParamAdder paramAdder) {
76 return paramAdder == null ? webTarget : paramAdder.apply(webTarget);
80 * Generates a {@link org.onap.msb.sdclient.wrapper.consul.model.ConsulResponse} for a specific datacenter,
81 * set of {@link org.onap.msb.sdclient.wrapper.consul.option.QueryOptions}, and a result type.
83 * @param target The base {@link javax.ws.rs.client.WebTarget}.
84 * @param catalogOptions Catalog specific options to use.
85 * @param queryOptions The Query Options to use.
86 * @param type The generic type to marshall the resulting data to.
87 * @param <T> The result type.
88 * @return A {@link org.onap.msb.sdclient.wrapper.consul.model.ConsulResponse}.
90 public static <T> ConsulResponse<T> response(WebTarget target, CatalogOptions catalogOptions,
91 QueryOptions queryOptions,
92 GenericType<T> type) {
93 target = addParams(target, catalogOptions);
94 target = addParams(target, queryOptions);
96 return response(target, type);
100 * Generates a {@link org.onap.msb.sdclient.wrapper.consul.model.ConsulResponse} for a specific datacenter,
101 * set of {@link org.onap.msb.sdclient.wrapper.consul.option.QueryOptions}, and a result type.
103 * @param target The base {@link javax.ws.rs.client.WebTarget}.
104 * @param catalogOptions Catalog specific options to use.
105 * @param queryOptions The Query Options to use.
106 * @param type The generic type to marshall the resulting data to.
107 * @param <T> The result type.
109 public static <T> void response(WebTarget target, CatalogOptions catalogOptions,
110 QueryOptions queryOptions,
112 ConsulResponseCallback<T> callback) {
114 target = addParams(target, catalogOptions);
115 target = addParams(target, queryOptions);
117 response(target, type, callback);
121 * Given a {@link javax.ws.rs.client.WebTarget} object and a type to marshall
122 * the result JSON into, complete the HTTP GET request.
124 * @param webTarget The JAX-RS target.
125 * @param responseType The class to marshall the JSON into.
126 * @param <T> The class to marshall the JSON into.
127 * @return A {@link org.onap.msb.sdclient.wrapper.consul.model.ConsulResponse} containing the result.
129 public static <T> ConsulResponse<T> response(WebTarget webTarget, GenericType<T> responseType) {
130 Response response = webTarget.request().accept(MediaType.APPLICATION_JSON_TYPE).get();
132 return consulResponse(responseType, response);
136 * Given a {@link javax.ws.rs.client.WebTarget} object and a type to marshall
137 * the result JSON into, complete the HTTP GET request.
139 * @param webTarget The JAX-RS target.
140 * @param responseType The class to marshall the JSON into.
141 * @param callback The callback object to handle the result on a different thread.
142 * @param <T> The class to marshall the JSON into.
144 public static <T> void response(WebTarget webTarget, final GenericType<T> responseType,
145 final ConsulResponseCallback<T> callback) {
146 webTarget.request().accept(MediaType.APPLICATION_JSON_TYPE).async().get(new InvocationCallback<Response>() {
149 public void completed(Response response) {
151 callback.onComplete(consulResponse(responseType, response));
152 } catch (Exception ex) {
153 callback.onFailure(ex);
158 public void failed(Throwable throwable) {
159 callback.onFailure(throwable);
165 * Extracts Consul specific headers and adds them to a {@link org.onap.msb.sdclient.wrapper.consul.model.ConsulResponse}
166 * object, which also contains the returned JSON entity.
168 * @param responseType The class to marshall the JSON to.
169 * @param response The HTTP response.
170 * @param <T> The class to marshall the JSON to.
171 * @return A {@link org.onap.msb.sdclient.wrapper.consul.model.ConsulResponse} object.
173 private static <T> ConsulResponse<T> consulResponse(GenericType<T> responseType, Response response) {
174 handleErrors(response);
176 String indexHeaderValue = response.getHeaderString("X-Consul-Index");
177 String lastContactHeaderValue = response.getHeaderString("X-Consul-Lastcontact");
178 String knownLeaderHeaderValue = response.getHeaderString("X-Consul-Knownleader");
180 BigInteger index = new BigInteger(indexHeaderValue);
181 long lastContact = lastContactHeaderValue == null ? -1 : Long.parseLong(lastContactHeaderValue);
182 boolean knownLeader = knownLeaderHeaderValue == null ? false : Boolean.valueOf(knownLeaderHeaderValue);
184 ConsulResponse<T> consulResponse = new ConsulResponse<T>(readResponse(response, responseType), lastContact, knownLeader, index);
188 return consulResponse;
192 * Converts a {@link Response} object to the generic type provided, or an empty
193 * representation if appropriate
195 * @param response response
196 * @param responseType response type
200 @SuppressWarnings("unchecked")
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);