2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.cloudify.connector.http;
23 import java.io.IOException;
24 import java.io.InputStream;
26 import java.net.URISyntaxException;
27 import java.net.UnknownHostException;
28 import java.util.List;
30 import java.util.Map.Entry;
32 import org.apache.http.HttpEntity;
33 import org.apache.http.HttpStatus;
34 import org.apache.http.auth.AuthScope;
35 import org.apache.http.auth.UsernamePasswordCredentials;
36 import org.apache.http.client.CredentialsProvider;
37 import org.apache.http.client.HttpResponseException;
38 import org.apache.http.client.methods.CloseableHttpResponse;
39 import org.apache.http.client.methods.HttpDelete;
40 import org.apache.http.client.methods.HttpGet;
41 import org.apache.http.client.methods.HttpPost;
42 import org.apache.http.client.methods.HttpPut;
43 import org.apache.http.client.methods.HttpUriRequest;
44 import org.apache.http.client.utils.URIBuilder;
45 import org.apache.http.entity.ContentType;
46 import org.apache.http.entity.InputStreamEntity;
47 import org.apache.http.entity.StringEntity;
48 import org.apache.http.impl.client.BasicCredentialsProvider;
49 import org.apache.http.impl.client.CloseableHttpClient;
50 import org.apache.http.impl.client.HttpClients;
51 import org.onap.so.cloudify.base.client.CloudifyClientConnector;
52 import org.onap.so.cloudify.base.client.CloudifyConnectException;
53 import org.onap.so.cloudify.base.client.CloudifyRequest;
54 import org.onap.so.cloudify.base.client.CloudifyResponse;
55 import org.onap.so.cloudify.base.client.CloudifyResponseException;
56 import org.onap.so.logger.MsoLogger;
58 import com.fasterxml.jackson.annotation.JsonInclude.Include;
59 import com.fasterxml.jackson.annotation.JsonRootName;
60 import com.fasterxml.jackson.core.JsonProcessingException;
61 import com.fasterxml.jackson.databind.DeserializationFeature;
62 import com.fasterxml.jackson.databind.ObjectMapper;
63 import com.fasterxml.jackson.databind.SerializationFeature;
65 public class HttpClientConnector implements CloudifyClientConnector {
67 private static ObjectMapper DEFAULT_MAPPER;
68 private static ObjectMapper WRAPPED_MAPPER;
70 private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, HttpClientConnector.class);
73 DEFAULT_MAPPER = new ObjectMapper();
75 DEFAULT_MAPPER.setSerializationInclusion(Include.NON_NULL);
76 DEFAULT_MAPPER.disable(SerializationFeature.INDENT_OUTPUT);
77 DEFAULT_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
78 DEFAULT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
80 WRAPPED_MAPPER = new ObjectMapper();
82 WRAPPED_MAPPER.setSerializationInclusion(Include.NON_NULL);
83 WRAPPED_MAPPER.disable(SerializationFeature.INDENT_OUTPUT);
84 WRAPPED_MAPPER.enable(SerializationFeature.WRAP_ROOT_VALUE);
85 WRAPPED_MAPPER.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
86 WRAPPED_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
87 WRAPPED_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
90 protected static <T> ObjectMapper getObjectMapper (Class<T> type) {
91 return type.getAnnotation(JsonRootName.class) == null ? DEFAULT_MAPPER : WRAPPED_MAPPER;
94 public <T> CloudifyResponse request(CloudifyRequest<T> request) {
96 CloseableHttpClient httpClient = null; //HttpClients.createDefault();
98 if (request.isBasicAuth()) {
99 // Use Basic Auth for this request.
100 CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
101 credentialsProvider.setCredentials(AuthScope.ANY,
102 new UsernamePasswordCredentials (request.getUser(), request.getPassword()));
104 httpClient = HttpClients.custom().setRedirectStrategy(new HttpClientRedirectStrategy()).setDefaultCredentialsProvider(credentialsProvider).build();
107 // Don't use basic authentication. The Client will attempt Token-based authentication
108 httpClient = HttpClients.custom().setRedirectStrategy(new HttpClientRedirectStrategy()).build();
113 // Build the URI with query params
115 URIBuilder uriBuilder = new URIBuilder(request.endpoint() + request.path());
117 for(Map.Entry<String, List<Object> > entry : request.queryParams().entrySet()) {
118 for (Object o : entry.getValue()) {
119 uriBuilder.setParameter(entry.getKey(), String.valueOf(o));
123 uri = uriBuilder.build();
124 } catch (URISyntaxException e) {
125 throw new HttpClientException (e);
128 HttpEntity entity = null;
129 if (request.entity() != null) {
130 // Special handling for streaming input
131 if (request.entity().getEntity() instanceof InputStream) {
132 // Entity is an InputStream
133 entity = new InputStreamEntity ((InputStream) request.entity().getEntity());
136 // Assume to be JSON. Flatten the entity to a Json string
138 // Get appropriate mapper, based on existence of a root element in Entity class
139 ObjectMapper mapper = getObjectMapper (request.entity().getEntity().getClass());
141 String entityJson = mapper.writeValueAsString (request.entity().getEntity());
142 entity = new StringEntity(entityJson, ContentType.create(request.entity().getContentType()));
144 LOGGER.debug ("Request JSON Body: " + entityJson.replaceAll("\"password\":\"[^\"]*\"", "\"password\":\"***\""));
146 } catch (JsonProcessingException e) {
147 throw new HttpClientException ("Json processing error on request entity", e);
148 } catch (IOException e) {
149 throw new HttpClientException ("Json IO error on request entity", e);
154 // Determine the HttpRequest class based on the method
155 HttpUriRequest httpRequest;
157 switch (request.method()) {
159 HttpPost post = new HttpPost(uri);
160 post.setEntity (entity);
165 httpRequest = new HttpGet(uri);
169 HttpPut put = new HttpPut(uri);
170 put.setEntity (entity);
175 httpRequest = new HttpDelete(uri);
179 throw new HttpClientException ("Unrecognized HTTP Method: " + request.method());
182 for (Entry<String, List<Object>> h : request.headers().entrySet()) {
183 StringBuilder sb = new StringBuilder();
184 for (Object v : h.getValue()) {
185 sb.append(String.valueOf(v));
187 httpRequest.addHeader(h.getKey(), sb.toString());
190 // Get the Response. But don't get the body entity yet, as this response
191 // will be wrapped in an HttpClientResponse. The HttpClientResponse
192 // buffers the body in constructor, so can close the response here.
193 HttpClientResponse httpClientResponse = null;
194 CloseableHttpResponse httpResponse = null;
196 // Catch known HttpClient exceptions, and wrap them in OpenStack Client Exceptions
197 // so calling functions can distinguish. Only RuntimeExceptions are allowed.
199 httpResponse = httpClient.execute(httpRequest);
201 LOGGER.debug ("Response status: " + httpResponse.getStatusLine().getStatusCode());
203 httpClientResponse = new HttpClientResponse (httpResponse);
205 int status = httpResponse.getStatusLine().getStatusCode();
206 if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED ||
207 status == HttpStatus.SC_NO_CONTENT || status == HttpStatus.SC_ACCEPTED)
209 return httpClientResponse;
212 catch (HttpResponseException e) {
213 // What exactly does this mean? It does not appear to get thrown for
214 // non-2XX responses as documented.
215 throw new CloudifyResponseException(e.getMessage(), e.getStatusCode());
217 catch (UnknownHostException e) {
218 throw new CloudifyConnectException("Unknown Host: " + e.getMessage());
220 catch (IOException e) {
221 // Catch all other IOExceptions and throw as OpenStackConnectException
222 throw new CloudifyConnectException(e.getMessage());
224 catch (Exception e) {
225 // Catchall for anything else, must throw as a RuntimeException
226 LOGGER.error("Client exception", e);
227 throw new RuntimeException("Unexpected client exception", e);
230 // Have the body. Close the stream
231 if (httpResponse != null)
233 httpResponse.close();
234 } catch (IOException e) {
235 LOGGER.debug("Unable to close HTTP Response: " + e);
239 // Get here on an error response (4XX-5XX)
240 throw new CloudifyResponseException(httpResponse.getStatusLine().getReasonPhrase(),
241 httpResponse.getStatusLine().getStatusCode(),