Update license; improve coverage; add docs dir
[portal.git] / ecomp-portal-BE-os / src / test / java / org / openecomp / portalapp / portal / controller / SharedContextRestClient.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright © 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.openecomp.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  * Provides reusable features for test cases to get or post from an REST
67  * endpoint, allowing use of HTTPS connections to servers that use self-signed
68  * certificates.
69  */
70 public class SharedContextRestClient {
71
72         private static final Log logger = LogFactory.getLog(SharedContextRestClient.class);
73
74         /**
75          * Convenience method that builds and sends a GET request using properties
76          * to build the URI and populate header with credentials.
77          * 
78          * @param task
79          *            last component(s) of REST endpoint name; e.g., "get".
80          * @param contextId
81          * @param contextKey
82          * @return JSON string fetched
83          * @throws Exception
84          *             if the HTTP response code is anything other than OK.
85          */
86         public static String getJson(final SharedContextTestProperties properties, final String task,
87                         final String contextId, final String contextKey) throws Exception {
88                 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
89                                 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
90                                 + '/' + task;
91                 return getJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), //
92                                 properties.getProperty(SharedContextTestProperties.PORT, -1), //
93                                 properties.getProperty(SharedContextTestProperties.SECURE, true), //
94                                 properties.getProperty(SharedContextTestProperties.UEBKEY), //
95                                 properties.getProperty(SharedContextTestProperties.USERNAME), //
96                                 properties.getProperty(SharedContextTestProperties.PASSWORD), requestPath, //
97                                 contextId, //
98                                 contextKey);
99         }
100
101         /**
102          * Constructs and sends a GET request using the specified values.
103          * 
104          * @param hostname
105          * @param port
106          *            ignored if negative
107          * @param secure
108          *            If true, uses https; else http.
109          * @param headerUebkey
110          * @param headerUsername
111          * @param headerPassword
112          * @param requestPath
113          *            full path of the REST endpoint
114          * @param contextId
115          * @param contextKey
116          * Ignored if null
117          * @return JSON result
118          */
119         public static String getJson(final String hostname, final int port, boolean secure, final String headerUebkey,
120                         final String headerUsername, final String headerPassword, final String requestPath, final String contextId,
121                         final String contextKey) throws Exception {
122
123                 URIBuilder uriBuilder = new URIBuilder();
124                 if (secure)
125                         uriBuilder.setScheme("https");
126                 else
127                         uriBuilder.setScheme("http");
128                 uriBuilder.setHost(hostname);
129                 if (port > 0)
130                         uriBuilder.setPort(port);
131                 uriBuilder.setPath(requestPath);
132                 uriBuilder.addParameter("context_id", contextId);
133                 if (contextKey != null)
134                         uriBuilder.addParameter("ckey", contextKey);
135                 final URI uri = uriBuilder.build();
136
137                 CloseableHttpClient httpClient;
138                 if (secure) {
139                         // Tell HttpClient to accept any server certificate for HTTPS.
140                         // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error
141                         SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
142                                 @Override
143                                 public boolean isTrusted(final X509Certificate[] chain, final String authType)
144                                                 throws CertificateException {
145                                         return true;
146                                 }
147                         }).build();
148                         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
149                                         NoopHostnameVerifier.INSTANCE);
150                         httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
151                 } else {
152                         httpClient = HttpClients.createDefault();
153                 }
154
155                 HttpGet httpGet = new HttpGet(uri);
156                 httpGet.setHeader("uebkey", headerUebkey);
157                 httpGet.setHeader("username", headerUsername);
158                 httpGet.setHeader("password", headerPassword);
159
160                 String json = null;
161                 CloseableHttpResponse response = null;
162                 try {
163                         logger.debug("GET from " + uri);
164                         response = httpClient.execute(httpGet);
165                         logger.info("Status is " + response.getStatusLine());
166                         if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
167                                 throw new Exception("Status is " + response.getStatusLine().toString());
168                         HttpEntity entity = response.getEntity();
169                         if (entity == null) {
170                                 logger.warn("Entity is null!");
171                         } else {
172                                 // entity content length is never set.
173                                 // this naively tries to read everything.
174                                 json = EntityUtils.toString(entity);
175                                 EntityUtils.consume(entity);
176                         }
177                 } finally {
178                         if (response != null)
179                                 response.close();
180                 }
181                 return json;
182         }
183
184         /**
185          * Convenience method that builds and sends a POST request using properties
186          * to build the URI and populate header with credentials.
187          * 
188          * @param path
189          *            last component(s) of REST endpoint name; e.g., "users" or
190          *            "user/{userid}/roles".
191          * @return JSON string fetched
192          * @throws Exception
193          *             if the HTTP response code is anything other than OK.
194          */
195         public static String postJson(final SharedContextTestProperties properties, final String path, final String json)
196                         throws Exception {
197                 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
198                                 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
199                                 + '/' + path;
200                 return postJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), //
201                                 properties.getProperty(SharedContextTestProperties.PORT, -1), //
202                                 properties.getProperty(SharedContextTestProperties.SECURE, true), //
203                                 properties.getProperty(SharedContextTestProperties.UEBKEY), //
204                                 properties.getProperty(SharedContextTestProperties.USERNAME), //
205                                 properties.getProperty(SharedContextTestProperties.PASSWORD), //
206                                 requestPath, //
207                                 json);
208         }
209
210         /**
211          * Constructs and sends a POST request using the specified values.
212          * 
213          * @param hostname
214          * @param port
215          * @param secure
216          *            If true, uses https; else http.
217          * @param requestPath
218          *            full path of the REST endpoint
219          * @param headerUebkey
220          * @param headerUsername
221          * @param headerPassword
222          * @param json
223          *            Content to post
224          * @return JSON result
225          * @throws Exception
226          */
227         public static String postJson(final String hostname, final int port, boolean secure, final String headerUebkey,
228                         final String headerUsername, final String headerPassword, final String requestPath, final String json)
229                         throws Exception {
230
231                 URIBuilder builder = new URIBuilder();
232                 if (secure)
233                         builder.setScheme("https");
234                 else
235                         builder.setScheme("http");
236                 builder.setHost(hostname);
237                 if (port > 0)
238                         builder.setPort(port);
239                 builder.setPath(requestPath);
240                 final URI uri = builder.build();
241
242                 CloseableHttpClient httpClient;
243                 if (secure) {
244                         // Tell HttpClient to accept any server certificate for HTTPS.
245                         // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error
246                         SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
247                                 @Override
248                                 public boolean isTrusted(final X509Certificate[] chain, final String authType)
249                                                 throws CertificateException {
250                                         return true;
251                                 }
252                         }).build();
253                         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
254                                         NoopHostnameVerifier.INSTANCE);
255                         httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
256                 } else {
257                         httpClient = HttpClients.createDefault();
258                 }
259                 HttpPost httpPost = new HttpPost(uri);
260                 httpPost.setHeader("uebkey", headerUebkey);
261                 httpPost.setHeader("username", headerUsername);
262                 httpPost.setHeader("password", headerPassword);
263
264                 StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
265                 httpPost.setEntity(postEntity);
266
267                 String responseJson = null;
268                 CloseableHttpResponse response = null;
269                 try {
270                         logger.debug("POST to " + uri);
271                         response = httpClient.execute(httpPost);
272                         logger.info("Status is " + response.getStatusLine());
273                         if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
274                                 throw new Exception("Status is " + response.getStatusLine().toString());
275
276                         HttpEntity entity = response.getEntity();
277                         if (entity == null) {
278                                 logger.warn("Entity is null!");
279                         } else {
280                                 long len = entity.getContentLength();
281                                 if (len < 0)
282                                         logger.warn("Content length is -1");
283                                 if (len < 2048) {
284                                         responseJson = EntityUtils.toString(entity);
285                                         logger.debug(responseJson);
286                                 } else {
287                                         logger.warn("Not implemented - stream content");
288                                 }
289                                 EntityUtils.consume(entity);
290                         }
291                 } finally {
292                         if (response != null)
293                                 response.close();
294                 }
295                 return responseJson;
296         }
297
298 }