[PORTAL-16 PORTAL-18] Widget ms; staging
[portal.git] / ecomp-portal-BE-common / src / test / java / org / openecomp / portalapp / portal / controller / SharedContextRestClient.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.controller;
21
22 import java.net.URI;
23 import java.security.cert.CertificateException;
24 import java.security.cert.X509Certificate;
25
26 import javax.net.ssl.SSLContext;
27 import javax.servlet.http.HttpServletResponse;
28
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;
47
48 /**
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
51  * certificates.
52  */
53 public class SharedContextRestClient {
54
55         private static final Log logger = LogFactory.getLog(SharedContextRestClient.class);
56
57         /**
58          * Convenience method that builds and sends a GET request using properties
59          * to build the URI and populate header with credentials.
60          * 
61          * @param task
62          *            last component(s) of REST endpoint name; e.g., "get".
63          * @param contextId
64          * @param contextKey
65          * @return JSON string fetched
66          * @throws Exception
67          *             if the HTTP response code is anything other than OK.
68          */
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) //
73                                 + '/' + task;
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, //
80                                 contextId, //
81                                 contextKey);
82         }
83
84         /**
85          * Constructs and sends a GET request using the specified values.
86          * 
87          * @param hostname
88          * @param port
89          *            ignored if negative
90          * @param secure
91          *            If true, uses https; else http.
92          * @param headerUebkey
93          * @param headerUsername
94          * @param headerPassword
95          * @param requestPath
96          *            full path of the REST endpoint
97          * @param contextId
98          * @param contextKey
99          * Ignored if null
100          * @return JSON result
101          */
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 {
105
106                 URIBuilder uriBuilder = new URIBuilder();
107                 if (secure)
108                         uriBuilder.setScheme("https");
109                 else
110                         uriBuilder.setScheme("http");
111                 uriBuilder.setHost(hostname);
112                 if (port > 0)
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();
119
120                 CloseableHttpClient httpClient;
121                 if (secure) {
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() {
125                                 @Override
126                                 public boolean isTrusted(final X509Certificate[] chain, final String authType)
127                                                 throws CertificateException {
128                                         return true;
129                                 }
130                         }).build();
131                         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
132                                         NoopHostnameVerifier.INSTANCE);
133                         httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
134                 } else {
135                         httpClient = HttpClients.createDefault();
136                 }
137
138                 HttpGet httpGet = new HttpGet(uri);
139                 httpGet.setHeader("uebkey", headerUebkey);
140                 httpGet.setHeader("username", headerUsername);
141                 httpGet.setHeader("password", headerPassword);
142
143                 String json = null;
144                 CloseableHttpResponse response = null;
145                 try {
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!");
154                         } else {
155                                 // entity content length is never set.
156                                 // this naively tries to read everything.
157                                 json = EntityUtils.toString(entity);
158                                 EntityUtils.consume(entity);
159                         }
160                 } finally {
161                         if (response != null)
162                                 response.close();
163                 }
164                 return json;
165         }
166
167         /**
168          * Convenience method that builds and sends a POST request using properties
169          * to build the URI and populate header with credentials.
170          * 
171          * @param path
172          *            last component(s) of REST endpoint name; e.g., "users" or
173          *            "user/ab1234/roles".
174          * @return JSON string fetched
175          * @throws Exception
176          *             if the HTTP response code is anything other than OK.
177          */
178         public static String postJson(final SharedContextTestProperties properties, final String path, final String json)
179                         throws Exception {
180                 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
181                                 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
182                                 + '/' + path;
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), //
189                                 requestPath, //
190                                 json);
191         }
192
193         /**
194          * Constructs and sends a POST request using the specified values.
195          * 
196          * @param hostname
197          * @param port
198          * @param secure
199          *            If true, uses https; else http.
200          * @param requestPath
201          *            full path of the REST endpoint
202          * @param headerUebkey
203          * @param headerUsername
204          * @param headerPassword
205          * @param json
206          *            Content to post
207          * @return JSON result
208          * @throws Exception
209          */
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)
212                         throws Exception {
213
214                 URIBuilder builder = new URIBuilder();
215                 if (secure)
216                         builder.setScheme("https");
217                 else
218                         builder.setScheme("http");
219                 builder.setHost(hostname);
220                 if (port > 0)
221                         builder.setPort(port);
222                 builder.setPath(requestPath);
223                 final URI uri = builder.build();
224
225                 CloseableHttpClient httpClient;
226                 if (secure) {
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() {
230                                 @Override
231                                 public boolean isTrusted(final X509Certificate[] chain, final String authType)
232                                                 throws CertificateException {
233                                         return true;
234                                 }
235                         }).build();
236                         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
237                                         NoopHostnameVerifier.INSTANCE);
238                         httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
239                 } else {
240                         httpClient = HttpClients.createDefault();
241                 }
242                 HttpPost httpPost = new HttpPost(uri);
243                 httpPost.setHeader("uebkey", headerUebkey);
244                 httpPost.setHeader("username", headerUsername);
245                 httpPost.setHeader("password", headerPassword);
246
247                 StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
248                 httpPost.setEntity(postEntity);
249
250                 String responseJson = null;
251                 CloseableHttpResponse response = null;
252                 try {
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());
258
259                         HttpEntity entity = response.getEntity();
260                         if (entity == null) {
261                                 logger.warn("Entity is null!");
262                         } else {
263                                 long len = entity.getContentLength();
264                                 if (len < 0)
265                                         logger.warn("Content length is -1");
266                                 if (len < 2048) {
267                                         responseJson = EntityUtils.toString(entity);
268                                         logger.debug(responseJson);
269                                 } else {
270                                         logger.warn("Not implemented - stream content");
271                                 }
272                                 EntityUtils.consume(entity);
273                         }
274                 } finally {
275                         if (response != null)
276                                 response.close();
277                 }
278                 return responseJson;
279         }
280
281 }