2 * ================================================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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 * ================================================================================
20 package org.openecomp.portalsdk.core.onboarding.rest;
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.InputStreamReader;
25 import java.net.HttpURLConnection;
27 import java.util.Base64;
28 import java.util.UUID;
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;
36 * Simple REST client for GET-ing content from and POST-ing content , Delete to the
39 public class RestWebServiceClient {
41 private final Log logger = LogFactory.getLog(RestWebServiceClient.class);
46 private static RestWebServiceClient instance = null;
49 * Constructor is private. Clients should obtain an instance via
52 private RestWebServiceClient() {
56 * Gets the static instance of RestWebServiceClient; creates it if
57 * necessary. Synchronized to be thread safe.
59 * @return Static instance of RestWebServiceClient.
61 public static synchronized RestWebServiceClient getInstance() {
63 instance = new RestWebServiceClient();
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.
74 * Partial path of the endpoint; e.g., "/specialRestService"
76 * userId for the user originating the request
78 * Application Name for logging.
80 * 128-bit UUID value to uniquely identify the transaction.
82 * REST API user name for Portal to authenticate the request
84 * REST API password (in the clear, not encrypted) for Portal to
85 * authenticate the request
86 * @return Content from REST endpoint
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);
93 if (restURL == null) {
94 // should never happen
95 String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
97 throw new Exception(msg);
99 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
101 if (appUebKey == null) {
102 // should never happen
103 String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
106 throw new Exception(msg);
108 final String restEndpointUrl = restURL + restPath;
111 return get(restEndpointUrl, userId,appName, requestId, appUebKey, appUserName, appPassword,isBasicAuth);
113 return get(restEndpointUrl, userId,appName, requestId, appUebKey, appUserName, appPassword);
118 * Makes a call to a Portal REST API using the specified URL and parameters.
121 * Complete URL of the REST endpoint.
123 * User that it should be fetching the data
125 * Application name for logging; if null or empty, defaulted to
128 * 128-bit UUID value to uniquely identify the transaction; if
129 * null or empty, one is generated.
131 * Unique key for the application, used by Portal to authenticate
134 * REST API user name, used by Portal to authenticate the request
136 * REST API password, used by Portal to authenticate the request
137 * @return Content from REST endpoint
139 * On any failure; e.g., unknown host.
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);
149 * Makes a call to a Portal REST API using the specified URL and parameters.
152 * Complete URL of the REST endpoint.
154 * User that it should be fetching the data
156 * Application name for logging; if null or empty, defaulted to
159 * 128-bit UUID value to uniquely identify the transaction; if
160 * null or empty, one is generated.
162 * Unique key for the application, used by Portal to authenticate
165 * REST API user name, used by Portal to authenticate the request
167 * REST API password, used by Portal to authenticate the request
168 * @return Content from REST endpoint
170 * On any failure; e.g., unknown host.
172 public String get(String url, String loginId, String appName, String requestId, String appUebKey,
173 String appUserName, String appPassword, Boolean useBasicAuth) throws Exception {
175 logger.debug("RestWebServiceClient.get (" + url + ") operation is started.");
177 if (appName == null || appName.trim().length() == 0)
179 if (requestId == null || requestId.trim().length() == 0)
180 requestId = UUID.randomUUID().toString();
182 URL obj = new URL(url);
183 // Create the connection object
184 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
185 con.setRequestMethod("GET");
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)));
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)));
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);
206 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
207 con.setRequestProperty("Authorization", "Basic "+ encoding);
210 int responseCode = con.getResponseCode();
211 logger.debug("get: received response code '" + responseCode + "' while getting the '" + url + "' for user: "
214 StringBuffer sb = new StringBuffer();
215 BufferedReader in = null;
217 in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
218 String inputLine = null;
219 while ((inputLine = in.readLine()) != null)
220 sb.append(inputLine);
225 } catch (IOException ex) {
226 logger.error("get: failed to close reader", ex);
230 final String response = sb.toString();
231 if (logger.isDebugEnabled())
232 logger.debug("get: url " + url + " yielded " + response);
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.
243 * Partial path of the endpoint; e.g., "/specialRestService"
245 * ID for the user originating the request
247 * Application Name for logging.
249 * 128-bit UUID value to uniquely identify the transaction.
251 * REST API user name for Portal to authenticate the request;
254 * REST API password (in the clear, not encrypted) for Portal to
255 * authenticate the request; ignored if null
257 * content type for header
260 * @return Content from REST endpoint
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);
269 if (restURL == null) {
270 // should never happen
271 String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
274 throw new Exception(msg);
276 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
278 if (appUebKey == null) {
279 // should never happen
280 String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
283 throw new Exception(msg);
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);
292 * Makes a POST call to a Portal REST API using the specified URL and
296 * Complete URL of the REST endpoint.
298 * User who is fetching the data
300 * Application name for logging; if null or empty, defaulted to
303 * 128-bit UUID value to uniquely identify the transaction; if
304 * null or empty, one is generated.
306 * Unique key for the application, used by Portal to authenticate
309 * REST API user name used by Portal to authenticate the request;
312 * REST API password used by Portal to authenticate the request;
318 * @return Any content read from the endpoint
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 {
325 if (logger.isDebugEnabled())
326 logger.debug("RestWebServiceClient.post to URL " + url);
327 if (appName == null || appName.trim().length() == 0)
329 if (requestId == null || requestId.trim().length() == 0)
330 requestId = UUID.randomUUID().toString();
332 URL obj = new URL(url);
333 // Create the connection object
334 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
335 con.setRequestMethod("POST");
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)));
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)));
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);
358 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
359 con.setRequestProperty("Authorization", "Basic "+ encoding);
362 con.setDoInput(true);
363 con.setDoOutput(true);
364 con.getOutputStream().write(content.getBytes());
365 con.getOutputStream().flush();
366 con.getOutputStream().close();
368 int responseCode = con.getResponseCode();
369 logger.debug("Response Code : " + responseCode);
371 StringBuffer sb = new StringBuffer();
372 InputStreamReader in = null;
373 char[] buf = new char[8196];
376 in = new InputStreamReader(con.getInputStream(), "UTF-8");
377 while ((bytes = in.read(buf)) > 0)
378 sb.append(new String(buf, 0, bytes));
383 } catch (IOException ex) {
384 logger.warn("get: failed to close reader", ex);
388 return sb.toString();
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);
396 if (restURL == null) {
397 // should never happen
398 String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
401 throw new Exception(msg);
403 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
405 if (appUebKey == null) {
406 // should never happen
407 String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
410 throw new Exception(msg);
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);
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 {
421 if (logger.isDebugEnabled())
422 logger.debug("RestWebServiceClient.post to URL " + url);
423 if (appName == null || appName.trim().length() == 0)
425 if (requestId == null || requestId.trim().length() == 0)
426 requestId = UUID.randomUUID().toString();
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)));
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)));
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);
453 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
454 con.setRequestProperty("Authorization", "Basic "+ encoding);
457 con.setDoInput(true);
458 con.setDoOutput(true);
459 con.getOutputStream().write(content.getBytes());
460 con.getOutputStream().flush();
461 con.getOutputStream().close();
463 int responseCode = con.getResponseCode();
464 logger.debug("Response Code : " + responseCode);
466 StringBuffer sb = new StringBuffer();
467 InputStreamReader in = null;
468 char[] buf = new char[8196];
471 in = new InputStreamReader(con.getInputStream(), "UTF-8");
472 while ((bytes = in.read(buf)) > 0)
473 sb.append(new String(buf, 0, bytes));
478 } catch (IOException ex) {
479 logger.warn("get: failed to close reader", ex);
483 return sb.toString();
488 * Basic unit test for the client to call Portal app on localhost.
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);