2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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 * ============LICENSE_END=========================================================
20 package org.onap.vid.aai.util;
23 import com.att.eelf.configuration.EELFLogger;
24 import org.apache.commons.lang3.exception.ExceptionUtils;
25 import org.eclipse.jetty.util.security.Password;
26 import org.onap.vid.aai.ExceptionWithRequestInfo;
27 import org.onap.vid.aai.ResponseWithRequestInfo;
28 import org.onap.vid.utils.Logging;
29 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
30 import org.onap.portalsdk.core.util.SystemProperties;
31 import org.springframework.beans.factory.annotation.Autowired;
32 import org.springframework.http.HttpMethod;
34 import javax.ws.rs.client.Client;
35 import javax.ws.rs.client.Entity;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
38 import java.io.UnsupportedEncodingException;
39 import java.net.URLEncoder;
40 import java.text.DateFormat;
41 import java.text.SimpleDateFormat;
42 import java.util.Base64;
43 import java.util.Date;
44 import java.util.UUID;
46 import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
47 import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY;
51 * The Class AAIRestInterface.
53 public class AAIRestInterface {
55 public static final String WITH_STATUS = " with status=";
57 protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class);
59 protected final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai");
61 /** The Constant dateFormat. */
62 protected final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
65 private Client client = null;
67 /** The rest srvr base URL. */
68 private String restSrvrBaseURL;
71 protected HttpsAuthClient httpsAuthClientFactory;
73 private String START_STRING = " start";
74 protected String TRANSACTION_ID_HEADER = "X-TransactionId";
75 protected String FROM_APP_ID_HEADER = "X-FromAppId";
76 private String SUCCESSFUL_API_MESSAGE=" REST api POST was successful!";
77 protected String URL_DECLARATION = ", url=";
79 public AAIRestInterface(HttpsAuthClient httpsAuthClientFactory) {
80 this.httpsAuthClientFactory = httpsAuthClientFactory;
86 * @param nodeKey the node key
88 * @throws UnsupportedEncodingException the unsupported encoding exception
90 public String encodeURL (String nodeKey) throws UnsupportedEncodingException {
91 return URLEncoder.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20");
94 private void initRestClient() {
95 initRestClient(false);
99 private void initRestClient(boolean propagateExceptions)
101 if (client == null) {
103 client = httpsAuthClientFactory.getClient(HttpClientMode.WITHOUT_KEYSTORE);
104 } catch (Exception e) {
105 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== Exception in REST call to DB in initRestClient" + e.toString());
106 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== Exception in REST call to DB : " + e.toString());
107 if (propagateExceptions) {
108 ExceptionUtils.rethrow(e);
117 * Sets the rest srvr base URL.
119 * @param baseURL the base URL
121 public void SetRestSrvrBaseURL(String baseURL)
125 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== REST Server base URL cannot be null.");
126 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== REST Server base URL cannot be null.");
129 restSrvrBaseURL = baseURL;
133 * Gets the rest srvr base URL.
135 * @return the rest srvr base URL
137 public String getRestSrvrBaseURL()
139 return restSrvrBaseURL;
146 * @param fromAppId the from app id
147 * @param transId the trans id
148 * @param requestUri the request uri
153 public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml) {
154 return RestGet(fromAppId, transId, requestUri, xml, false);
157 public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml, boolean propagateExceptions) {
160 String methodName = "RestGet";
161 url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + requestUri;
163 String responseType = MediaType.APPLICATION_JSON;
165 responseType = MediaType.APPLICATION_XML;
167 initRestClient(propagateExceptions);
169 String clientCert = SystemProperties.getProperty(AAIProperties.AAI_USE_CLIENT_CERT);
171 boolean useClientCert = false;
172 if (clientCert != null &&
173 SystemProperties.getProperty(AAIProperties.AAI_USE_CLIENT_CERT).equalsIgnoreCase("true")) {
174 useClientCert = true;
177 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING);
178 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + url + " for the get REST API");
180 Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
183 if (useClientCert == true) {
184 cres = client.target(url)
186 .accept(responseType)
187 .header(TRANSACTION_ID_HEADER, transId)
188 .header(FROM_APP_ID_HEADER, fromAppId)
189 .header("Content-Type", MediaType.APPLICATION_JSON)
190 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
194 String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME);
195 String vidPassword = Password.deobfuscate(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X));
196 String encodeThis = vidUsername + ":" + vidPassword;
198 cres = client.target(url)
200 .accept(responseType)
201 .header(TRANSACTION_ID_HEADER, transId)
202 .header(FROM_APP_ID_HEADER, fromAppId)
203 .header("Content-Type", "application/json")
204 .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8")))
205 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
208 Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres);
210 if (cres.getStatus() == 200) {
211 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE);
212 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE);
214 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS + cres.getStatus() + URL_DECLARATION + url);
216 return new ResponseWithRequestInfo(cres, url, HttpMethod.GET);
217 } catch (Exception e) {
218 // no need to ask if "propagateExceptions" because any exception
219 // at this point should have already obey to the
220 // "propagateExceptions" flag
221 throw new ExceptionWithRequestInfo(HttpMethod.GET, defaultIfNull(url, requestUri), e);
225 protected String extractOrGenerateRequestId() {
226 return Logging.extractOrGenerateRequestId();
233 * @param sourceID the source ID
234 * @param transId the trans id
235 * @param path the path
236 * @return true, if successful
238 public boolean Delete(String sourceID, String transId, String path) {
239 String methodName = "Delete";
241 transId += ":" + UUID.randomUUID().toString();
242 logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START_STRING);
245 url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + path;
246 Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url);
247 final Response cres = client.target(url)
249 .accept(MediaType.APPLICATION_JSON)
250 .header(TRANSACTION_ID_HEADER, transId)
251 .header(FROM_APP_ID_HEADER, sourceID)
252 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
254 Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres);
255 if (cres.getStatus() == 404) { // resource not found
256 String msg = "Resource does not exist...: " + cres.getStatus()
257 + ":" + cres.readEntity(String.class);
258 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + msg);
260 } else if (cres.getStatus() == 200 || cres.getStatus() == 204){
261 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Resource " + url + " deleted");
264 String msg = "Deleting Resource failed: " + cres.getStatus()
265 + ":" + cres.readEntity(String.class);
266 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + msg);
276 * @param fromAppId the from app id
277 * @param path the path
278 * @param payload the payload
282 public Response RestPut(String fromAppId, String path, String payload, boolean xml) {
283 String methodName = "RestPut";
285 String transId = UUID.randomUUID().toString();
286 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING);
290 String responseType = MediaType.APPLICATION_JSON;
292 responseType = "application/xml";
296 url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + path;
297 String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME);
298 String vidPassword = Password.deobfuscate(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X));
299 String encodeThis = vidUsername + ":" + vidPassword;
301 Logging.logRequest(outgoingRequestsLogger, HttpMethod.PUT, url, payload);
302 final Response cres = client.target(url)
304 .accept(responseType)
305 .header(TRANSACTION_ID_HEADER, transId)
306 .header(FROM_APP_ID_HEADER, fromAppId)
307 .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8")))
308 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
309 .put(Entity.entity(payload, MediaType.APPLICATION_JSON));
310 Logging.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, cres);
312 if (cres.getStatus() == 200 && cres.getStatus() <= 299) {
313 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION);
314 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION);
316 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +cres.getStatus()+ URL_DECLARATION +url);
319 } catch (Exception e) {
320 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION +url+ ", Exception: " + e.toString());
330 * @param fromAppId the from app id
331 * @param path the path
332 * @param payload the payload
336 public Response RestPost(String fromAppId, String path, String payload, boolean xml) {
337 String methodName = "RestPost";
339 String transId = UUID.randomUUID().toString();
340 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING);
344 String responseType = MediaType.APPLICATION_JSON;
346 responseType = "application/xml";
350 url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL_BASE) + path;
351 String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME);
352 String vidPassword = Password.deobfuscate(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X));
353 String encodeThis = vidUsername + ":" + vidPassword;
355 Logging.logRequest(outgoingRequestsLogger, HttpMethod.POST, url, payload);
356 final Response cres = client.target(url)
358 .accept(responseType)
359 .header(TRANSACTION_ID_HEADER, transId)
360 .header(FROM_APP_ID_HEADER, fromAppId)
361 .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8")))
362 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
363 .post(Entity.entity(payload, MediaType.APPLICATION_JSON));
364 Logging.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, cres);
366 if (cres.getStatus() == 200 && cres.getStatus() <= 299) {
367 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION);
368 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION);
370 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +cres.getStatus()+ URL_DECLARATION +url);
373 } catch (Exception e) {
374 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION +url+ ", Exception: " + e.toString());