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");
186 con.setConnectTimeout(3000);
187 con.setReadTimeout(8000);
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);
198 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
199 con.setRequestProperty("Authorization", "Basic "+ encoding);
202 int responseCode = con.getResponseCode();
203 logger.debug("get: received response code '" + responseCode + "' while getting the '" + url + "' for user: "
206 StringBuffer sb = new StringBuffer();
207 BufferedReader in = null;
209 in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
210 String inputLine = null;
211 while ((inputLine = in.readLine()) != null)
212 sb.append(inputLine);
217 } catch (IOException ex) {
218 logger.error("get: failed to close reader", ex);
222 final String response = sb.toString();
223 if (logger.isDebugEnabled())
224 logger.debug("get: url " + url + " yielded " + response);
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.
235 * Partial path of the endpoint; e.g., "/specialRestService"
237 * ID for the user originating the request
239 * Application Name for logging.
241 * 128-bit UUID value to uniquely identify the transaction.
243 * REST API user name for Portal to authenticate the request;
246 * REST API password (in the clear, not encrypted) for Portal to
247 * authenticate the request; ignored if null
249 * content type for header
252 * @return Content from REST endpoint
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);
261 if (restURL == null) {
262 // should never happen
263 String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
266 throw new Exception(msg);
268 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
270 if (appUebKey == null) {
271 // should never happen
272 String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
275 throw new Exception(msg);
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);
284 * Makes a POST call to a Portal REST API using the specified URL and
288 * Complete URL of the REST endpoint.
290 * User who is fetching the data
292 * Application name for logging; if null or empty, defaulted to
295 * 128-bit UUID value to uniquely identify the transaction; if
296 * null or empty, one is generated.
298 * Unique key for the application, used by Portal to authenticate
301 * REST API user name used by Portal to authenticate the request;
304 * REST API password used by Portal to authenticate the request;
310 * @return Any content read from the endpoint
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 {
317 if (logger.isDebugEnabled())
318 logger.debug("RestWebServiceClient.post to URL " + url);
319 if (appName == null || appName.trim().length() == 0)
321 if (requestId == null || requestId.trim().length() == 0)
322 requestId = UUID.randomUUID().toString();
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);
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);
342 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
343 con.setRequestProperty("Authorization", "Basic "+ encoding);
346 con.setDoInput(true);
347 con.setDoOutput(true);
348 con.getOutputStream().write(content.getBytes());
349 con.getOutputStream().flush();
350 con.getOutputStream().close();
352 int responseCode = con.getResponseCode();
353 logger.debug("Response Code : " + responseCode);
355 StringBuffer sb = new StringBuffer();
356 InputStreamReader in = null;
357 char[] buf = new char[8196];
360 in = new InputStreamReader(con.getInputStream(), "UTF-8");
361 while ((bytes = in.read(buf)) > 0)
362 sb.append(new String(buf, 0, bytes));
367 } catch (IOException ex) {
368 logger.warn("get: failed to close reader", ex);
372 return sb.toString();
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);
380 if (restURL == null) {
381 // should never happen
382 String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
385 throw new Exception(msg);
387 String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
389 if (appUebKey == null) {
390 // should never happen
391 String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
394 throw new Exception(msg);
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);
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 {
405 if (logger.isDebugEnabled())
406 logger.debug("RestWebServiceClient.post to URL " + url);
407 if (appName == null || appName.trim().length() == 0)
409 if (requestId == null || requestId.trim().length() == 0)
410 requestId = UUID.randomUUID().toString();
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);
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);
431 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
432 con.setRequestProperty("Authorization", "Basic "+ encoding);
435 con.setDoInput(true);
436 con.setDoOutput(true);
437 con.getOutputStream().write(content.getBytes());
438 con.getOutputStream().flush();
439 con.getOutputStream().close();
441 int responseCode = con.getResponseCode();
442 logger.debug("Response Code : " + responseCode);
444 StringBuffer sb = new StringBuffer();
445 InputStreamReader in = null;
446 char[] buf = new char[8196];
449 in = new InputStreamReader(con.getInputStream(), "UTF-8");
450 while ((bytes = in.read(buf)) > 0)
451 sb.append(new String(buf, 0, bytes));
456 } catch (IOException ex) {
457 logger.warn("get: failed to close reader", ex);
461 return sb.toString();
466 * Basic unit test for the client to call Portal app on localhost.
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);