2 * ================================================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ================================================================================
20 package org.openecomp.portalapp.portal.controller;
23 import java.security.cert.CertificateException;
24 import java.security.cert.X509Certificate;
26 import javax.net.ssl.SSLContext;
27 import javax.servlet.http.HttpServletResponse;
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogFactory;
31 import org.apache.http.Consts;
32 import org.apache.http.HttpEntity;
33 import org.apache.http.client.methods.CloseableHttpResponse;
34 import org.apache.http.client.methods.HttpGet;
35 import org.apache.http.client.methods.HttpPost;
36 import org.apache.http.client.utils.URIBuilder;
37 import org.apache.http.conn.ssl.NoopHostnameVerifier;
38 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
39 import org.apache.http.entity.ContentType;
40 import org.apache.http.entity.StringEntity;
41 import org.apache.http.impl.client.CloseableHttpClient;
42 import org.apache.http.impl.client.HttpClientBuilder;
43 import org.apache.http.impl.client.HttpClients;
44 import org.apache.http.ssl.SSLContexts;
45 import org.apache.http.ssl.TrustStrategy;
46 import org.apache.http.util.EntityUtils;
49 * Provides reusable features for test cases to get or post from an REST
50 * endpoint, allowing use of HTTPS connections to servers that use self-signed
53 public class SharedContextRestClient {
55 private static final Log logger = LogFactory.getLog(SharedContextRestClient.class);
58 * Convenience method that builds and sends a GET request using properties
59 * to build the URI and populate header with credentials.
62 * last component(s) of REST endpoint name; e.g., "get".
65 * @return JSON string fetched
67 * if the HTTP response code is anything other than OK.
69 public static String getJson(final SharedContextTestProperties properties, final String task,
70 final String contextId, final String contextKey) throws Exception {
71 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
72 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
74 return getJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), //
75 properties.getProperty(SharedContextTestProperties.PORT, -1), //
76 properties.getProperty(SharedContextTestProperties.SECURE, true), //
77 properties.getProperty(SharedContextTestProperties.UEBKEY), //
78 properties.getProperty(SharedContextTestProperties.USERNAME), //
79 properties.getProperty(SharedContextTestProperties.PASSWORD), requestPath, //
85 * Constructs and sends a GET request using the specified values.
91 * If true, uses https; else http.
93 * @param headerUsername
94 * @param headerPassword
96 * full path of the REST endpoint
100 * @return JSON result
102 public static String getJson(final String hostname, final int port, boolean secure, final String headerUebkey,
103 final String headerUsername, final String headerPassword, final String requestPath, final String contextId,
104 final String contextKey) throws Exception {
106 URIBuilder uriBuilder = new URIBuilder();
108 uriBuilder.setScheme("https");
110 uriBuilder.setScheme("http");
111 uriBuilder.setHost(hostname);
113 uriBuilder.setPort(port);
114 uriBuilder.setPath(requestPath);
115 uriBuilder.addParameter("context_id", contextId);
116 if (contextKey != null)
117 uriBuilder.addParameter("ckey", contextKey);
118 final URI uri = uriBuilder.build();
120 CloseableHttpClient httpClient;
122 // Tell HttpClient to accept any server certificate for HTTPS.
123 // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error
124 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
126 public boolean isTrusted(final X509Certificate[] chain, final String authType)
127 throws CertificateException {
131 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
132 NoopHostnameVerifier.INSTANCE);
133 httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
135 httpClient = HttpClients.createDefault();
138 HttpGet httpGet = new HttpGet(uri);
139 httpGet.setHeader("uebkey", headerUebkey);
140 httpGet.setHeader("username", headerUsername);
141 httpGet.setHeader("password", headerPassword);
144 CloseableHttpResponse response = null;
146 logger.debug("GET from " + uri);
147 response = httpClient.execute(httpGet);
148 logger.info("Status is " + response.getStatusLine());
149 if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
150 throw new Exception("Status is " + response.getStatusLine().toString());
151 HttpEntity entity = response.getEntity();
152 if (entity == null) {
153 logger.warn("Entity is null!");
155 // entity content length is never set.
156 // this naively tries to read everything.
157 json = EntityUtils.toString(entity);
158 EntityUtils.consume(entity);
161 if (response != null)
168 * Convenience method that builds and sends a POST request using properties
169 * to build the URI and populate header with credentials.
172 * last component(s) of REST endpoint name; e.g., "users" or
173 * "user/ab1234/roles".
174 * @return JSON string fetched
176 * if the HTTP response code is anything other than OK.
178 public static String postJson(final SharedContextTestProperties properties, final String path, final String json)
180 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
181 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
183 return postJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), //
184 properties.getProperty(SharedContextTestProperties.PORT, -1), //
185 properties.getProperty(SharedContextTestProperties.SECURE, true), //
186 properties.getProperty(SharedContextTestProperties.UEBKEY), //
187 properties.getProperty(SharedContextTestProperties.USERNAME), //
188 properties.getProperty(SharedContextTestProperties.PASSWORD), //
194 * Constructs and sends a POST request using the specified values.
199 * If true, uses https; else http.
201 * full path of the REST endpoint
202 * @param headerUebkey
203 * @param headerUsername
204 * @param headerPassword
207 * @return JSON result
210 public static String postJson(final String hostname, final int port, boolean secure, final String headerUebkey,
211 final String headerUsername, final String headerPassword, final String requestPath, final String json)
214 URIBuilder builder = new URIBuilder();
216 builder.setScheme("https");
218 builder.setScheme("http");
219 builder.setHost(hostname);
221 builder.setPort(port);
222 builder.setPath(requestPath);
223 final URI uri = builder.build();
225 CloseableHttpClient httpClient;
227 // Tell HttpClient to accept any server certificate for HTTPS.
228 // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error
229 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
231 public boolean isTrusted(final X509Certificate[] chain, final String authType)
232 throws CertificateException {
236 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
237 NoopHostnameVerifier.INSTANCE);
238 httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
240 httpClient = HttpClients.createDefault();
242 HttpPost httpPost = new HttpPost(uri);
243 httpPost.setHeader("uebkey", headerUebkey);
244 httpPost.setHeader("username", headerUsername);
245 httpPost.setHeader("password", headerPassword);
247 StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
248 httpPost.setEntity(postEntity);
250 String responseJson = null;
251 CloseableHttpResponse response = null;
253 logger.debug("POST to " + uri);
254 response = httpClient.execute(httpPost);
255 logger.info("Status is " + response.getStatusLine());
256 if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
257 throw new Exception("Status is " + response.getStatusLine().toString());
259 HttpEntity entity = response.getEntity();
260 if (entity == null) {
261 logger.warn("Entity is null!");
263 long len = entity.getContentLength();
265 logger.warn("Content length is -1");
267 responseJson = EntityUtils.toString(entity);
268 logger.debug(responseJson);
270 logger.warn("Not implemented - stream content");
272 EntityUtils.consume(entity);
275 if (response != null)