fa7a147899f1e04df53c298523be47ae194eaf8d
[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                 con.getOutputStream().write(content.getBytes());
365                 con.getOutputStream().flush();
366                 con.getOutputStream().close();
367
368                 int responseCode = con.getResponseCode();
369                 logger.debug("Response Code : " + responseCode);
370
371                 StringBuffer sb = new StringBuffer();
372                 InputStreamReader in = null;
373                 char[] buf = new char[8196];
374                 int bytes;
375                 try {
376                         in = new InputStreamReader(con.getInputStream(), "UTF-8");
377                         while ((bytes = in.read(buf)) > 0)
378                                 sb.append(new String(buf, 0, bytes));
379                 } finally {
380                         try {
381                                 if (in != null)
382                                         in.close();
383                         } catch (IOException ex) {
384                                 logger.warn("get: failed to close reader", ex);
385                         }
386                 }
387
388                 return sb.toString();
389         }
390         
391         
392         public String deletePortalContent(String restPath, String userId, String appName, String requestId,
393                         String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth ,String filter) throws Exception {
394                 String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
395
396                 if (restURL == null) {
397                         // should never happen
398                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
399
400                         logger.error(msg);
401                         throw new Exception(msg);
402                 }
403                 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
404
405                 if (appUebKey == null) {
406                         // should never happen
407                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
408
409                         logger.error(msg);
410                         throw new Exception(msg);
411                 }
412                 final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/";
413                 final String restEndpointUrl = restURL + separator + restPath;
414                 return delete(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType,
415                                 content,isBasicAuth,filter);
416         }
417         
418         public String delete(String url, String loginId, String appName, String requestId, String appUebKey,
419                         String appUserName, String appPassword, String contentType, String content,boolean isBasicAuth ,String filter) throws Exception {
420
421                 if (logger.isDebugEnabled())
422                         logger.debug("RestWebServiceClient.post to URL " + url);
423                 if (appName == null || appName.trim().length() == 0)
424                         appName = "Unknown";
425                 if (requestId == null || requestId.trim().length() == 0)
426                         requestId = UUID.randomUUID().toString();
427
428                 URL obj = new URL(url);
429                 // Create the connection object
430                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
431                 con.setRequestMethod("DELETE");
432                 con.setConnectTimeout(3000);
433                 // if the portal property is set then gets the timeout value from portal properties
434                 if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)!= null){
435                         con.setConnectTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)));
436             }
437                 con.setReadTimeout(15000);
438                 if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)!= null){
439                         con.setReadTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)));
440             }
441                 // add request header
442                 con.setRequestProperty("uebkey", appUebKey);
443                 if (appUserName != null)
444                         con.setRequestProperty("username", appUserName);
445                 if (appPassword != null)
446                         con.setRequestProperty("password", appPassword);
447                 con.setRequestProperty("LoginId", loginId);
448                 con.setRequestProperty("user-agent", appName);
449                 con.setRequestProperty("X-ECOMP-RequestID", requestId);
450                 con.setRequestProperty("Content-Type", contentType);
451                 con.setRequestProperty("filter", filter);
452                 if(isBasicAuth){
453                         String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
454                         con.setRequestProperty("Authorization", "Basic "+ encoding);
455                         }
456
457                 con.setDoInput(true);
458                 con.setDoOutput(true);
459                 con.getOutputStream().write(content.getBytes());
460                 con.getOutputStream().flush();
461                 con.getOutputStream().close();
462
463                 int responseCode = con.getResponseCode();
464                 logger.debug("Response Code : " + responseCode);
465
466                 StringBuffer sb = new StringBuffer();
467                 InputStreamReader in = null;
468                 char[] buf = new char[8196];
469                 int bytes;
470                 try {
471                         in = new InputStreamReader(con.getInputStream(), "UTF-8");
472                         while ((bytes = in.read(buf)) > 0)
473                                 sb.append(new String(buf, 0, bytes));
474                 } finally {
475                         try {
476                                 if (in != null)
477                                         in.close();
478                         } catch (IOException ex) {
479                                 logger.warn("get: failed to close reader", ex);
480                         }
481                 }
482
483                 return sb.toString();
484         }
485         
486
487         /**
488          * Basic unit test for the client to call Portal app on localhost.
489          * 
490          * @param args
491          *            Ignored
492          * @throws Exception
493          */
494         public static void main(String[] args) throws Exception {
495                 RestWebServiceClient client = RestWebServiceClient.getInstance();
496                 final String getUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/analytics";
497                 String get = client.get(getUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword", null);
498                 System.out.println("Get result:\n" + get);
499                 final String postUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/storeAnalytics";
500                 final String content = " { " + " \"action\"  : \"test1\", " + " \"page\"     : \"test2\", "
501                                 + " \"function\" : \"test3\", " + " \"userid\"   : \"ab1234\" " + "}";
502                 String post = client.post(postUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword",
503                                 "application/json", content, true);
504                 System.out.println("Post result:\n" + post);
505         }
506 }