c3ca243066920f198765c0ad38ae671f72fae233
[portal.git] / ecomp-portal-BE-os / 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  * Provides reusable features for test cases to get or post from an REST
49  * endpoint, allowing use of HTTPS connections to servers that use self-signed
50  * certificates.
51  */
52 public class SharedContextRestClient {
53
54         private static final Log logger = LogFactory.getLog(SharedContextRestClient.class);
55
56         /**
57          * Convenience method that builds and sends a GET request using properties
58          * to build the URI and populate header with credentials.
59          * 
60          * @param task
61          *            last component(s) of REST endpoint name; e.g., "get".
62          * @param contextId
63          * @param contextKey
64          * @return JSON string fetched
65          * @throws Exception
66          *             if the HTTP response code is anything other than OK.
67          */
68         public static String getJson(final SharedContextTestProperties properties, final String task,
69                         final String contextId, final String contextKey) throws Exception {
70                 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
71                                 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
72                                 + '/' + task;
73                 return getJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), //
74                                 properties.getProperty(SharedContextTestProperties.PORT, -1), //
75                                 properties.getProperty(SharedContextTestProperties.SECURE, true), //
76                                 properties.getProperty(SharedContextTestProperties.UEBKEY), //
77                                 properties.getProperty(SharedContextTestProperties.USERNAME), //
78                                 properties.getProperty(SharedContextTestProperties.PASSWORD), requestPath, //
79                                 contextId, //
80                                 contextKey);
81         }
82
83         /**
84          * Constructs and sends a GET request using the specified values.
85          * 
86          * @param hostname
87          * @param port
88          *            ignored if negative
89          * @param secure
90          *            If true, uses https; else http.
91          * @param headerUebkey
92          * @param headerUsername
93          * @param headerPassword
94          * @param requestPath
95          *            full path of the REST endpoint
96          * @param contextId
97          * @param contextKey
98          * Ignored if null
99          * @return JSON result
100          */
101         public static String getJson(final String hostname, final int port, boolean secure, final String headerUebkey,
102                         final String headerUsername, final String headerPassword, final String requestPath, final String contextId,
103                         final String contextKey) throws Exception {
104
105                 URIBuilder uriBuilder = new URIBuilder();
106                 if (secure)
107                         uriBuilder.setScheme("https");
108                 else
109                         uriBuilder.setScheme("http");
110                 uriBuilder.setHost(hostname);
111                 if (port > 0)
112                         uriBuilder.setPort(port);
113                 uriBuilder.setPath(requestPath);
114                 uriBuilder.addParameter("context_id", contextId);
115                 if (contextKey != null)
116                         uriBuilder.addParameter("ckey", contextKey);
117                 final URI uri = uriBuilder.build();
118
119                 CloseableHttpClient httpClient;
120                 if (secure) {
121                         // Tell HttpClient to accept any server certificate for HTTPS.
122                         // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error
123                         SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
124                                 @Override
125                                 public boolean isTrusted(final X509Certificate[] chain, final String authType)
126                                                 throws CertificateException {
127                                         return true;
128                                 }
129                         }).build();
130                         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
131                                         NoopHostnameVerifier.INSTANCE);
132                         httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
133                 } else {
134                         httpClient = HttpClients.createDefault();
135                 }
136
137                 HttpGet httpGet = new HttpGet(uri);
138                 httpGet.setHeader("uebkey", headerUebkey);
139                 httpGet.setHeader("username", headerUsername);
140                 httpGet.setHeader("password", headerPassword);
141
142                 String json = null;
143                 CloseableHttpResponse response = null;
144                 try {
145                         logger.debug("GET from " + uri);
146                         response = httpClient.execute(httpGet);
147                         logger.info("Status is " + response.getStatusLine());
148                         if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
149                                 throw new Exception("Status is " + response.getStatusLine().toString());
150                         HttpEntity entity = response.getEntity();
151                         if (entity == null) {
152                                 logger.warn("Entity is null!");
153                         } else {
154                                 // entity content length is never set.
155                                 // this naively tries to read everything.
156                                 json = EntityUtils.toString(entity);
157                                 EntityUtils.consume(entity);
158                         }
159                 } finally {
160                         if (response != null)
161                                 response.close();
162                 }
163                 return json;
164         }
165
166         /**
167          * Convenience method that builds and sends a POST request using properties
168          * to build the URI and populate header with credentials.
169          * 
170          * @param path
171          *            last component(s) of REST endpoint name; e.g., "users" or
172          *            "user/{userid}/roles".
173          * @return JSON string fetched
174          * @throws Exception
175          *             if the HTTP response code is anything other than OK.
176          */
177         public static String postJson(final SharedContextTestProperties properties, final String path, final String json)
178                         throws Exception {
179                 String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) //
180                                 + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) //
181                                 + '/' + path;
182                 return postJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), //
183                                 properties.getProperty(SharedContextTestProperties.PORT, -1), //
184                                 properties.getProperty(SharedContextTestProperties.SECURE, true), //
185                                 properties.getProperty(SharedContextTestProperties.UEBKEY), //
186                                 properties.getProperty(SharedContextTestProperties.USERNAME), //
187                                 properties.getProperty(SharedContextTestProperties.PASSWORD), //
188                                 requestPath, //
189                                 json);
190         }
191
192         /**
193          * Constructs and sends a POST request using the specified values.
194          * 
195          * @param hostname
196          * @param port
197          * @param secure
198          *            If true, uses https; else http.
199          * @param requestPath
200          *            full path of the REST endpoint
201          * @param headerUebkey
202          * @param headerUsername
203          * @param headerPassword
204          * @param json
205          *            Content to post
206          * @return JSON result
207          * @throws Exception
208          */
209         public static String postJson(final String hostname, final int port, boolean secure, final String headerUebkey,
210                         final String headerUsername, final String headerPassword, final String requestPath, final String json)
211                         throws Exception {
212
213                 URIBuilder builder = new URIBuilder();
214                 if (secure)
215                         builder.setScheme("https");
216                 else
217                         builder.setScheme("http");
218                 builder.setHost(hostname);
219                 if (port > 0)
220                         builder.setPort(port);
221                 builder.setPath(requestPath);
222                 final URI uri = builder.build();
223
224                 CloseableHttpClient httpClient;
225                 if (secure) {
226                         // Tell HttpClient to accept any server certificate for HTTPS.
227                         // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error
228                         SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
229                                 @Override
230                                 public boolean isTrusted(final X509Certificate[] chain, final String authType)
231                                                 throws CertificateException {
232                                         return true;
233                                 }
234                         }).build();
235                         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
236                                         NoopHostnameVerifier.INSTANCE);
237                         httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
238                 } else {
239                         httpClient = HttpClients.createDefault();
240                 }
241                 HttpPost httpPost = new HttpPost(uri);
242                 httpPost.setHeader("uebkey", headerUebkey);
243                 httpPost.setHeader("username", headerUsername);
244                 httpPost.setHeader("password", headerPassword);
245
246                 StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
247                 httpPost.setEntity(postEntity);
248
249                 String responseJson = null;
250                 CloseableHttpResponse response = null;
251                 try {
252                         logger.debug("POST to " + uri);
253                         response = httpClient.execute(httpPost);
254                         logger.info("Status is " + response.getStatusLine());
255                         if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
256                                 throw new Exception("Status is " + response.getStatusLine().toString());
257
258                         HttpEntity entity = response.getEntity();
259                         if (entity == null) {
260                                 logger.warn("Entity is null!");
261                         } else {
262                                 long len = entity.getContentLength();
263                                 if (len < 0)
264                                         logger.warn("Content length is -1");
265                                 if (len < 2048) {
266                                         responseJson = EntityUtils.toString(entity);
267                                         logger.debug(responseJson);
268                                 } else {
269                                         logger.warn("Not implemented - stream content");
270                                 }
271                                 EntityUtils.consume(entity);
272                         }
273                 } finally {
274                         if (response != null)
275                                 response.close();
276                 }
277                 return responseJson;
278         }
279
280 }