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);
366 con.getOutputStream().write(content.getBytes());
368 con.getOutputStream().flush();
369 con.getOutputStream().close();
371 int responseCode = con.getResponseCode();
372 logger.debug("Response Code : " + responseCode);
374 StringBuffer sb = new StringBuffer();
375 InputStreamReader in = null;
376 char[] buf = new char[8196];
379 in = new InputStreamReader(con.getInputStream(), "UTF-8");
380 while ((bytes = in.read(buf)) > 0)
381 sb.append(new String(buf, 0, bytes));
386 } catch (IOException ex) {
387 logger.warn("get: failed to close reader", ex);
391 return sb.toString();
395 public String deletePortalContent(String restPath, String userId, String appName, String requestId,
396 String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth ,String filter) throws Exception {
397 String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
399 if (restURL == null) {
400 // should never happen
401 String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
404 throw new Exception(msg);
406 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
408 if (appUebKey == null) {
409 // should never happen
410 String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
413 throw new Exception(msg);
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,filter);
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 ,String filter) throws Exception {
424 if (logger.isDebugEnabled())
425 logger.debug("RestWebServiceClient.post to URL " + url);
426 if (appName == null || appName.trim().length() == 0)
428 if (requestId == null || requestId.trim().length() == 0)
429 requestId = UUID.randomUUID().toString();
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)));
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)));
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 con.setRequestProperty("filter", filter);
456 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
457 con.setRequestProperty("Authorization", "Basic "+ encoding);
460 con.setDoInput(true);
461 con.setDoOutput(true);
464 con.getOutputStream().write(content.getBytes());
466 con.getOutputStream().flush();
467 con.getOutputStream().close();
469 int responseCode = con.getResponseCode();
470 logger.debug("Response Code : " + responseCode);
472 StringBuffer sb = new StringBuffer();
473 InputStreamReader in = null;
474 char[] buf = new char[8196];
477 in = new InputStreamReader(con.getInputStream(), "UTF-8");
478 while ((bytes = in.read(buf)) > 0)
479 sb.append(new String(buf, 0, bytes));
484 } catch (IOException ex) {
485 logger.warn("get: failed to close reader", ex);
489 return sb.toString();
494 * Basic unit test for the client to call Portal app on localhost.
500 public static void main(String[] args) throws Exception {
501 RestWebServiceClient client = RestWebServiceClient.getInstance();
502 final String getUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/analytics";
503 String get = client.get(getUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword", null);
504 System.out.println("Get result:\n" + get);
505 final String postUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/storeAnalytics";
506 final String content = " { " + " \"action\" : \"test1\", " + " \"page\" : \"test2\", "
507 + " \"function\" : \"test3\", " + " \"userid\" : \"ab1234\" " + "}";
508 String post = client.post(postUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword",
509 "application/json", content, true);
510 System.out.println("Post result:\n" + post);