84a220b9aa8ada00b38454ee64f1dcaeb1152447
[policy/drools-applications.git] / controlloop / common / model-impl / rest / src / main / java / org / onap / policy / rest / RestManager.java
1 /*
2  * ============LICENSE_START=======================================================
3  * rest
4  * ================================================================================
5  * Copyright (C) 2017-2019 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.policy.rest;
22
23 import java.nio.charset.Charset;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import javax.xml.bind.DatatypeConverter;
27
28 import org.apache.http.HttpHeaders;
29 import org.apache.http.HttpResponse;
30 import org.apache.http.client.methods.HttpGet;
31 import org.apache.http.client.methods.HttpPost;
32 import org.apache.http.client.methods.HttpRequestBase;
33 import org.apache.http.conn.ssl.NoopHostnameVerifier;
34 import org.apache.http.entity.StringEntity;
35 import org.apache.http.impl.client.CloseableHttpClient;
36 import org.apache.http.impl.client.HttpClientBuilder;
37 import org.apache.http.util.EntityUtils;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public class RestManager {
42
43     private static final Logger logger = LoggerFactory.getLogger(RestManager.class);
44
45     public class Pair<A, B> {
46         public final A first;
47         public final B second;
48
49         public Pair(A first, B second) {
50             this.first = first;
51             this.second = second;
52         }
53     }
54
55     /**
56      * Perform REST Post.
57      *
58      * @param url         the url
59      * @param username    the user name
60      * @param password    the password
61      * @param headers     any headers
62      * @param contentType what the content type is
63      * @param body        body to send
64      * @return the response status code and the body
65      */
66     public Pair<Integer, String> post(String url, String username, String password,
67                                       Map<String, String> headers, String contentType, String body) {
68         HttpPost post = new HttpPost(url);
69         addHeaders(post, username, password, headers);
70         post.addHeader("Content-Type", contentType);
71         try {
72             StringEntity input = new StringEntity(body);
73             input.setContentType(contentType);
74             post.setEntity(input);
75         } catch (Exception e) {
76             logger.error("post threw: ", e);
77             return null;
78         }
79         return sendRequest(post);
80     }
81
82     /**
83      * Do a REST get.
84      *
85      * @param url      URL
86      * @param username user name
87      * @param password password
88      * @param headers  any headers to add
89      * @return a Pair for the response status and the body
90      */
91     public Pair<Integer, String> get(String url, String username, String password,
92                                      Map<String, String> headers) {
93         HttpGet get = new HttpGet(url);
94         addHeaders(get, username, password, headers);
95         return sendRequest(get);
96     }
97
98     /**
99      * Perform REST Delete.
100      *
101      * @param url         the url
102      * @param username    the user name
103      * @param password    the password
104      * @param headers     any headers
105      * @param contentType what the content type is
106      * @param body        body (optional) to send
107      * @return the response status code and the body
108      */
109     public Pair<Integer, String> delete(String url, String username, String password, Map<String, String> headers,
110                                         String contentType, String body) {
111         HttpDeleteWithBody delete = new HttpDeleteWithBody(url);
112         addHeaders(delete, username, password, headers);
113         delete.addHeader("Content-Type", contentType);
114         if (body != null && !body.isEmpty()) {
115             try {
116                 StringEntity input = new StringEntity(body);
117                 input.setContentType(contentType);
118                 delete.setEntity(input);
119             } catch (Exception e) {
120                 logger.error("delete threw: ", e);
121                 return null;
122             }
123         }
124         return sendRequest(delete);
125     }
126
127     /**
128      * Send REST request.
129      *
130      * @param request http request to send
131      * @return the response status code and the body
132      */
133     private Pair<Integer, String> sendRequest(HttpRequestBase request) {
134         if (logger.isDebugEnabled()) {
135             logger.debug("***** sendRequest to url {}:", request.getURI());
136         }
137
138         try (CloseableHttpClient client =
139                      HttpClientBuilder
140                              .create()
141                              .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
142                              .build()) {
143             HttpResponse response = client.execute(request);
144             if (response != null) {
145                 String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
146                 logger.debug("HTTP Response Status Code: {}",
147                         response.getStatusLine().getStatusCode());
148                 logger.debug("HTTP Response Body:");
149                 logger.debug(returnBody);
150
151                 return new Pair<>(response.getStatusLine().getStatusCode(),
152                         returnBody);
153             } else {
154                 logger.error("Response from {} is null", request.getURI());
155                 return null;
156             }
157         } catch (Exception e) {
158             logger.error("Request failed to {}", request.getURI(), e);
159             return null;
160         }
161     }
162
163     /**
164      * Add header to the request.
165      *
166      * @param request  http request to send
167      * @param username the user name
168      * @param password the password
169      * @param headers  any headers
170      */
171     private void addHeaders(HttpRequestBase request, String username, String password, Map<String,
172             String> headers) {
173         String authHeader = makeAuthHeader(username, password);
174         if (headers != null) {
175             for (Entry<String, String> entry : headers.entrySet()) {
176                 request.addHeader(entry.getKey(), headers.get(entry.getKey()));
177             }
178         }
179         if (authHeader != null) {
180             request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
181         }
182     }
183
184     private String makeAuthHeader(String username, String password) {
185         if (username == null || username.isEmpty()) {
186             return null;
187         }
188
189         String auth = username + ":" + (password == null ? "" : password);
190         return "Basic " + DatatypeConverter.printBase64Binary(auth.getBytes(Charset.forName("ISO-8859-1")));
191     }
192 }