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