Security/ Package Name changes
[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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
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                 }
182                 return json;
183         }
184
185         /**
186          * Convenience method that builds and sends a POST request using properties
187          * to build the URI and populate header with credentials.
188          * 
189          * @param path
190          *            last component(s) of REST endpoint name; e.g., "users" or
191          *            "user/ab1234/roles".
192          * @return JSON string fetched
193          * @throws Exception
194          *             if the HTTP response code is anything other than OK.
195          */
196         public static String postJson(final SharedContextTestProperties properties, final String path, final String json)
197                         throws Exception {
198                 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
199                                 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
200                                 + '/' + path;
201                 return postJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), //
202                                 properties.getProperty(SharedContextTestProperties.PORT, -1), //
203                                 properties.getProperty(SharedContextTestProperties.SECURE, true), //
204                                 properties.getProperty(SharedContextTestProperties.UEBKEY), //
205                                 properties.getProperty(SharedContextTestProperties.USERNAME), //
206                                 properties.getProperty(SharedContextTestProperties.COUNTERSIGN), //
207                                 requestPath, //
208                                 json);
209         }
210
211         /**
212          * Constructs and sends a POST request using the specified values.
213          * 
214          * @param hostname
215          * @param port
216          * @param secure
217          *            If true, uses https; else http.
218          * @param requestPath
219          *            full path of the REST endpoint
220          * @param headerUebkey
221          * @param headerUsername
222          * @param headerPassword
223          * @param json
224          *            Content to post
225          * @return JSON result
226          * @throws Exception
227          */
228         public static String postJson(final String hostname, final int port, boolean secure, final String headerUebkey,
229                         final String headerUsername, final String headerPassword, final String requestPath, final String json)
230                         throws Exception {
231
232                 URIBuilder builder = new URIBuilder();
233                 if (secure)
234                         builder.setScheme("https");
235                 else
236                         builder.setScheme("http");
237                 builder.setHost(hostname);
238                 if (port > 0)
239                         builder.setPort(port);
240                 builder.setPath(requestPath);
241                 final URI uri = builder.build();
242
243                 CloseableHttpClient httpClient;
244                 if (secure) {
245                         // Tell HttpClient to accept any server certificate for HTTPS.
246                         // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error
247                         SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
248                                 @Override
249                                 public boolean isTrusted(final X509Certificate[] chain, final String authType)
250                                                 throws CertificateException {
251                                         return true;
252                                 }
253                         }).build();
254                         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
255                                         NoopHostnameVerifier.INSTANCE);
256                         httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
257                 } else {
258                         httpClient = HttpClients.createDefault();
259                 }
260                 HttpPost httpPost = new HttpPost(uri);
261                 httpPost.setHeader("uebkey", headerUebkey);
262                 httpPost.setHeader("username", headerUsername);
263                 httpPost.setHeader("password", headerPassword);
264
265                 StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
266                 httpPost.setEntity(postEntity);
267
268                 String responseJson = null;
269                 CloseableHttpResponse response = null;
270                 try {
271                         logger.debug("POST to " + uri);
272                         response = httpClient.execute(httpPost);
273                         logger.info("Status is " + response.getStatusLine());
274                         if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
275                                 throw new Exception("Status is " + response.getStatusLine().toString());
276
277                         HttpEntity entity = response.getEntity();
278                         if (entity == null) {
279                                 logger.warn("Entity is null!");
280                         } else {
281                                 long len = entity.getContentLength();
282                                 if (len < 0)
283                                         logger.warn("Content length is -1");
284                                 if (len < 2048) {
285                                         responseJson = EntityUtils.toString(entity);
286                                         logger.debug(responseJson);
287                                 } else {
288                                         logger.warn("Not implemented - stream content");
289                                 }
290                                 EntityUtils.consume(entity);
291                         }
292                 } finally {
293                         if (response != null)
294                                 response.close();
295                 }
296                 return responseJson;
297         }
298
299 }