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============================================
 
  36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 
  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)
 
 186          * Convenience method that builds and sends a POST request using properties
 
 187          * to build the URI and populate header with credentials.
 
 190          *            last component(s) of REST endpoint name; e.g., "users" or
 
 191          *            "user/ab1234/roles".
 
 192          * @return JSON string fetched
 
 194          *             if the HTTP response code is anything other than OK.
 
 196         public static String postJson(final SharedContextTestProperties properties, final String path, final String json)
 
 198                 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
 
 199                                 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
 
 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), //
 
 212          * Constructs and sends a POST request using the specified values.
 
 217          *            If true, uses https; else http.
 
 219          *            full path of the REST endpoint
 
 220          * @param headerUebkey
 
 221          * @param headerUsername
 
 222          * @param headerPassword
 
 225          * @return JSON result
 
 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)
 
 232                 URIBuilder builder = new URIBuilder();
 
 234                         builder.setScheme("https");
 
 236                         builder.setScheme("http");
 
 237                 builder.setHost(hostname);
 
 239                         builder.setPort(port);
 
 240                 builder.setPath(requestPath);
 
 241                 final URI uri = builder.build();
 
 243                 CloseableHttpClient httpClient;
 
 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() {
 
 249                                 public boolean isTrusted(final X509Certificate[] chain, final String authType)
 
 250                                                 throws CertificateException {
 
 254                         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
 
 255                                         NoopHostnameVerifier.INSTANCE);
 
 256                         httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
 
 258                         httpClient = HttpClients.createDefault();
 
 260                 HttpPost httpPost = new HttpPost(uri);
 
 261                 httpPost.setHeader("uebkey", headerUebkey);
 
 262                 httpPost.setHeader("username", headerUsername);
 
 263                 httpPost.setHeader("password", headerPassword);
 
 265                 StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
 
 266                 httpPost.setEntity(postEntity);
 
 268                 String responseJson = null;
 
 269                 CloseableHttpResponse response = null;
 
 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());
 
 277                         HttpEntity entity = response.getEntity();
 
 278                         if (entity == null) {
 
 279                                 logger.warn("Entity is null!");
 
 281                                 long len = entity.getContentLength();
 
 283                                         logger.warn("Content length is -1");
 
 285                                         responseJson = EntityUtils.toString(entity);
 
 286                                         logger.debug(responseJson);
 
 288                                         logger.warn("Not implemented - stream content");
 
 290                                 EntityUtils.consume(entity);
 
 293                         if (response != null)