2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 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============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
38 package org.openecomp.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;
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
70 public class SharedContextRestClient {
72 private static final Log logger = LogFactory.getLog(SharedContextRestClient.class);
75 * Convenience method that builds and sends a GET request using properties
76 * to build the URI and populate header with credentials.
79 * last component(s) of REST endpoint name; e.g., "get".
82 * @return JSON string fetched
84 * if the HTTP response code is anything other than OK.
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) //
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, //
102 * Constructs and sends a GET request using the specified values.
106 * ignored if negative
108 * If true, uses https; else http.
109 * @param headerUebkey
110 * @param headerUsername
111 * @param headerPassword
113 * full path of the REST endpoint
117 * @return JSON result
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 {
123 URIBuilder uriBuilder = new URIBuilder();
125 uriBuilder.setScheme("https");
127 uriBuilder.setScheme("http");
128 uriBuilder.setHost(hostname);
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();
137 CloseableHttpClient httpClient;
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() {
143 public boolean isTrusted(final X509Certificate[] chain, final String authType)
144 throws CertificateException {
148 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
149 NoopHostnameVerifier.INSTANCE);
150 httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
152 httpClient = HttpClients.createDefault();
155 HttpGet httpGet = new HttpGet(uri);
156 httpGet.setHeader("uebkey", headerUebkey);
157 httpGet.setHeader("username", headerUsername);
158 httpGet.setHeader("password", headerPassword);
161 CloseableHttpResponse response = null;
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!");
172 // entity content length is never set.
173 // this naively tries to read everything.
174 json = EntityUtils.toString(entity);
175 EntityUtils.consume(entity);
178 if (response != null)
185 * Convenience method that builds and sends a POST request using properties
186 * to build the URI and populate header with credentials.
189 * last component(s) of REST endpoint name; e.g., "users" or
190 * "user/{userid}/roles".
191 * @return JSON string fetched
193 * if the HTTP response code is anything other than OK.
195 public static String postJson(final SharedContextTestProperties properties, final String path, final String json)
197 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
198 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
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), //
211 * Constructs and sends a POST request using the specified values.
216 * If true, uses https; else http.
218 * full path of the REST endpoint
219 * @param headerUebkey
220 * @param headerUsername
221 * @param headerPassword
224 * @return JSON result
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)
231 URIBuilder builder = new URIBuilder();
233 builder.setScheme("https");
235 builder.setScheme("http");
236 builder.setHost(hostname);
238 builder.setPort(port);
239 builder.setPath(requestPath);
240 final URI uri = builder.build();
242 CloseableHttpClient httpClient;
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() {
248 public boolean isTrusted(final X509Certificate[] chain, final String authType)
249 throws CertificateException {
253 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
254 NoopHostnameVerifier.INSTANCE);
255 httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
257 httpClient = HttpClients.createDefault();
259 HttpPost httpPost = new HttpPost(uri);
260 httpPost.setHeader("uebkey", headerUebkey);
261 httpPost.setHeader("username", headerUsername);
262 httpPost.setHeader("password", headerPassword);
264 StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
265 httpPost.setEntity(postEntity);
267 String responseJson = null;
268 CloseableHttpResponse response = null;
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());
276 HttpEntity entity = response.getEntity();
277 if (entity == null) {
278 logger.warn("Entity is null!");
280 long len = entity.getContentLength();
282 logger.warn("Content length is -1");
284 responseJson = EntityUtils.toString(entity);
285 logger.debug(responseJson);
287 logger.warn("Not implemented - stream content");
289 EntityUtils.consume(entity);
292 if (response != null)