added generic fabric support to SO
[so.git] / cloudify-client / src / main / java / org / onap / so / cloudify / connector / http / HttpClientConnector.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.so.cloudify.connector.http;
22
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.net.UnknownHostException;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31
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;
57
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;
64
65 public class HttpClientConnector implements CloudifyClientConnector {
66
67         private static ObjectMapper DEFAULT_MAPPER;
68         private static ObjectMapper WRAPPED_MAPPER;
69         
70     private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, HttpClientConnector.class);
71
72         static {
73                 DEFAULT_MAPPER = new ObjectMapper();
74
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);
79
80                 WRAPPED_MAPPER = new ObjectMapper();
81
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);
88         }
89         
90         protected static <T> ObjectMapper getObjectMapper (Class<T> type) {
91                 return type.getAnnotation(JsonRootName.class) == null ? DEFAULT_MAPPER : WRAPPED_MAPPER;
92         }
93
94         public <T> CloudifyResponse request(CloudifyRequest<T> request) {
95
96                 CloseableHttpClient httpClient = null; //HttpClients.createDefault();
97
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()));
103
104                         httpClient = HttpClients.custom().setRedirectStrategy(new HttpClientRedirectStrategy()).setDefaultCredentialsProvider(credentialsProvider).build();
105                 }
106                 else {
107                         // Don't use basic authentication.  The Client will attempt Token-based authentication
108                         httpClient = HttpClients.custom().setRedirectStrategy(new HttpClientRedirectStrategy()).build();
109                 }
110                 
111                 URI uri = null;
112                 
113                 // Build the URI with query params
114                 try {
115                         URIBuilder uriBuilder = new URIBuilder(request.endpoint() + request.path());
116
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));
120                                 }
121                         }
122                         
123                         uri = uriBuilder.build();
124                 } catch (URISyntaxException e) {
125                         throw new HttpClientException (e);
126                 }
127
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());
134                         }
135                         else {
136                                 // Assume to be JSON.  Flatten the entity to a Json string                                      
137                                 try {
138                                 // Get appropriate mapper, based on existence of a root element in Entity class
139                                         ObjectMapper mapper = getObjectMapper (request.entity().getEntity().getClass());
140         
141                                         String entityJson = mapper.writeValueAsString (request.entity().getEntity());
142                                         entity = new StringEntity(entityJson, ContentType.create(request.entity().getContentType()));
143                                         
144                                         LOGGER.debug ("Request JSON Body: " + entityJson.replaceAll("\"password\":\"[^\"]*\"", "\"password\":\"***\""));
145         
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);
150                                 }
151                         }
152                 }
153                 
154                 // Determine the HttpRequest class based on the method
155                 HttpUriRequest httpRequest;
156                 
157                 switch (request.method()) {
158                 case POST:
159                         HttpPost post = new HttpPost(uri);
160                         post.setEntity (entity);
161                         httpRequest = post;
162                         break;
163                         
164                 case GET:
165                         httpRequest = new HttpGet(uri);
166                         break;
167
168                 case PUT:
169                         HttpPut put = new HttpPut(uri);
170                         put.setEntity (entity);
171                         httpRequest = put;
172                         break;
173                         
174                 case DELETE:
175                         httpRequest = new HttpDelete(uri);
176                         break;
177                         
178                 default:
179                         throw new HttpClientException ("Unrecognized HTTP Method: " + request.method());
180                 }
181                 
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));
186                         }
187                         httpRequest.addHeader(h.getKey(), sb.toString());
188                 }
189
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;
195                 
196                 // Catch known HttpClient exceptions, and wrap them in OpenStack Client Exceptions
197                 // so calling functions can distinguish.  Only RuntimeExceptions are allowed.
198                 try {
199                         httpResponse = httpClient.execute(httpRequest);
200
201                         LOGGER.debug ("Response status: " + httpResponse.getStatusLine().getStatusCode());
202                         
203                         httpClientResponse = new HttpClientResponse (httpResponse);
204
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)
208                         {
209                                 return httpClientResponse;
210                         }
211                 }
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());
216                 }
217                 catch (UnknownHostException e) {
218                         throw new CloudifyConnectException("Unknown Host: " + e.getMessage());
219                 }
220                 catch (IOException e) {
221                         // Catch all other IOExceptions and throw as OpenStackConnectException
222                         throw new CloudifyConnectException(e.getMessage());
223                 }
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);
228                 }
229                 finally {
230                         // Have the body.  Close the stream
231                         if (httpResponse != null)
232                                 try {
233                                         httpResponse.close();
234                                 } catch (IOException e) {
235                                         LOGGER.debug("Unable to close HTTP Response: " + e);
236                                 }
237                 }
238                 
239                 // Get here on an error response (4XX-5XX)
240                 throw new CloudifyResponseException(httpResponse.getStatusLine().getReasonPhrase(),
241                                                                                         httpResponse.getStatusLine().getStatusCode(),
242                                                                                         httpClientResponse);
243         }
244
245 }