2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.controller;
41 import java.security.cert.CertificateException;
42 import java.security.cert.X509Certificate;
44 import javax.net.ssl.SSLContext;
45 import javax.servlet.http.HttpServletResponse;
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;
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
71 public class SharedContextRestClient {
73 private static final Log logger = LogFactory.getLog(SharedContextRestClient.class);
76 * Convenience method that builds and sends a GET request using properties
77 * to build the URI and populate header with credentials.
80 * last component(s) of REST endpoint name; e.g., "get".
83 * @return JSON string fetched
85 * if the HTTP response code is anything other than OK.
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) //
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, //
103 * Constructs and sends a GET request using the specified values.
107 * ignored if negative
109 * If true, uses https; else http.
110 * @param headerUebkey
111 * @param headerUsername
112 * @param headerPassword
114 * full path of the REST endpoint
118 * @return JSON result
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 {
124 URIBuilder uriBuilder = new URIBuilder();
126 uriBuilder.setScheme("https");
128 uriBuilder.setScheme("http");
129 uriBuilder.setHost(hostname);
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();
138 CloseableHttpClient httpClient;
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() {
144 public boolean isTrusted(final X509Certificate[] chain, final String authType)
145 throws CertificateException {
149 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
150 NoopHostnameVerifier.INSTANCE);
151 httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
153 httpClient = HttpClients.createDefault();
156 HttpGet httpGet = new HttpGet(uri);
157 httpGet.setHeader("uebkey", headerUebkey);
158 httpGet.setHeader("username", headerUsername);
159 httpGet.setHeader("password", headerPassword);
162 CloseableHttpResponse response = null;
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!");
173 // entity content length is never set.
174 // this naively tries to read everything.
175 json = EntityUtils.toString(entity);
176 EntityUtils.consume(entity);
179 if (response != null)
187 * Convenience method that builds and sends a POST request using properties
188 * to build the URI and populate header with credentials.
191 * last component(s) of REST endpoint name; e.g., "users" or
192 * "user/ab1234/roles".
193 * @return JSON string fetched
195 * if the HTTP response code is anything other than OK.
197 public static String postJson(final SharedContextTestProperties properties, final String path, final String json)
199 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
200 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
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), //
213 * Constructs and sends a POST request using the specified values.
218 * If true, uses https; else http.
220 * full path of the REST endpoint
221 * @param headerUebkey
222 * @param headerUsername
223 * @param headerPassword
226 * @return JSON result
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)
233 URIBuilder builder = new URIBuilder();
235 builder.setScheme("https");
237 builder.setScheme("http");
238 builder.setHost(hostname);
240 builder.setPort(port);
241 builder.setPath(requestPath);
242 final URI uri = builder.build();
244 CloseableHttpClient httpClient;
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() {
250 public boolean isTrusted(final X509Certificate[] chain, final String authType)
251 throws CertificateException {
255 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
256 NoopHostnameVerifier.INSTANCE);
257 httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
259 httpClient = HttpClients.createDefault();
261 HttpPost httpPost = new HttpPost(uri);
262 httpPost.setHeader("uebkey", headerUebkey);
263 httpPost.setHeader("username", headerUsername);
264 httpPost.setHeader("password", headerPassword);
266 StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
267 httpPost.setEntity(postEntity);
269 String responseJson = null;
270 CloseableHttpResponse response = null;
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());
278 HttpEntity entity = response.getEntity();
279 if (entity == null) {
280 logger.warn("Entity is null!");
282 long len = entity.getContentLength();
284 logger.warn("Content length is -1");
286 responseJson = EntityUtils.toString(entity);
287 logger.debug(responseJson);
289 logger.warn("Not implemented - stream content");
291 EntityUtils.consume(entity);
294 if (response != null)