migrate model-impl from drools-applications
[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
29 import org.apache.http.HttpHeaders;
30 import org.apache.http.HttpResponse;
31 import org.apache.http.client.methods.HttpGet;
32 import org.apache.http.client.methods.HttpPost;
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 Post.
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> post(String url, String username, String password,
68                                       Map<String, String> headers, String contentType, String body) {
69         HttpPost post = new HttpPost(url);
70         addHeaders(post, username, password, headers);
71         post.addHeader("Content-Type", contentType);
72         try {
73             StringEntity input = new StringEntity(body);
74             input.setContentType(contentType);
75             post.setEntity(input);
76         } catch (Exception e) {
77             logger.error("post threw: ", e);
78             return null;
79         }
80         return sendRequest(post);
81     }
82
83     /**
84      * Do a REST get.
85      *
86      * @param url      URL
87      * @param username user name
88      * @param password password
89      * @param headers  any headers to add
90      * @return a Pair for the response status and the body
91      */
92     public Pair<Integer, String> get(String url, String username, String password,
93                                      Map<String, String> headers) {
94         HttpGet get = new HttpGet(url);
95         addHeaders(get, username, password, headers);
96         return sendRequest(get);
97     }
98
99     /**
100      * Perform REST Delete.
101      *
102      * @param url         the url
103      * @param username    the user name
104      * @param password    the password
105      * @param headers     any headers
106      * @param contentType what the content type is
107      * @param body        body (optional) to send
108      * @return the response status code and the body
109      */
110     public Pair<Integer, String> delete(String url, String username, String password, Map<String, String> headers,
111                                         String contentType, String body) {
112         HttpDeleteWithBody delete = new HttpDeleteWithBody(url);
113         addHeaders(delete, username, password, headers);
114         delete.addHeader("Content-Type", contentType);
115         if (body != null && !body.isEmpty()) {
116             try {
117                 StringEntity input = new StringEntity(body);
118                 input.setContentType(contentType);
119                 delete.setEntity(input);
120             } catch (Exception e) {
121                 logger.error("delete threw: ", e);
122                 return null;
123             }
124         }
125         return sendRequest(delete);
126     }
127
128     /**
129      * Send REST request.
130      *
131      * @param request http request to send
132      * @return the response status code and the body
133      */
134     private Pair<Integer, String> sendRequest(HttpRequestBase request) {
135         if (logger.isDebugEnabled()) {
136             logger.debug("***** sendRequest to url {}:", request.getURI());
137         }
138
139         try (CloseableHttpClient client =
140                      HttpClientBuilder
141                              .create()
142                              .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
143                              .build()) {
144             HttpResponse response = client.execute(request);
145             if (response != null) {
146                 String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
147                 logger.debug("HTTP Response Status Code: {}",
148                         response.getStatusLine().getStatusCode());
149                 logger.debug("HTTP Response Body:");
150                 logger.debug(returnBody);
151
152                 return new Pair<>(response.getStatusLine().getStatusCode(),
153                         returnBody);
154             } else {
155                 logger.error("Response from {} is null", request.getURI());
156                 return null;
157             }
158         } catch (Exception e) {
159             logger.error("Request failed to {}", request.getURI(), e);
160             return null;
161         }
162     }
163
164     /**
165      * Add header to the request.
166      *
167      * @param request  http request to send
168      * @param username the user name
169      * @param password the password
170      * @param headers  any headers
171      */
172     private void addHeaders(HttpRequestBase request, String username, String password, Map<String,
173             String> headers) {
174         String authHeader = makeAuthHeader(username, password);
175         if (headers != null) {
176             for (Entry<String, String> entry : headers.entrySet()) {
177                 request.addHeader(entry.getKey(), headers.get(entry.getKey()));
178             }
179         }
180         if (authHeader != null) {
181             request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
182         }
183     }
184
185     private String makeAuthHeader(String username, String password) {
186         if (username == null || username.isEmpty()) {
187             return null;
188         }
189
190         String auth = username + ":" + (password == null ? "" : password);
191         return "Basic " + DatatypeConverter.printBase64Binary(auth.getBytes(Charset.forName("ISO-8859-1")));
192     }
193 }