f01590d49a8f1c2c9283a395b58c7cd254cdda1d
[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.UUID;
28
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogFactory;
31 import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
32 import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
33
34 /**
35  * Simple REST client for GET-ing content from and POST-ing content to the
36  * Portal application.
37  */
38 public class RestWebServiceClient {
39
40         private final Log logger = LogFactory.getLog(RestWebServiceClient.class);
41
42         /**
43          * Singleton instance
44          */
45         private static RestWebServiceClient instance = null;
46
47         /**
48          * Constructor is private. Clients should obtain an instance via
49          * getInstance().
50          */
51         private RestWebServiceClient() {
52         }
53
54         /**
55          * Gets the static instance of RestWebServiceClient; creates it if
56          * necessary. Synchronized to be thread safe.
57          * 
58          * @return Static instance of RestWebServiceClient.
59          */
60         public static synchronized RestWebServiceClient getInstance() {
61                 if (instance == null)
62                         instance = new RestWebServiceClient();
63                 return instance;
64         }
65
66         /**
67          * Convenience method that fetches the URL for the Portal REST API endpoint
68          * and the application UEB key, then calls
69          * {@link #get(String, String, String, String, String, String, String)} to
70          * access the Portal's REST endpoint.
71          * 
72          * @param restPath
73          *            Partial path of the endpoint; e.g., "/specialRestService"
74          * @param userId
75          *            userId for the user originating the request
76          * @param appName
77          *            Application Name for logging.
78          * @param requestId
79          *            128-bit UUID value to uniquely identify the transaction.
80          * @param appUserName
81          *            REST API user name for Portal to authenticate the request
82          * @param appPassword
83          *            REST API password (in the clear, not encrypted) for Portal to
84          *            authenticate the request
85          * @return Content from REST endpoint
86          * @throws Exception
87          *             on any failure
88          */
89         public String getPortalContent(String restPath, String userId, String appName, String requestId, String appUserName,
90                         String appPassword) throws Exception {
91                 String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
92                 if (restURL == null) {
93                         // should never happen
94                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
95                         logger.error(msg);
96                         throw new Exception(msg);
97                 }
98                 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
99                 if (appUebKey == null) {
100                         // should never happen
101                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
102                         logger.error(msg);
103                         throw new Exception(msg);
104                 }
105                 final String restEndpointUrl = restURL + restPath;
106                 return get(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword);
107
108         }
109
110         /**
111          * Makes a call to a Portal REST API using the specified URL and parameters.
112          * 
113          * @param url
114          *            Complete URL of the REST endpoint.
115          * @param loginId
116          *            User that it should be fetching the data
117          * @param appName
118          *            Application name for logging; if null or empty, defaulted to
119          *            Unknown.
120          * @param requestId
121          *            128-bit UUID value to uniquely identify the transaction; if
122          *            null or empty, one is generated.
123          * @param appUebKey
124          *            Unique key for the application, used by Portal to authenticate
125          *            the request
126          * @param appUserName
127          *            REST API user name, used by Portal to authenticate the request
128          * @param appPassword
129          *            REST API password, used by Portal to authenticate the request
130          * @return Content from REST endpoint
131          * @throws Exception
132          *             On any failure; e.g., unknown host.
133          */
134         public String get(String url, String loginId, String appName, String requestId, String appUebKey,
135                         String appUserName, String appPassword) throws Exception {
136
137                 logger.debug("RestWebServiceClient.get (" + url + ") operation is started.");
138
139                 if (appName == null || appName.trim().length() == 0)
140                         appName = "Unknown";
141                 if (requestId == null || requestId.trim().length() == 0)
142                         requestId = UUID.randomUUID().toString();
143
144                 URL obj = new URL(url);
145                 // Create the connection object
146                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
147                 con.setRequestMethod("GET");
148                 con.setConnectTimeout(3000);
149                 con.setReadTimeout(8000);
150
151                 // add request header
152                 con.setRequestProperty("uebkey", appUebKey);
153                 con.setRequestProperty("username", appUserName);
154                 con.setRequestProperty("password", appPassword);
155                 con.setRequestProperty("LoginId", loginId);
156                 con.setRequestProperty("user-agent", appName);
157                 con.setRequestProperty("X-ECOMP-RequestID", requestId);
158
159                 int responseCode = con.getResponseCode();
160                 logger.debug("get: received response code '" + responseCode + "' while getting the '" + url + "' for user: "
161                                 + loginId);
162
163                 StringBuffer sb = new StringBuffer();
164                 BufferedReader in = null;
165                 try {
166                         in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
167                         String inputLine = null;
168                         while ((inputLine = in.readLine()) != null)
169                                 sb.append(inputLine);
170                 } finally {
171                         try {
172                                 if (in != null)
173                                         in.close();
174                         } catch (IOException ex) {
175                                 logger.error("get: failed to close reader", ex);
176                         }
177                 }
178
179                 final String response = sb.toString();
180                 if (logger.isDebugEnabled())
181                         logger.debug("get: url " + url + " yielded " + response);
182                 return response;
183         }
184
185         /**
186          * Convenience method that fetches the URL for the Portal REST API endpoint
187          * and the application UEB key, then calls
188          * {@link #post(String, String, String, String, String, String, String, String, String)}
189          * to access the Portal's REST endpoint.
190          * 
191          * @param restPath
192          *            Partial path of the endpoint; e.g., "/specialRestService"
193          * @param userId
194          *            ID for the user originating the request
195          * @param appName
196          *            Application Name for logging.
197          * @param requestId
198          *            128-bit UUID value to uniquely identify the transaction.
199          * @param appUserName
200          *            REST API user name for Portal to authenticate the request;
201          *            ignored if null
202          * @param appPassword
203          *            REST API password (in the clear, not encrypted) for Portal to
204          *            authenticate the request; ignored if null
205          * @param contentType
206          *            content type for header
207          * @param content
208          *            String to post
209          * @return Content from REST endpoint
210          * @throws Exception
211          *             on any failure
212          */
213         public String postPortalContent(String restPath, String userId, String appName, String requestId,
214                         String appUserName, String appPassword, String contentType, String content) throws Exception {
215                 String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
216                 if (restURL == null) {
217                         // should never happen
218                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
219                         logger.error(msg);
220                         throw new Exception(msg);
221                 }
222                 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
223                 if (appUebKey == null) {
224                         // should never happen
225                         String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
226                         logger.error(msg);
227                         throw new Exception(msg);
228                 }
229                 final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/";
230                 final String restEndpointUrl = restURL + separator + restPath;
231                 return post(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType,
232                                 content);
233         }
234
235         /**
236          * Makes a POST call to a Portal REST API using the specified URL and
237          * parameters.
238          * 
239          * @param url
240          *            Complete URL of the REST endpoint.
241          * @param loginId
242          *            User who is fetching the data
243          * @param appName
244          *            Application name for logging; if null or empty, defaulted to
245          *            Unknown.
246          * @param requestId
247          *            128-bit UUID value to uniquely identify the transaction; if
248          *            null or empty, one is generated.
249          * @param appUebKey
250          *            Unique key for the application, used by Portal to authenticate
251          *            the request
252          * @param appUserName
253          *            REST API user name used by Portal to authenticate the request;
254          *            ignored if null
255          * @param appPassword
256          *            REST API password used by Portal to authenticate the request;
257          *            ignored if null
258          * @param contentType
259          *            MIME header
260          * @param content
261          *            Content to POST
262          * @return Any content read from the endpoint
263          * @throws Exception
264          *             On any error
265          */
266         public String post(String url, String loginId, String appName, String requestId, String appUebKey,
267                         String appUserName, String appPassword, String contentType, String content) throws Exception {
268
269                 if (logger.isDebugEnabled())
270                         logger.debug("RestWebServiceClient.post to URL " + url);
271                 if (appName == null || appName.trim().length() == 0)
272                         appName = "Unknown";
273                 if (requestId == null || requestId.trim().length() == 0)
274                         requestId = UUID.randomUUID().toString();
275
276                 URL obj = new URL(url);
277                 // Create the connection object
278                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
279                 con.setRequestMethod("POST");
280                 con.setConnectTimeout(3000);
281                 con.setReadTimeout(15000);
282
283                 // add request header
284                 con.setRequestProperty("uebkey", appUebKey);
285                 if (appUserName != null)
286                         con.setRequestProperty("username", appUserName);
287                 if (appPassword != null)
288                         con.setRequestProperty("password", appPassword);
289                 con.setRequestProperty("LoginId", loginId);
290                 con.setRequestProperty("user-agent", appName);
291                 con.setRequestProperty("X-ECOMP-RequestID", requestId);
292                 con.setRequestProperty("Content-Type", contentType);
293
294                 con.setDoInput(true);
295                 con.setDoOutput(true);
296                 con.getOutputStream().write(content.getBytes());
297                 con.getOutputStream().flush();
298                 con.getOutputStream().close();
299
300                 int responseCode = con.getResponseCode();
301                 logger.debug("Response Code : " + responseCode);
302
303                 StringBuffer sb = new StringBuffer();
304                 InputStreamReader in = null;
305                 char[] buf = new char[8196];
306                 int bytes;
307                 try {
308                         in = new InputStreamReader(con.getInputStream(), "UTF-8");
309                         while ((bytes = in.read(buf)) > 0)
310                                 sb.append(new String(buf, 0, bytes));
311                 } finally {
312                         try {
313                                 if (in != null)
314                                         in.close();
315                         } catch (IOException ex) {
316                                 logger.warn("get: failed to close reader", ex);
317                         }
318                 }
319
320                 return sb.toString();
321         }
322
323         /**
324          * Basic unit test for the client to call Portal app on localhost.
325          * 
326          * @param args
327          *            Ignored
328          * @throws Exception
329          */
330         public static void main(String[] args) throws Exception {
331                 RestWebServiceClient client = RestWebServiceClient.getInstance();
332                 final String getUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/analytics";
333                 String get = client.get(getUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword");
334                 System.out.println("Get result:\n" + get);
335                 final String postUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/storeAnalytics";
336                 final String content = " { " + " \"action\"  : \"test1\", " + " \"page\"     : \"test2\", "
337                                 + " \"function\" : \"test3\", " + " \"userid\"   : \"ab1234\" " + "}";
338                 String post = client.post(postUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword",
339                                 "application/json", content);
340                 System.out.println("Post result:\n" + post);
341         }
342 }