1d4feb07dcfe3da361765ed09773b69316c3f990
[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                 con.setConnectTimeout(3000);
187                 con.setReadTimeout(8000);
188
189                 // add request header
190                 con.setRequestProperty("uebkey", appUebKey);
191                 con.setRequestProperty("LoginId", loginId);
192                 con.setRequestProperty("user-agent", appName);
193                 con.setRequestProperty("X-ECOMP-RequestID", requestId);
194                 con.setRequestProperty("username", appUserName);
195                 con.setRequestProperty("password", appPassword);
196                         
197                         if(useBasicAuth){
198                         String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
199                         con.setRequestProperty("Authorization", "Basic "+ encoding);
200                         }
201                 
202                 int responseCode = con.getResponseCode();
203                 logger.debug("get: received response code '" + responseCode + "' while getting the '" + url + "' for user: "
204                                 + loginId);
205
206                 StringBuffer sb = new StringBuffer();
207                 BufferedReader in = null;
208                 try {
209                         in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
210                         String inputLine = null;
211                         while ((inputLine = in.readLine()) != null)
212                                 sb.append(inputLine);
213                 } finally {
214                         try {
215                                 if (in != null)
216                                         in.close();
217                         } catch (IOException ex) {
218                                 logger.error("get: failed to close reader", ex);
219                         }
220                 }
221
222                 final String response = sb.toString();
223                 if (logger.isDebugEnabled())
224                         logger.debug("get: url " + url + " yielded " + response);
225                 return response;
226         }
227         
228         /**
229          * Convenience method that fetches the URL for the Portal REST API endpoint
230          * and the application UEB key, then calls
231          * {@link #post(String, String, String, String, String, String, String, String, String)}
232          * to access the Portal's REST endpoint.
233          * 
234          * @param restPath
235          *            Partial path of the endpoint; e.g., "/specialRestService"
236          * @param userId
237          *            ID for the user originating the request
238          * @param appName
239          *            Application Name for logging.
240          * @param requestId
241          *            128-bit UUID value to uniquely identify the transaction.
242          * @param appUserName
243          *            REST API user name for Portal to authenticate the request;
244          *            ignored if null
245          * @param appPassword
246          *            REST API password (in the clear, not encrypted) for Portal to
247          *            authenticate the request; ignored if null
248          * @param contentType
249          *            content type for header
250          * @param content
251          *            String to post
252          * @return Content from REST endpoint
253          * @throws Exception
254          *             on any failure
255          */
256         public String postPortalContent(String restPath, String userId, String appName, String requestId,
257                         String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) throws Exception {
258                 String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
259
260                 
261                 if (restURL == null) {
262                         // should never happen
263                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
264
265                         logger.error(msg);
266                         throw new Exception(msg);
267                 }
268                 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
269
270                 if (appUebKey == null) {
271                         // should never happen
272                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
273
274                         logger.error(msg);
275                         throw new Exception(msg);
276                 }
277                 final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/";
278                 final String restEndpointUrl = restURL + separator + restPath;
279                 return post(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType,
280                                 content,isBasicAuth);
281         }
282
283         /**
284          * Makes a POST call to a Portal REST API using the specified URL and
285          * parameters.
286          * 
287          * @param url
288          *            Complete URL of the REST endpoint.
289          * @param loginId
290          *            User who is fetching the data
291          * @param appName
292          *            Application name for logging; if null or empty, defaulted to
293          *            Unknown.
294          * @param requestId
295          *            128-bit UUID value to uniquely identify the transaction; if
296          *            null or empty, one is generated.
297          * @param appUebKey
298          *            Unique key for the application, used by Portal to authenticate
299          *            the request
300          * @param appUserName
301          *            REST API user name used by Portal to authenticate the request;
302          *            ignored if null
303          * @param appPassword
304          *            REST API password used by Portal to authenticate the request;
305          *            ignored if null
306          * @param contentType
307          *            MIME header
308          * @param content
309          *            Content to POST
310          * @return Any content read from the endpoint
311          * @throws Exception
312          *             On any error
313          */
314         public String post(String url, String loginId, String appName, String requestId, String appUebKey,
315                         String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) throws Exception {
316
317                 if (logger.isDebugEnabled())
318                         logger.debug("RestWebServiceClient.post to URL " + url);
319                 if (appName == null || appName.trim().length() == 0)
320                         appName = "Unknown";
321                 if (requestId == null || requestId.trim().length() == 0)
322                         requestId = UUID.randomUUID().toString();
323
324                 URL obj = new URL(url);
325                 // Create the connection object
326                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
327                 con.setRequestMethod("POST");
328                 con.setConnectTimeout(3000);
329                 con.setReadTimeout(15000);
330
331                 // add request header
332                 con.setRequestProperty("uebkey", appUebKey);
333                 if (appUserName != null)
334                         con.setRequestProperty("username", appUserName);
335                 if (appPassword != null)
336                         con.setRequestProperty("password", appPassword);
337                 con.setRequestProperty("LoginId", loginId);
338                 con.setRequestProperty("user-agent", appName);
339                 con.setRequestProperty("X-ECOMP-RequestID", requestId);
340                 con.setRequestProperty("Content-Type", contentType);
341                 if(isBasicAuth){
342                         String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
343                         con.setRequestProperty("Authorization", "Basic "+ encoding);
344                         }
345
346                 con.setDoInput(true);
347                 con.setDoOutput(true);
348                 con.getOutputStream().write(content.getBytes());
349                 con.getOutputStream().flush();
350                 con.getOutputStream().close();
351
352                 int responseCode = con.getResponseCode();
353                 logger.debug("Response Code : " + responseCode);
354
355                 StringBuffer sb = new StringBuffer();
356                 InputStreamReader in = null;
357                 char[] buf = new char[8196];
358                 int bytes;
359                 try {
360                         in = new InputStreamReader(con.getInputStream(), "UTF-8");
361                         while ((bytes = in.read(buf)) > 0)
362                                 sb.append(new String(buf, 0, bytes));
363                 } finally {
364                         try {
365                                 if (in != null)
366                                         in.close();
367                         } catch (IOException ex) {
368                                 logger.warn("get: failed to close reader", ex);
369                         }
370                 }
371
372                 return sb.toString();
373         }
374         
375         
376         public String deletePortalContent(String restPath, String userId, String appName, String requestId,
377                         String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth ,String filter) throws Exception {
378                 String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
379
380                 if (restURL == null) {
381                         // should never happen
382                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
383
384                         logger.error(msg);
385                         throw new Exception(msg);
386                 }
387                 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
388
389                 if (appUebKey == null) {
390                         // should never happen
391                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
392
393                         logger.error(msg);
394                         throw new Exception(msg);
395                 }
396                 final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/";
397                 final String restEndpointUrl = restURL + separator + restPath;
398                 return delete(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType,
399                                 content,isBasicAuth,filter);
400         }
401         
402         public String delete(String url, String loginId, String appName, String requestId, String appUebKey,
403                         String appUserName, String appPassword, String contentType, String content,boolean isBasicAuth ,String filter) throws Exception {
404
405                 if (logger.isDebugEnabled())
406                         logger.debug("RestWebServiceClient.post to URL " + url);
407                 if (appName == null || appName.trim().length() == 0)
408                         appName = "Unknown";
409                 if (requestId == null || requestId.trim().length() == 0)
410                         requestId = UUID.randomUUID().toString();
411
412                 URL obj = new URL(url);
413                 // Create the connection object
414                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
415                 con.setRequestMethod("DELETE");
416                 con.setConnectTimeout(3000);
417                 con.setReadTimeout(15000);
418
419                 // add request header
420                 con.setRequestProperty("uebkey", appUebKey);
421                 if (appUserName != null)
422                         con.setRequestProperty("username", appUserName);
423                 if (appPassword != null)
424                         con.setRequestProperty("password", appPassword);
425                 con.setRequestProperty("LoginId", loginId);
426                 con.setRequestProperty("user-agent", appName);
427                 con.setRequestProperty("X-ECOMP-RequestID", requestId);
428                 con.setRequestProperty("Content-Type", contentType);
429                 con.setRequestProperty("filter", filter);
430                 if(isBasicAuth){
431                         String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
432                         con.setRequestProperty("Authorization", "Basic "+ encoding);
433                         }
434
435                 con.setDoInput(true);
436                 con.setDoOutput(true);
437                 con.getOutputStream().write(content.getBytes());
438                 con.getOutputStream().flush();
439                 con.getOutputStream().close();
440
441                 int responseCode = con.getResponseCode();
442                 logger.debug("Response Code : " + responseCode);
443
444                 StringBuffer sb = new StringBuffer();
445                 InputStreamReader in = null;
446                 char[] buf = new char[8196];
447                 int bytes;
448                 try {
449                         in = new InputStreamReader(con.getInputStream(), "UTF-8");
450                         while ((bytes = in.read(buf)) > 0)
451                                 sb.append(new String(buf, 0, bytes));
452                 } finally {
453                         try {
454                                 if (in != null)
455                                         in.close();
456                         } catch (IOException ex) {
457                                 logger.warn("get: failed to close reader", ex);
458                         }
459                 }
460
461                 return sb.toString();
462         }
463         
464
465         /**
466          * Basic unit test for the client to call Portal app on localhost.
467          * 
468          * @param args
469          *            Ignored
470          * @throws Exception
471          */
472         public static void main(String[] args) throws Exception {
473                 RestWebServiceClient client = RestWebServiceClient.getInstance();
474                 final String getUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/analytics";
475                 String get = client.get(getUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword", null);
476                 System.out.println("Get result:\n" + get);
477                 final String postUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/storeAnalytics";
478                 final String content = " { " + " \"action\"  : \"test1\", " + " \"page\"     : \"test2\", "
479                                 + " \"function\" : \"test3\", " + " \"userid\"   : \"ab1234\" " + "}";
480                 String post = client.post(postUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword",
481                                 "application/json", content, true);
482                 System.out.println("Post result:\n" + post);
483         }
484 }