Bulk upload changes and music health check apis
[portal.git] / ecomp-portal-BE-common / src / test / java / org / onap / portalapp / portal / controller / SharedContextRestClient.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.portal.controller;
39
40 import java.net.URI;
41 import java.security.cert.CertificateException;
42 import java.security.cert.X509Certificate;
43
44 import javax.net.ssl.SSLContext;
45 import javax.servlet.http.HttpServletResponse;
46
47 import org.apache.commons.logging.Log;
48 import org.apache.commons.logging.LogFactory;
49 import org.apache.http.Consts;
50 import org.apache.http.HttpEntity;
51 import org.apache.http.client.methods.CloseableHttpResponse;
52 import org.apache.http.client.methods.HttpGet;
53 import org.apache.http.client.methods.HttpPost;
54 import org.apache.http.client.utils.URIBuilder;
55 import org.apache.http.conn.ssl.NoopHostnameVerifier;
56 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
57 import org.apache.http.entity.ContentType;
58 import org.apache.http.entity.StringEntity;
59 import org.apache.http.impl.client.CloseableHttpClient;
60 import org.apache.http.impl.client.HttpClientBuilder;
61 import org.apache.http.impl.client.HttpClients;
62 import org.apache.http.ssl.SSLContexts;
63 import org.apache.http.ssl.TrustStrategy;
64 import org.apache.http.util.EntityUtils;
65
66 /**
67  * Provides reusable features for test cases to get or post from an REST
68  * endpoint, allowing use of HTTPS connections to servers that use self-signed
69  * certificates.
70  */
71 public class SharedContextRestClient {
72
73         private static final Log logger = LogFactory.getLog(SharedContextRestClient.class);
74
75         /**
76          * Convenience method that builds and sends a GET request using properties
77          * to build the URI and populate header with credentials.
78          * 
79          * @param task
80          *            last component(s) of REST endpoint name; e.g., "get".
81          * @param contextId
82          * @param contextKey
83          * @return JSON string fetched
84          * @throws Exception
85          *             if the HTTP response code is anything other than OK.
86          */
87         public static String getJson(final SharedContextTestProperties properties, final String task,
88                         final String contextId, final String contextKey) throws Exception {
89                 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
90                                 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
91                                 + '/' + task;
92                 return getJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), //
93                                 properties.getProperty(SharedContextTestProperties.PORT, -1), //
94                                 properties.getProperty(SharedContextTestProperties.SECURE, true), //
95                                 properties.getProperty(SharedContextTestProperties.UEBKEY), //
96                                 properties.getProperty(SharedContextTestProperties.USERNAME), //
97                                 properties.getProperty(SharedContextTestProperties.COUNTERSIGN), requestPath, //
98                                 contextId, //
99                                 contextKey);
100         }
101
102         /**
103          * Constructs and sends a GET request using the specified values.
104          * 
105          * @param hostname
106          * @param port
107          *            ignored if negative
108          * @param secure
109          *            If true, uses https; else http.
110          * @param headerUebkey
111          * @param headerUsername
112          * @param headerPassword
113          * @param requestPath
114          *            full path of the REST endpoint
115          * @param contextId
116          * @param contextKey
117          * Ignored if null
118          * @return JSON result
119          */
120         public static String getJson(final String hostname, final int port, boolean secure, final String headerUebkey,
121                         final String headerUsername, final String headerPassword, final String requestPath, final String contextId,
122                         final String contextKey) throws Exception {
123
124                 URIBuilder uriBuilder = new URIBuilder();
125                 if (secure)
126                         uriBuilder.setScheme("https");
127                 else
128                         uriBuilder.setScheme("http");
129                 uriBuilder.setHost(hostname);
130                 if (port > 0)
131                         uriBuilder.setPort(port);
132                 uriBuilder.setPath(requestPath);
133                 uriBuilder.addParameter("context_id", contextId);
134                 if (contextKey != null)
135                         uriBuilder.addParameter("ckey", contextKey);
136                 final URI uri = uriBuilder.build();
137
138                 CloseableHttpClient httpClient;
139                 if (secure) {
140                         // Tell HttpClient to accept any server certificate for HTTPS.
141                         // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error
142                         SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
143                                 @Override
144                                 public boolean isTrusted(final X509Certificate[] chain, final String authType)
145                                                 throws CertificateException {
146                                         return true;
147                                 }
148                         }).build();
149                         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
150                                         NoopHostnameVerifier.INSTANCE);
151                         httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
152                 } else {
153                         httpClient = HttpClients.createDefault();
154                 }
155
156                 HttpGet httpGet = new HttpGet(uri);
157                 httpGet.setHeader("uebkey", headerUebkey);
158                 httpGet.setHeader("username", headerUsername);
159                 httpGet.setHeader("password", headerPassword);
160
161                 String json = null;
162                 CloseableHttpResponse response = null;
163                 try {
164                         logger.debug("GET from " + uri);
165                         response = httpClient.execute(httpGet);
166                         logger.info("Status is " + response.getStatusLine());
167                         if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
168                                 throw new Exception("Status is " + response.getStatusLine().toString());
169                         HttpEntity entity = response.getEntity();
170                         if (entity == null) {
171                                 logger.warn("Entity is null!");
172                         } else {
173                                 // entity content length is never set.
174                                 // this naively tries to read everything.
175                                 json = EntityUtils.toString(entity);
176                                 EntityUtils.consume(entity);
177                         }
178                 } finally {
179                         if (response != null)
180                                 response.close();
181                         httpClient.close();
182                 }
183                 return json;
184         }
185
186         /**
187          * Convenience method that builds and sends a POST request using properties
188          * to build the URI and populate header with credentials.
189          * 
190          * @param path
191          *            last component(s) of REST endpoint name; e.g., "users" or
192          *            "user/ab1234/roles".
193          * @return JSON string fetched
194          * @throws Exception
195          *             if the HTTP response code is anything other than OK.
196          */
197         public static String postJson(final SharedContextTestProperties properties, final String path, final String json)
198                         throws Exception {
199                 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
200                                 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
201                                 + '/' + path;
202                 return postJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), //
203                                 properties.getProperty(SharedContextTestProperties.PORT, -1), //
204                                 properties.getProperty(SharedContextTestProperties.SECURE, true), //
205                                 properties.getProperty(SharedContextTestProperties.UEBKEY), //
206                                 properties.getProperty(SharedContextTestProperties.USERNAME), //
207                                 properties.getProperty(SharedContextTestProperties.COUNTERSIGN), //
208                                 requestPath, //
209                                 json);
210         }
211
212         /**
213          * Constructs and sends a POST request using the specified values.
214          * 
215          * @param hostname
216          * @param port
217          * @param secure
218          *            If true, uses https; else http.
219          * @param requestPath
220          *            full path of the REST endpoint
221          * @param headerUebkey
222          * @param headerUsername
223          * @param headerPassword
224          * @param json
225          *            Content to post
226          * @return JSON result
227          * @throws Exception
228          */
229         public static String postJson(final String hostname, final int port, boolean secure, final String headerUebkey,
230                         final String headerUsername, final String headerPassword, final String requestPath, final String json)
231                         throws Exception {
232
233                 URIBuilder builder = new URIBuilder();
234                 if (secure)
235                         builder.setScheme("https");
236                 else
237                         builder.setScheme("http");
238                 builder.setHost(hostname);
239                 if (port > 0)
240                         builder.setPort(port);
241                 builder.setPath(requestPath);
242                 final URI uri = builder.build();
243
244                 CloseableHttpClient httpClient;
245                 if (secure) {
246                         // Tell HttpClient to accept any server certificate for HTTPS.
247                         // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error
248                         SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
249                                 @Override
250                                 public boolean isTrusted(final X509Certificate[] chain, final String authType)
251                                                 throws CertificateException {
252                                         return true;
253                                 }
254                         }).build();
255                         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
256                                         NoopHostnameVerifier.INSTANCE);
257                         httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
258                 } else {
259                         httpClient = HttpClients.createDefault();
260                 }
261                 HttpPost httpPost = new HttpPost(uri);
262                 httpPost.setHeader("uebkey", headerUebkey);
263                 httpPost.setHeader("username", headerUsername);
264                 httpPost.setHeader("password", headerPassword);
265
266                 StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
267                 httpPost.setEntity(postEntity);
268
269                 String responseJson = null;
270                 CloseableHttpResponse response = null;
271                 try {
272                         logger.debug("POST to " + uri);
273                         response = httpClient.execute(httpPost);
274                         logger.info("Status is " + response.getStatusLine());
275                         if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
276                                 throw new Exception("Status is " + response.getStatusLine().toString());
277
278                         HttpEntity entity = response.getEntity();
279                         if (entity == null) {
280                                 logger.warn("Entity is null!");
281                         } else {
282                                 long len = entity.getContentLength();
283                                 if (len < 0)
284                                         logger.warn("Content length is -1");
285                                 if (len < 2048) {
286                                         responseJson = EntityUtils.toString(entity);
287                                         logger.debug(responseJson);
288                                 } else {
289                                         logger.warn("Not implemented - stream content");
290                                 }
291                                 EntityUtils.consume(entity);
292                         }
293                 } finally {
294                         if (response != null)
295                                 response.close();
296                         httpClient.close();
297                 }
298                 return responseJson;
299         }
300
301 }