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.UUID;
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;
35 * Simple REST client for GET-ing content from and POST-ing content to the
38 public class RestWebServiceClient {
40 private final Log logger = LogFactory.getLog(RestWebServiceClient.class);
45 private static RestWebServiceClient instance = null;
48 * Constructor is private. Clients should obtain an instance via
51 private RestWebServiceClient() {
55 * Gets the static instance of RestWebServiceClient; creates it if
56 * necessary. Synchronized to be thread safe.
58 * @return Static instance of RestWebServiceClient.
60 public static synchronized RestWebServiceClient getInstance() {
62 instance = new RestWebServiceClient();
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.
73 * Partial path of the endpoint; e.g., "/specialRestService"
75 * userId for the user originating the request
77 * Application Name for logging.
79 * 128-bit UUID value to uniquely identify the transaction.
81 * REST API user name for Portal to authenticate the request
83 * REST API password (in the clear, not encrypted) for Portal to
84 * authenticate the request
85 * @return Content from REST endpoint
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;
96 throw new Exception(msg);
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;
103 throw new Exception(msg);
105 final String restEndpointUrl = restURL + restPath;
106 return get(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword);
111 * Makes a call to a Portal REST API using the specified URL and parameters.
114 * Complete URL of the REST endpoint.
116 * User that it should be fetching the data
118 * Application name for logging; if null or empty, defaulted to
121 * 128-bit UUID value to uniquely identify the transaction; if
122 * null or empty, one is generated.
124 * Unique key for the application, used by Portal to authenticate
127 * REST API user name, used by Portal to authenticate the request
129 * REST API password, used by Portal to authenticate the request
130 * @return Content from REST endpoint
132 * On any failure; e.g., unknown host.
134 public String get(String url, String loginId, String appName, String requestId, String appUebKey,
135 String appUserName, String appPassword) throws Exception {
137 logger.debug("RestWebServiceClient.get (" + url + ") operation is started.");
139 if (appName == null || appName.trim().length() == 0)
141 if (requestId == null || requestId.trim().length() == 0)
142 requestId = UUID.randomUUID().toString();
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);
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);
159 int responseCode = con.getResponseCode();
160 logger.debug("get: received response code '" + responseCode + "' while getting the '" + url + "' for user: "
163 StringBuffer sb = new StringBuffer();
164 BufferedReader in = null;
166 in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
167 String inputLine = null;
168 while ((inputLine = in.readLine()) != null)
169 sb.append(inputLine);
174 } catch (IOException ex) {
175 logger.error("get: failed to close reader", ex);
179 final String response = sb.toString();
180 if (logger.isDebugEnabled())
181 logger.debug("get: url " + url + " yielded " + response);
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.
192 * Partial path of the endpoint; e.g., "/specialRestService"
194 * ID for the user originating the request
196 * Application Name for logging.
198 * 128-bit UUID value to uniquely identify the transaction.
200 * REST API user name for Portal to authenticate the request;
203 * REST API password (in the clear, not encrypted) for Portal to
204 * authenticate the request; ignored if null
206 * content type for header
209 * @return Content from REST endpoint
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;
220 throw new Exception(msg);
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;
227 throw new Exception(msg);
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,
236 * Makes a POST call to a Portal REST API using the specified URL and
240 * Complete URL of the REST endpoint.
242 * User who is fetching the data
244 * Application name for logging; if null or empty, defaulted to
247 * 128-bit UUID value to uniquely identify the transaction; if
248 * null or empty, one is generated.
250 * Unique key for the application, used by Portal to authenticate
253 * REST API user name used by Portal to authenticate the request;
256 * REST API password used by Portal to authenticate the request;
262 * @return Any content read from the endpoint
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 {
269 if (logger.isDebugEnabled())
270 logger.debug("RestWebServiceClient.post to URL " + url);
271 if (appName == null || appName.trim().length() == 0)
273 if (requestId == null || requestId.trim().length() == 0)
274 requestId = UUID.randomUUID().toString();
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);
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);
294 con.setDoInput(true);
295 con.setDoOutput(true);
296 con.getOutputStream().write(content.getBytes());
297 con.getOutputStream().flush();
298 con.getOutputStream().close();
300 int responseCode = con.getResponseCode();
301 logger.debug("Response Code : " + responseCode);
303 StringBuffer sb = new StringBuffer();
304 InputStreamReader in = null;
305 char[] buf = new char[8196];
308 in = new InputStreamReader(con.getInputStream(), "UTF-8");
309 while ((bytes = in.read(buf)) > 0)
310 sb.append(new String(buf, 0, bytes));
315 } catch (IOException ex) {
316 logger.warn("get: failed to close reader", ex);
320 return sb.toString();
324 * Basic unit test for the client to call Portal app on localhost.
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);