f19ed78728ccc8f9994a30c8b8a149e0ed69892c
[policy/models.git] / models-interactions / 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  * Modifications Copyright (C) 2019 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.rest;
23
24 import java.nio.charset.Charset;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import javax.xml.bind.DatatypeConverter;
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.HttpPut;
33 import org.apache.http.client.methods.HttpRequestBase;
34 import org.apache.http.conn.ssl.NoopHostnameVerifier;
35 import org.apache.http.entity.StringEntity;
36 import org.apache.http.impl.client.CloseableHttpClient;
37 import org.apache.http.impl.client.HttpClientBuilder;
38 import org.apache.http.util.EntityUtils;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public class RestManager {
43
44     private static final Logger logger = LoggerFactory.getLogger(RestManager.class);
45
46     public class Pair<A, B> {
47         public final A first;
48         public final B second;
49
50         public Pair(A first, B second) {
51             this.first = first;
52             this.second = second;
53         }
54     }
55
56     /**
57      * Perform REST PUT.
58      *
59      * @param url         the url
60      * @param username    the user name
61      * @param password    the password
62      * @param headers     any headers
63      * @param contentType what the content type is
64      * @param body        body to send
65      * @return the response status code and the body
66      */
67     public Pair<Integer, String> put(String url, String username, String password,
68                                       Map<String, String> headers, String contentType, String body) {
69         HttpPut put = new HttpPut(url);
70         addHeaders(put, username, password, headers);
71         put.addHeader("Content-Type", contentType);
72         try {
73             StringEntity input = new StringEntity(body);
74             input.setContentType(contentType);
75             put.setEntity(input);
76         } catch (Exception e) {
77             logger.error("put threw: ", e);
78             return null;
79         }
80         return sendRequest(put);
81     }
82
83     /**
84      * Perform REST Post.
85      *
86      * @param url         the url
87      * @param username    the user name
88      * @param password    the password
89      * @param headers     any headers
90      * @param contentType what the content type is
91      * @param body        body to send
92      * @return the response status code and the body
93      */
94     public Pair<Integer, String> post(String url, String username, String password,
95                                       Map<String, String> headers, String contentType, String body) {
96         HttpPost post = new HttpPost(url);
97         addHeaders(post, username, password, headers);
98         post.addHeader("Content-Type", contentType);
99         try {
100             StringEntity input = new StringEntity(body);
101             input.setContentType(contentType);
102             post.setEntity(input);
103         } catch (Exception e) {
104             logger.error("post threw: ", e);
105             return null;
106         }
107         return sendRequest(post);
108     }
109
110     /**
111      * Do a REST get.
112      *
113      * @param url      URL
114      * @param username user name
115      * @param password password
116      * @param headers  any headers to add
117      * @return a Pair for the response status and the body
118      */
119     public Pair<Integer, String> get(String url, String username, String password,
120                                      Map<String, String> headers) {
121         HttpGet get = new HttpGet(url);
122         addHeaders(get, username, password, headers);
123         return sendRequest(get);
124     }
125
126     /**
127      * Perform REST Delete.
128      *
129      * @param url         the url
130      * @param username    the user name
131      * @param password    the password
132      * @param headers     any headers
133      * @param contentType what the content type is
134      * @param body        body (optional) to send
135      * @return the response status code and the body
136      */
137     public Pair<Integer, String> delete(String url, String username, String password, Map<String, String> headers,
138                                         String contentType, String body) {
139         HttpDeleteWithBody delete = new HttpDeleteWithBody(url);
140         addHeaders(delete, username, password, headers);
141         delete.addHeader("Content-Type", contentType);
142         if (body != null && !body.isEmpty()) {
143             try {
144                 StringEntity input = new StringEntity(body);
145                 input.setContentType(contentType);
146                 delete.setEntity(input);
147             } catch (Exception e) {
148                 logger.error("delete threw: ", e);
149                 return null;
150             }
151         }
152         return sendRequest(delete);
153     }
154
155     /**
156      * Send REST request.
157      *
158      * @param request http request to send
159      * @return the response status code and the body
160      */
161     private Pair<Integer, String> sendRequest(HttpRequestBase request) {
162         if (logger.isDebugEnabled()) {
163             logger.debug("***** sendRequest to url {}:", request.getURI());
164         }
165
166         try (CloseableHttpClient client =
167                      HttpClientBuilder
168                              .create()
169                              .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
170                              .build()) {
171             HttpResponse response = client.execute(request);
172             if (response != null) {
173                 String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
174                 logger.debug("HTTP Response Status Code: {}",
175                         response.getStatusLine().getStatusCode());
176                 logger.debug("HTTP Response Body:");
177                 logger.debug(returnBody);
178
179                 return new Pair<>(response.getStatusLine().getStatusCode(),
180                         returnBody);
181             } else {
182                 logger.error("Response from {} is null", request.getURI());
183                 return null;
184             }
185         } catch (Exception e) {
186             logger.error("Request failed to {}", request.getURI(), e);
187             return null;
188         }
189     }
190
191     /**
192      * Add header to the request.
193      *
194      * @param request  http request to send
195      * @param username the user name
196      * @param password the password
197      * @param headers  any headers
198      */
199     private void addHeaders(HttpRequestBase request, String username, String password, Map<String,
200             String> headers) {
201         String authHeader = makeAuthHeader(username, password);
202         if (headers != null) {
203             for (Entry<String, String> entry : headers.entrySet()) {
204                 request.addHeader(entry.getKey(), headers.get(entry.getKey()));
205             }
206         }
207         if (authHeader != null) {
208             request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
209         }
210     }
211
212     private String makeAuthHeader(String username, String password) {
213         if (username == null || username.isEmpty()) {
214             return null;
215         }
216
217         String auth = username + ":" + (password == null ? "" : password);
218         return "Basic " + DatatypeConverter.printBase64Binary(auth.getBytes(Charset.forName("ISO-8859-1")));
219     }
220 }