Add health check to vLBMS
[demo.git] / vnfs / vLBMS / apis / health-vnf-onap-plugin / health-vnf-onap-plugin-impl / src / main / java / org / onap / vnf / health / RESTManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *
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.vnf.health;
22
23 import java.io.IOException;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import org.apache.http.HttpResponse;
27 import org.apache.http.auth.AuthScope;
28 import org.apache.http.auth.UsernamePasswordCredentials;
29 import org.apache.http.client.CredentialsProvider;
30 import org.apache.http.client.methods.HttpGet;
31 import org.apache.http.client.methods.HttpPost;
32 import org.apache.http.conn.ssl.NoopHostnameVerifier;
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
71                         .create()
72                         .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
73                         .setDefaultCredentialsProvider(credentials)
74                         .build()) {
75
76             HttpPost post = new HttpPost(url);
77             if (headers != null) {
78                 for (Entry<String, String> entry : headers.entrySet()) {
79                     post.addHeader(entry.getKey(), headers.get(entry.getKey()));
80                 }
81             }
82             post.addHeader("Content-Type", contentType);
83
84             StringEntity input = new StringEntity(body);
85             input.setContentType(contentType);
86             post.setEntity(input);
87
88             HttpResponse response = client.execute(post);
89             if (response != null) {
90                 String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
91                 logger.debug("HTTP POST Response Status Code: {}",
92                         response.getStatusLine().getStatusCode());
93                 logger.debug("HTTP POST Response Body:");
94                 logger.debug(returnBody);
95
96                 return new Pair<>(response.getStatusLine().getStatusCode(),
97                         returnBody);
98             }
99             else {
100                 logger.error("Response from {} is null", url);
101                 return null;
102             }
103         }
104         catch (Exception e) {
105             logger.error("Failed to POST to {}", url, e);
106             return null;
107         }
108     }
109
110     public Pair<Integer, String> get(String url, String username, String password,
111             Map<String, String> headers) {
112
113         CredentialsProvider credentials = new BasicCredentialsProvider();
114         credentials.setCredentials(AuthScope.ANY,
115                 new UsernamePasswordCredentials(username, password));
116
117         try (CloseableHttpClient client =
118                 HttpClientBuilder
119                         .create()
120                         .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
121                         .setDefaultCredentialsProvider(credentials)
122                         .build()) {
123
124             HttpGet get = new HttpGet(url);
125             if (headers != null) {
126                 for (Entry<String, String> entry : headers.entrySet()) {
127                     get.addHeader(entry.getKey(), headers.get(entry.getKey()));
128                 }
129             }
130
131             HttpResponse response = client.execute(get);
132
133             String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
134
135             logger.debug("HTTP GET Response Status Code: {}",
136                     response.getStatusLine().getStatusCode());
137             logger.debug("HTTP GET Response Body:");
138             logger.debug(returnBody);
139
140             return new Pair<>(response.getStatusLine().getStatusCode(), returnBody);
141         }
142         catch (IOException e) {
143             logger.error("Failed to GET to {}", url, e);
144             return null;
145         }
146     }
147 }