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