Removed all mention of www.example.org from tests
[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.HttpDelete;
31 import org.apache.http.client.methods.HttpGet;
32 import org.apache.http.client.methods.HttpPost;
33 import org.apache.http.client.methods.HttpPut;
34 import org.apache.http.client.methods.HttpRequestBase;
35 import org.apache.http.conn.ssl.NoopHostnameVerifier;
36 import org.apache.http.entity.StringEntity;
37 import org.apache.http.impl.client.CloseableHttpClient;
38 import org.apache.http.impl.client.HttpClientBuilder;
39 import org.apache.http.util.EntityUtils;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public class RestManager {
44
45     private static final Logger logger = LoggerFactory.getLogger(RestManager.class);
46
47     public class Pair<A, B> {
48         public final A first;
49         public final B second;
50
51         public Pair(A first, B second) {
52             this.first = first;
53             this.second = second;
54         }
55     }
56
57     /**
58      * Perform REST PUT.
59      *
60      * @param url         the url
61      * @param username    the user name
62      * @param password    the password
63      * @param headers     any headers
64      * @param contentType what the content type is
65      * @param body        body to send
66      * @return the response status code and the body
67      */
68     public Pair<Integer, String> put(String url, String username, String password,
69                                       Map<String, String> headers, String contentType, String body) {
70         HttpPut put = new HttpPut(url);
71         addHeaders(put, username, password, headers);
72         put.addHeader("Content-Type", contentType);
73         try {
74             StringEntity input = new StringEntity(body);
75             input.setContentType(contentType);
76             put.setEntity(input);
77         } catch (Exception e) {
78             logger.error("put threw: ", e);
79             return null;
80         }
81         return sendRequest(put);
82     }
83
84     /**
85      * Perform REST Post.
86      *
87      * @param url         the url
88      * @param username    the user name
89      * @param password    the password
90      * @param headers     any headers
91      * @param contentType what the content type is
92      * @param body        body to send
93      * @return the response status code and the body
94      */
95     public Pair<Integer, String> post(String url, String username, String password,
96                                       Map<String, String> headers, String contentType, String body) {
97         HttpPost post = new HttpPost(url);
98         addHeaders(post, username, password, headers);
99         post.addHeader("Content-Type", contentType);
100         try {
101             StringEntity input = new StringEntity(body);
102             input.setContentType(contentType);
103             post.setEntity(input);
104         } catch (Exception e) {
105             logger.error("post threw: ", e);
106             return null;
107         }
108         return sendRequest(post);
109     }
110
111     /**
112      * Do a REST get.
113      *
114      * @param url      URL
115      * @param username user name
116      * @param password password
117      * @param headers  any headers to add
118      * @return a Pair for the response status and the body
119      */
120     public Pair<Integer, String> get(String url, String username, String password,
121                                      Map<String, String> headers) {
122         HttpGet get = new HttpGet(url);
123         addHeaders(get, username, password, headers);
124         return sendRequest(get);
125     }
126
127     /**
128      * Perform REST Delete. <br/>
129      * <i>Note: Many REST endpoints will return a 400 error for delete requests with a non-empty body</i>
130      *
131      * @param url         the url
132      * @param username    the user name
133      * @param password    the password
134      * @param headers     any headers
135      * @param contentType what the content type is
136      * @param body        body (optional) to send
137      * @return the response status code and the body
138      */
139     public Pair<Integer, String> delete(String url, String username, String password, Map<String, String> headers,
140                                         String contentType, String body) {
141         HttpDeleteWithBody delete = new HttpDeleteWithBody(url);
142         addHeaders(delete, username, password, headers);
143         if (body != null && !body.isEmpty()) {
144             delete.addHeader("Content-Type", contentType);
145             try {
146                 StringEntity input = new StringEntity(body);
147                 input.setContentType(contentType);
148                 delete.setEntity(input);
149             } catch (Exception e) {
150                 logger.error("delete threw: ", e);
151                 return null;
152             }
153         }
154         return sendRequest(delete);
155     }
156
157     /**
158      * Perform REST Delete.
159      *
160      * @param url         the url
161      * @param username    the user name
162      * @param password    the password
163      * @param headers     any headers
164      * @return the response status code and the body
165      */
166     public Pair<Integer, String> delete(String url, String username, String password, Map<String, String> headers) {
167         HttpDelete delete = new HttpDelete(url);
168         addHeaders(delete, username, password, headers);
169         return sendRequest(delete);
170     }
171
172     /**
173      * Send REST request.
174      *
175      * @param request http request to send
176      * @return the response status code and the body
177      */
178     private Pair<Integer, String> sendRequest(HttpRequestBase request) {
179         if (logger.isDebugEnabled()) {
180             logger.debug("***** sendRequest to url {}:", request.getURI());
181         }
182
183         try (CloseableHttpClient client =
184                      HttpClientBuilder
185                              .create()
186                              .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
187                              .build()) {
188             HttpResponse response = client.execute(request);
189             if (response != null) {
190                 String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
191                 logger.debug("HTTP Response Status Code: {}",
192                         response.getStatusLine().getStatusCode());
193                 logger.debug("HTTP Response Body:");
194                 logger.debug(returnBody);
195
196                 return new Pair<>(response.getStatusLine().getStatusCode(),
197                         returnBody);
198             } else {
199                 logger.error("Response from {} is null", request.getURI());
200                 return null;
201             }
202         } catch (Exception e) {
203             logger.error("Request failed to {}", request.getURI(), e);
204             return null;
205         }
206     }
207
208     /**
209      * Add header to the request.
210      *
211      * @param request  http request to send
212      * @param username the user name
213      * @param password the password
214      * @param headers  any headers
215      */
216     private void addHeaders(HttpRequestBase request, String username, String password, Map<String,
217             String> headers) {
218         String authHeader = makeAuthHeader(username, password);
219         if (headers != null) {
220             for (Entry<String, String> entry : headers.entrySet()) {
221                 request.addHeader(entry.getKey(), headers.get(entry.getKey()));
222             }
223         }
224         if (authHeader != null) {
225             request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
226         }
227     }
228
229     private String makeAuthHeader(String username, String password) {
230         if (username == null || username.isEmpty()) {
231             return null;
232         }
233
234         String auth = username + ":" + (password == null ? "" : password);
235         return "Basic " + DatatypeConverter.printBase64Binary(auth.getBytes(Charset.forName("ISO-8859-1")));
236     }
237 }