44177466d7bbe3d26db3caca28af1391864c974f
[portal/sdk.git] /
1 /*-
2  * ================================================================================
3  * ECOMP Portal SDK
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.portalsdk.core.onboarding.rest;
21
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.InputStreamReader;
25 import java.net.HttpURLConnection;
26 import java.net.URL;
27 import java.util.Base64;
28 import java.util.UUID;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
33 import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
34
35 /**
36  * Simple REST client for GET-ing content from and POST-ing content , Delete to the
37  * Portal application.
38  */
39 public class RestWebServiceClient {
40
41         private final Log logger = LogFactory.getLog(RestWebServiceClient.class);
42
43         /**
44          * Singleton instance
45          */
46         private static RestWebServiceClient instance = null;
47
48         /**
49          * Constructor is private. Clients should obtain an instance via
50          * getInstance().
51          */
52         private RestWebServiceClient() {
53         }
54
55         /**
56          * Gets the static instance of RestWebServiceClient; creates it if
57          * necessary. Synchronized to be thread safe.
58          * 
59          * @return Static instance of RestWebServiceClient.
60          */
61         public static synchronized RestWebServiceClient getInstance() {
62                 if (instance == null)
63                         instance = new RestWebServiceClient();
64                 return instance;
65         }
66
67         /**
68          * Convenience method that fetches the URL for the Portal REST API endpoint
69          * and the application UEB key, then calls
70          * {@link #get(String, String, String, String, String, String, String)} to
71          * access the Portal's REST endpoint.
72          * 
73          * @param restPath
74          *            Partial path of the endpoint; e.g., "/specialRestService"
75          * @param userId
76          *            userId for the user originating the request
77          * @param appName
78          *            Application Name for logging.
79          * @param requestId
80          *            128-bit UUID value to uniquely identify the transaction.
81          * @param appUserName
82          *            REST API user name for Portal to authenticate the request
83          * @param appPassword
84          *            REST API password (in the clear, not encrypted) for Portal to
85          *            authenticate the request
86          * @return Content from REST endpoint
87          * @throws Exception
88          *             on any failure
89          */
90         public String getPortalContent(String restPath,String userId, String appName, String requestId, String appUserName, String appPassword, boolean isBasicAuth) throws Exception {
91         String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
92
93                 if (restURL == null) {
94                         // should never happen
95                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
96                         logger.error(msg);
97                         throw new Exception(msg);
98                 }
99                 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
100
101                 if (appUebKey == null) {
102                         // should never happen
103                 String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
104
105                         logger.error(msg);
106                         throw new Exception(msg);
107                 }
108                 final String restEndpointUrl = restURL + restPath;
109                 if(isBasicAuth)
110                 {
111                         return get(restEndpointUrl, userId,appName, requestId, appUebKey, appUserName, appPassword,isBasicAuth);
112                 }
113                 return get(restEndpointUrl, userId,appName, requestId, appUebKey, appUserName, appPassword);
114         }
115
116         
117         /**
118          * Makes a call to a Portal REST API using the specified URL and parameters.
119          * 
120          * @param url
121          *            Complete URL of the REST endpoint.
122          * @param loginId
123          *            User that it should be fetching the data
124          * @param appName
125          *            Application name for logging; if null or empty, defaulted to
126          *            Unknown.
127          * @param requestId
128          *            128-bit UUID value to uniquely identify the transaction; if
129          *            null or empty, one is generated.
130          * @param appUebKey
131          *            Unique key for the application, used by Portal to authenticate
132          *            the request
133          * @param appUserName
134          *            REST API user name, used by Portal to authenticate the request
135          * @param appPassword
136          *            REST API password, used by Portal to authenticate the request
137          * @return Content from REST endpoint
138          * @throws Exception
139          *             On any failure; e.g., unknown host.
140          */
141         
142         public String get(String url, String loginId, String appName, String requestId, String appUebKey,
143                         String appUserName, String appPassword) throws Exception {
144                 return get(url, loginId, appName,requestId, appUebKey, appUserName, appPassword, false);
145         }
146         
147         
148         /**
149          * Makes a call to a Portal REST API using the specified URL and parameters.
150          * 
151          * @param url
152          *            Complete URL of the REST endpoint.
153          * @param loginId
154          *            User that it should be fetching the data
155          * @param appName
156          *            Application name for logging; if null or empty, defaulted to
157          *            Unknown.
158          * @param requestId
159          *            128-bit UUID value to uniquely identify the transaction; if
160          *            null or empty, one is generated.
161          * @param appUebKey
162          *            Unique key for the application, used by Portal to authenticate
163          *            the request
164          * @param appUserName
165          *            REST API user name, used by Portal to authenticate the request
166          * @param appPassword
167          *            REST API password, used by Portal to authenticate the request
168          * @return Content from REST endpoint
169          * @throws Exception
170          *             On any failure; e.g., unknown host.
171          */
172         public String get(String url, String loginId, String appName, String requestId, String appUebKey,
173                         String appUserName, String appPassword, Boolean useBasicAuth) throws Exception {
174
175                 logger.debug("RestWebServiceClient.get (" + url + ") operation is started.");
176
177                 if (appName == null || appName.trim().length() == 0)
178                         appName = "Unknown";
179                 if (requestId == null || requestId.trim().length() == 0)
180                         requestId = UUID.randomUUID().toString();
181
182                 URL obj = new URL(url);
183                 // Create the connection object
184                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
185                 con.setRequestMethod("GET");
186                 
187                 con.setConnectTimeout(3000);
188                 // if the portal property is set then gets the timeout value from portal properties
189                 if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)!= null){
190                         con.setConnectTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)));
191             }
192                 con.setReadTimeout(8000);
193                 if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)!= null){
194                         con.setReadTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)));
195             }
196
197                 // add request header
198                 con.setRequestProperty("uebkey", appUebKey);
199                 con.setRequestProperty("LoginId", loginId);
200                 con.setRequestProperty("user-agent", appName);
201                 con.setRequestProperty("X-ECOMP-RequestID", requestId);
202                 con.setRequestProperty("username", appUserName);
203                 con.setRequestProperty("password", appPassword);
204                         
205                         if(useBasicAuth){
206                         String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
207                         con.setRequestProperty("Authorization", "Basic "+ encoding);
208                         }
209                 
210                 int responseCode = con.getResponseCode();
211                 logger.debug("get: received response code '" + responseCode + "' while getting the '" + url + "' for user: "
212                                 + loginId);
213
214                 StringBuffer sb = new StringBuffer();
215                 BufferedReader in = null;
216                 try {
217                         in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
218                         String inputLine = null;
219                         while ((inputLine = in.readLine()) != null)
220                                 sb.append(inputLine);
221                 } finally {
222                         try {
223                                 if (in != null)
224                                         in.close();
225                         } catch (IOException ex) {
226                                 logger.error("get: failed to close reader", ex);
227                         }
228                 }
229
230                 final String response = sb.toString();
231                 if (logger.isDebugEnabled())
232                         logger.debug("get: url " + url + " yielded " + response);
233                 return response;
234         }
235         
236         /**
237          * Convenience method that fetches the URL for the Portal REST API endpoint
238          * and the application UEB key, then calls
239          * {@link #post(String, String, String, String, String, String, String, String, String)}
240          * to access the Portal's REST endpoint.
241          * 
242          * @param restPath
243          *            Partial path of the endpoint; e.g., "/specialRestService"
244          * @param userId
245          *            ID for the user originating the request
246          * @param appName
247          *            Application Name for logging.
248          * @param requestId
249          *            128-bit UUID value to uniquely identify the transaction.
250          * @param appUserName
251          *            REST API user name for Portal to authenticate the request;
252          *            ignored if null
253          * @param appPassword
254          *            REST API password (in the clear, not encrypted) for Portal to
255          *            authenticate the request; ignored if null
256          * @param contentType
257          *            content type for header
258          * @param content
259          *            String to post
260          * @return Content from REST endpoint
261          * @throws Exception
262          *             on any failure
263          */
264         public String postPortalContent(String restPath, String userId, String appName, String requestId,
265                         String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) throws Exception {
266                 String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
267
268                 
269                 if (restURL == null) {
270                         // should never happen
271                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
272
273                         logger.error(msg);
274                         throw new Exception(msg);
275                 }
276                 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
277
278                 if (appUebKey == null) {
279                         // should never happen
280                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
281
282                         logger.error(msg);
283                         throw new Exception(msg);
284                 }
285                 final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/";
286                 final String restEndpointUrl = restURL + separator + restPath;
287                 return post(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType,
288                                 content,isBasicAuth);
289         }
290
291         /**
292          * Makes a POST call to a Portal REST API using the specified URL and
293          * parameters.
294          * 
295          * @param url
296          *            Complete URL of the REST endpoint.
297          * @param loginId
298          *            User who is fetching the data
299          * @param appName
300          *            Application name for logging; if null or empty, defaulted to
301          *            Unknown.
302          * @param requestId
303          *            128-bit UUID value to uniquely identify the transaction; if
304          *            null or empty, one is generated.
305          * @param appUebKey
306          *            Unique key for the application, used by Portal to authenticate
307          *            the request
308          * @param appUserName
309          *            REST API user name used by Portal to authenticate the request;
310          *            ignored if null
311          * @param appPassword
312          *            REST API password used by Portal to authenticate the request;
313          *            ignored if null
314          * @param contentType
315          *            MIME header
316          * @param content
317          *            Content to POST
318          * @return Any content read from the endpoint
319          * @throws Exception
320          *             On any error
321          */
322         public String post(String url, String loginId, String appName, String requestId, String appUebKey,
323                         String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) throws Exception {
324
325                 if (logger.isDebugEnabled())
326                         logger.debug("RestWebServiceClient.post to URL " + url);
327                 if (appName == null || appName.trim().length() == 0)
328                         appName = "Unknown";
329                 if (requestId == null || requestId.trim().length() == 0)
330                         requestId = UUID.randomUUID().toString();
331
332                 URL obj = new URL(url);
333                 // Create the connection object
334                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
335                 con.setRequestMethod("POST");
336                 
337                 con.setConnectTimeout(3000);
338                 // if the portal property is set then gets the timeout value from portal properties
339                 if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)!= null){
340                         con.setConnectTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)));
341             }
342                 con.setReadTimeout(15000);
343                 if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)!= null){
344                         con.setReadTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)));
345             }
346                 
347                 // add request header
348                 con.setRequestProperty("uebkey", appUebKey);
349                 if (appUserName != null)
350                         con.setRequestProperty("username", appUserName);
351                 if (appPassword != null)
352                         con.setRequestProperty("password", appPassword);
353                 con.setRequestProperty("LoginId", loginId);
354                 con.setRequestProperty("user-agent", appName);
355                 con.setRequestProperty("X-ECOMP-RequestID", requestId);
356                 con.setRequestProperty("Content-Type", contentType);
357                 if(isBasicAuth){
358                         String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
359                         con.setRequestProperty("Authorization", "Basic "+ encoding);
360                         }
361
362                 con.setDoInput(true);
363                 con.setDoOutput(true);
364                 if( content != null)
365                 {
366                 con.getOutputStream().write(content.getBytes());
367                 }
368                 con.getOutputStream().flush();
369                 con.getOutputStream().close();
370
371                 int responseCode = con.getResponseCode();
372                 logger.debug("Response Code : " + responseCode);
373
374                 StringBuffer sb = new StringBuffer();
375                 InputStreamReader in = null;
376                 char[] buf = new char[8196];
377                 int bytes;
378                 try {
379                         in = new InputStreamReader(con.getInputStream(), "UTF-8");
380                         while ((bytes = in.read(buf)) > 0)
381                                 sb.append(new String(buf, 0, bytes));
382                 } finally {
383                         try {
384                                 if (in != null)
385                                         in.close();
386                         } catch (IOException ex) {
387                                 logger.warn("get: failed to close reader", ex);
388                         }
389                 }
390
391                 return sb.toString();
392         }
393         
394         
395         public String deletePortalContent(String restPath, String userId, String appName, String requestId,
396                         String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) throws Exception {
397                 String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
398
399                 if (restURL == null) {
400                         // should never happen
401                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
402
403                         logger.error(msg);
404                         throw new Exception(msg);
405                 }
406                 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
407
408                 if (appUebKey == null) {
409                         // should never happen
410                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
411
412                         logger.error(msg);
413                         throw new Exception(msg);
414                 }
415                 final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/";
416                 final String restEndpointUrl = restURL + separator + restPath;
417                 return delete(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType,
418                                 content,isBasicAuth);
419         }
420         
421         public String delete(String url, String loginId, String appName, String requestId, String appUebKey,
422                         String appUserName, String appPassword, String contentType, String content,boolean isBasicAuth) throws Exception {
423
424                 if (logger.isDebugEnabled())
425                         logger.debug("RestWebServiceClient.post to URL " + url);
426                 if (appName == null || appName.trim().length() == 0)
427                         appName = "Unknown";
428                 if (requestId == null || requestId.trim().length() == 0)
429                         requestId = UUID.randomUUID().toString();
430
431                 URL obj = new URL(url);
432                 // Create the connection object
433                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
434                 con.setRequestMethod("DELETE");
435                 con.setConnectTimeout(3000);
436                 // if the portal property is set then gets the timeout value from portal properties
437                 if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)!= null){
438                         con.setConnectTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)));
439             }
440                 con.setReadTimeout(15000);
441                 if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)!= null){
442                         con.setReadTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)));
443             }
444                 // add request header
445                 con.setRequestProperty("uebkey", appUebKey);
446                 if (appUserName != null)
447                         con.setRequestProperty("username", appUserName);
448                 if (appPassword != null)
449                         con.setRequestProperty("password", appPassword);
450                 con.setRequestProperty("LoginId", loginId);
451                 con.setRequestProperty("user-agent", appName);
452                 con.setRequestProperty("X-ECOMP-RequestID", requestId);
453                 con.setRequestProperty("Content-Type", contentType);
454                 if(isBasicAuth){
455                         String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
456                         con.setRequestProperty("Authorization", "Basic "+ encoding);
457                         }
458
459                 con.setDoInput(true);
460                 con.setDoOutput(true);
461                 if( content != null)
462                 {
463                 con.getOutputStream().write(content.getBytes());
464                 }
465                 con.getOutputStream().flush();
466                 con.getOutputStream().close();
467
468                 int responseCode = con.getResponseCode();
469                 logger.debug("Response Code : " + responseCode);
470
471                 StringBuffer sb = new StringBuffer();
472                 InputStreamReader in = null;
473                 char[] buf = new char[8196];
474                 int bytes;
475                 try {
476                         in = new InputStreamReader(con.getInputStream(), "UTF-8");
477                         while ((bytes = in.read(buf)) > 0)
478                                 sb.append(new String(buf, 0, bytes));
479                 } finally {
480                         try {
481                                 if (in != null)
482                                         in.close();
483                         } catch (IOException ex) {
484                                 logger.warn("get: failed to close reader", ex);
485                         }
486                 }
487
488                 return sb.toString();
489         }
490         
491
492         /**
493          * Basic unit test for the client to call Portal app on localhost.
494          * 
495          * @param args
496          *            Ignored
497          * @throws Exception
498          */
499         public static void main(String[] args) throws Exception {
500                 RestWebServiceClient client = RestWebServiceClient.getInstance();
501                 final String getUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/analytics";
502                 String get = client.get(getUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword", null);
503                 System.out.println("Get result:\n" + get);
504                 final String postUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/storeAnalytics";
505                 final String content = " { " + " \"action\"  : \"test1\", " + " \"page\"     : \"test2\", "
506                                 + " \"function\" : \"test3\", " + " \"userid\"   : \"ab1234\" " + "}";
507                 String post = client.post(postUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword",
508                                 "application/json", content, true);
509                 System.out.println("Post result:\n" + post);
510         }
511 }