[PORTAL-7] Rebase
[portal.git] / ecomp-portal-BE-common / src / test / java / org / openecomp / portalapp / portal / controller / SharedContextRestClient.java
diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextRestClient.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextRestClient.java
new file mode 100644 (file)
index 0000000..fdafe5c
--- /dev/null
@@ -0,0 +1,281 @@
+/*-\r
+ * ================================================================================\r
+ * ECOMP Portal\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ================================================================================\r
+ */\r
+package org.openecomp.portalapp.portal.controller;\r
+\r
+import java.net.URI;\r
+import java.security.cert.CertificateException;\r
+import java.security.cert.X509Certificate;\r
+\r
+import javax.net.ssl.SSLContext;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import org.apache.commons.logging.Log;\r
+import org.apache.commons.logging.LogFactory;\r
+import org.apache.http.Consts;\r
+import org.apache.http.HttpEntity;\r
+import org.apache.http.client.methods.CloseableHttpResponse;\r
+import org.apache.http.client.methods.HttpGet;\r
+import org.apache.http.client.methods.HttpPost;\r
+import org.apache.http.client.utils.URIBuilder;\r
+import org.apache.http.conn.ssl.NoopHostnameVerifier;\r
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;\r
+import org.apache.http.entity.ContentType;\r
+import org.apache.http.entity.StringEntity;\r
+import org.apache.http.impl.client.CloseableHttpClient;\r
+import org.apache.http.impl.client.HttpClientBuilder;\r
+import org.apache.http.impl.client.HttpClients;\r
+import org.apache.http.ssl.SSLContexts;\r
+import org.apache.http.ssl.TrustStrategy;\r
+import org.apache.http.util.EntityUtils;\r
+\r
+/**\r
+ * Provides reusable features for test cases to get or post from an REST\r
+ * endpoint, allowing use of HTTPS connections to servers that use self-signed\r
+ * certificates.\r
+ */\r
+public class SharedContextRestClient {\r
+\r
+       private static final Log logger = LogFactory.getLog(SharedContextRestClient.class);\r
+\r
+       /**\r
+        * Convenience method that builds and sends a GET request using properties\r
+        * to build the URI and populate header with credentials.\r
+        * \r
+        * @param task\r
+        *            last component(s) of REST endpoint name; e.g., "get".\r
+        * @param contextId\r
+        * @param contextKey\r
+        * @return JSON string fetched\r
+        * @throws Exception\r
+        *             if the HTTP response code is anything other than OK.\r
+        */\r
+       public static String getJson(final SharedContextTestProperties properties, final String task,\r
+                       final String contextId, final String contextKey) throws Exception {\r
+               String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //\r
+                               + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //\r
+                               + '/' + task;\r
+               return getJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), //\r
+                               properties.getProperty(SharedContextTestProperties.PORT, -1), //\r
+                               properties.getProperty(SharedContextTestProperties.SECURE, true), //\r
+                               properties.getProperty(SharedContextTestProperties.UEBKEY), //\r
+                               properties.getProperty(SharedContextTestProperties.USERNAME), //\r
+                               properties.getProperty(SharedContextTestProperties.PASSWORD), requestPath, //\r
+                               contextId, //\r
+                               contextKey);\r
+       }\r
+\r
+       /**\r
+        * Constructs and sends a GET request using the specified values.\r
+        * \r
+        * @param hostname\r
+        * @param port\r
+        *            ignored if negative\r
+        * @param secure\r
+        *            If true, uses https; else http.\r
+        * @param headerUebkey\r
+        * @param headerUsername\r
+        * @param headerPassword\r
+        * @param requestPath\r
+        *            full path of the REST endpoint\r
+        * @param contextId\r
+        * @param contextKey\r
+        * Ignored if null\r
+        * @return JSON result\r
+        */\r
+       public static String getJson(final String hostname, final int port, boolean secure, final String headerUebkey,\r
+                       final String headerUsername, final String headerPassword, final String requestPath, final String contextId,\r
+                       final String contextKey) throws Exception {\r
+\r
+               URIBuilder uriBuilder = new URIBuilder();\r
+               if (secure)\r
+                       uriBuilder.setScheme("https");\r
+               else\r
+                       uriBuilder.setScheme("http");\r
+               uriBuilder.setHost(hostname);\r
+               if (port > 0)\r
+                       uriBuilder.setPort(port);\r
+               uriBuilder.setPath(requestPath);\r
+               uriBuilder.addParameter("context_id", contextId);\r
+               if (contextKey != null)\r
+                       uriBuilder.addParameter("ckey", contextKey);\r
+               final URI uri = uriBuilder.build();\r
+\r
+               CloseableHttpClient httpClient;\r
+               if (secure) {\r
+                       // Tell HttpClient to accept any server certificate for HTTPS.\r
+                       // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error\r
+                       SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {\r
+                               @Override\r
+                               public boolean isTrusted(final X509Certificate[] chain, final String authType)\r
+                                               throws CertificateException {\r
+                                       return true;\r
+                               }\r
+                       }).build();\r
+                       SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,\r
+                                       NoopHostnameVerifier.INSTANCE);\r
+                       httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();\r
+               } else {\r
+                       httpClient = HttpClients.createDefault();\r
+               }\r
+\r
+               HttpGet httpGet = new HttpGet(uri);\r
+               httpGet.setHeader("uebkey", headerUebkey);\r
+               httpGet.setHeader("username", headerUsername);\r
+               httpGet.setHeader("password", headerPassword);\r
+\r
+               String json = null;\r
+               CloseableHttpResponse response = null;\r
+               try {\r
+                       logger.debug("GET from " + uri);\r
+                       response = httpClient.execute(httpGet);\r
+                       logger.info("Status is " + response.getStatusLine());\r
+                       if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)\r
+                               throw new Exception("Status is " + response.getStatusLine().toString());\r
+                       HttpEntity entity = response.getEntity();\r
+                       if (entity == null) {\r
+                               logger.warn("Entity is null!");\r
+                       } else {\r
+                               // entity content length is never set.\r
+                               // this naively tries to read everything.\r
+                               json = EntityUtils.toString(entity);\r
+                               EntityUtils.consume(entity);\r
+                       }\r
+               } finally {\r
+                       if (response != null)\r
+                               response.close();\r
+               }\r
+               return json;\r
+       }\r
+\r
+       /**\r
+        * Convenience method that builds and sends a POST request using properties\r
+        * to build the URI and populate header with credentials.\r
+        * \r
+        * @param path\r
+        *            last component(s) of REST endpoint name; e.g., "users" or\r
+        *            "user/ab1234/roles".\r
+        * @return JSON string fetched\r
+        * @throws Exception\r
+        *             if the HTTP response code is anything other than OK.\r
+        */\r
+       public static String postJson(final SharedContextTestProperties properties, final String path, final String json)\r
+                       throws Exception {\r
+               String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //\r
+                               + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //\r
+                               + '/' + path;\r
+               return postJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), //\r
+                               properties.getProperty(SharedContextTestProperties.PORT, -1), //\r
+                               properties.getProperty(SharedContextTestProperties.SECURE, true), //\r
+                               properties.getProperty(SharedContextTestProperties.UEBKEY), //\r
+                               properties.getProperty(SharedContextTestProperties.USERNAME), //\r
+                               properties.getProperty(SharedContextTestProperties.PASSWORD), //\r
+                               requestPath, //\r
+                               json);\r
+       }\r
+\r
+       /**\r
+        * Constructs and sends a POST request using the specified values.\r
+        * \r
+        * @param hostname\r
+        * @param port\r
+        * @param secure\r
+        *            If true, uses https; else http.\r
+        * @param requestPath\r
+        *            full path of the REST endpoint\r
+        * @param headerUebkey\r
+        * @param headerUsername\r
+        * @param headerPassword\r
+        * @param json\r
+        *            Content to post\r
+        * @return JSON result\r
+        * @throws Exception\r
+        */\r
+       public static String postJson(final String hostname, final int port, boolean secure, final String headerUebkey,\r
+                       final String headerUsername, final String headerPassword, final String requestPath, final String json)\r
+                       throws Exception {\r
+\r
+               URIBuilder builder = new URIBuilder();\r
+               if (secure)\r
+                       builder.setScheme("https");\r
+               else\r
+                       builder.setScheme("http");\r
+               builder.setHost(hostname);\r
+               if (port > 0)\r
+                       builder.setPort(port);\r
+               builder.setPath(requestPath);\r
+               final URI uri = builder.build();\r
+\r
+               CloseableHttpClient httpClient;\r
+               if (secure) {\r
+                       // Tell HttpClient to accept any server certificate for HTTPS.\r
+                       // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error\r
+                       SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {\r
+                               @Override\r
+                               public boolean isTrusted(final X509Certificate[] chain, final String authType)\r
+                                               throws CertificateException {\r
+                                       return true;\r
+                               }\r
+                       }).build();\r
+                       SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,\r
+                                       NoopHostnameVerifier.INSTANCE);\r
+                       httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();\r
+               } else {\r
+                       httpClient = HttpClients.createDefault();\r
+               }\r
+               HttpPost httpPost = new HttpPost(uri);\r
+               httpPost.setHeader("uebkey", headerUebkey);\r
+               httpPost.setHeader("username", headerUsername);\r
+               httpPost.setHeader("password", headerPassword);\r
+\r
+               StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));\r
+               httpPost.setEntity(postEntity);\r
+\r
+               String responseJson = null;\r
+               CloseableHttpResponse response = null;\r
+               try {\r
+                       logger.debug("POST to " + uri);\r
+                       response = httpClient.execute(httpPost);\r
+                       logger.info("Status is " + response.getStatusLine());\r
+                       if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)\r
+                               throw new Exception("Status is " + response.getStatusLine().toString());\r
+\r
+                       HttpEntity entity = response.getEntity();\r
+                       if (entity == null) {\r
+                               logger.warn("Entity is null!");\r
+                       } else {\r
+                               long len = entity.getContentLength();\r
+                               if (len < 0)\r
+                                       logger.warn("Content length is -1");\r
+                               if (len < 2048) {\r
+                                       responseJson = EntityUtils.toString(entity);\r
+                                       logger.debug(responseJson);\r
+                               } else {\r
+                                       logger.warn("Not implemented - stream content");\r
+                               }\r
+                               EntityUtils.consume(entity);\r
+                       }\r
+               } finally {\r
+                       if (response != null)\r
+                               response.close();\r
+               }\r
+               return responseJson;\r
+       }\r
+\r
+}\r