2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.policy.rest;
24 import java.nio.charset.Charset;
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;
43 public class RestManager {
45 private static final Logger logger = LoggerFactory.getLogger(RestManager.class);
47 public class Pair<A, B> {
49 public final B second;
51 public Pair(A first, B second) {
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
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);
74 StringEntity input = new StringEntity(body);
75 input.setContentType(contentType);
77 } catch (Exception e) {
78 logger.error("put threw: ", e);
81 return sendRequest(put);
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
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);
101 StringEntity input = new StringEntity(body);
102 input.setContentType(contentType);
103 post.setEntity(input);
104 } catch (Exception e) {
105 logger.error("post threw: ", e);
108 return sendRequest(post);
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
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);
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>
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
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);
146 StringEntity input = new StringEntity(body);
147 input.setContentType(contentType);
148 delete.setEntity(input);
149 } catch (Exception e) {
150 logger.error("delete threw: ", e);
154 return sendRequest(delete);
158 * Perform REST Delete.
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
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);
175 * @param request http request to send
176 * @return the response status code and the body
178 private Pair<Integer, String> sendRequest(HttpRequestBase request) {
179 if (logger.isDebugEnabled()) {
180 logger.debug("***** sendRequest to url {}:", request.getURI());
183 try (CloseableHttpClient client =
186 .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
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);
196 return new Pair<>(response.getStatusLine().getStatusCode(),
199 logger.error("Response from {} is null", request.getURI());
202 } catch (Exception e) {
203 logger.error("Request failed to {}", request.getURI(), e);
209 * Add header to the request.
211 * @param request http request to send
212 * @param username the user name
213 * @param password the password
214 * @param headers any headers
216 private void addHeaders(HttpRequestBase request, String username, String password, Map<String,
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()));
224 if (authHeader != null) {
225 request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
229 private String makeAuthHeader(String username, String password) {
230 if (username == null || username.isEmpty()) {
234 String auth = username + ":" + (password == null ? "" : password);
235 return "Basic " + DatatypeConverter.printBase64Binary(auth.getBytes(Charset.forName("ISO-8859-1")));