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