2540cb27af192de60413903a9b28bdd053789b3d
[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 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.io.IOException;
24 import java.util.Map;
25 import java.util.Map.Entry;
26
27 import org.apache.http.HttpResponse;
28 import org.apache.http.auth.AuthScope;
29 import org.apache.http.auth.UsernamePasswordCredentials;
30 import org.apache.http.client.CredentialsProvider;
31 import org.apache.http.client.methods.HttpGet;
32 import org.apache.http.client.methods.HttpPost;
33 import org.apache.http.entity.StringEntity;
34 import org.apache.http.impl.client.BasicCredentialsProvider;
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 a;
47         public final B b;
48
49         public Pair(A a, B b) {
50             this.a = a;
51             this.b = b;
52         }
53     }
54
55     public Pair<Integer, String> post(String url, String username, String password,
56             Map<String, String> headers, String contentType, String body) {
57         CredentialsProvider credentials = new BasicCredentialsProvider();
58         credentials.setCredentials(AuthScope.ANY,
59                 new UsernamePasswordCredentials(username, password));
60
61         logger.debug("HTTP REQUEST: {} -> {} {} -> {}", url, username,
62                 ((password != null) ? password.length() : "-"), contentType);
63         if (headers != null) {
64             logger.debug("Headers: ");
65             headers.forEach((name, value) -> logger.debug("{} -> {}", name, value));
66         }
67         logger.debug(body);
68
69         try (CloseableHttpClient client =
70                 HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) {
71
72             HttpPost post = new HttpPost(url);
73             if (headers != null) {
74                 for (Entry<String, String> entry : headers.entrySet()) {
75                     post.addHeader(entry.getKey(), headers.get(entry.getKey()));
76                 }
77             }
78             post.addHeader("Content-Type", contentType);
79
80             StringEntity input = new StringEntity(body);
81             input.setContentType(contentType);
82             post.setEntity(input);
83
84             HttpResponse response = client.execute(post);
85             if (response != null) {
86                 String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
87                 logger.debug("HTTP POST Response Status Code: {}",
88                         response.getStatusLine().getStatusCode());
89                 logger.debug("HTTP POST Response Body:");
90                 logger.debug(returnBody);
91
92                 return new Pair<>(response.getStatusLine().getStatusCode(),
93                         returnBody);
94             }
95             else {
96                 logger.error("Response from {} is null", url);
97                 return null;
98             }
99         }
100         catch (Exception e) {
101             logger.error("Failed to POST to {}", url, e);
102             return null;
103         }
104     }
105
106     public Pair<Integer, String> get(String url, String username, String password,
107             Map<String, String> headers) {
108
109         CredentialsProvider credentials = new BasicCredentialsProvider();
110         credentials.setCredentials(AuthScope.ANY,
111                 new UsernamePasswordCredentials(username, password));
112
113         try (CloseableHttpClient client =
114                 HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) {
115
116             HttpGet get = new HttpGet(url);
117             if (headers != null) {
118                 for (Entry<String, String> entry : headers.entrySet()) {
119                     get.addHeader(entry.getKey(), headers.get(entry.getKey()));
120                 }
121             }
122
123             HttpResponse response = client.execute(get);
124
125             String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
126
127             logger.debug("HTTP GET Response Status Code: {}",
128                     response.getStatusLine().getStatusCode());
129             logger.debug("HTTP GET Response Body:");
130             logger.debug(returnBody);
131
132             return new Pair<>(response.getStatusLine().getStatusCode(), returnBody);
133         }
134         catch (IOException e) {
135             logger.error("Failed to GET to {}", url, e);
136             return null;
137         }
138     }
139 }