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