2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2018 Nokia. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
21 package org.onap.vid.aai.util;
24 import com.att.eelf.configuration.EELFLogger;
25 import org.apache.commons.lang3.exception.ExceptionUtils;
26 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
27 import org.onap.vid.aai.ExceptionWithRequestInfo;
28 import org.onap.vid.aai.ResponseWithRequestInfo;
29 import org.onap.vid.aai.exceptions.InvalidPropertyException;
30 import org.onap.vid.utils.Logging;
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.client.Invocation;
37 import javax.ws.rs.core.MediaType;
38 import javax.ws.rs.core.Response;
39 import java.io.UnsupportedEncodingException;
40 import java.net.URLEncoder;
41 import java.util.Optional;
42 import java.util.UUID;
44 import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
45 import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY;
49 * The Class AAIRestInterface.
51 public class AAIRestInterface {
54 protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class);
56 protected final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai");
60 private Client client = null;
62 /** The rest srvr base URL. */
63 private String restSrvrBaseURL;
66 protected HttpsAuthClient httpsAuthClientFactory;
67 private final ServletRequestHelper servletRequestHelper;
68 private final SystemPropertyHelper systemPropertyHelper;
70 protected static final String START_STRING = " start";
71 protected static final String TRANSACTION_ID_HEADER = "X-TransactionId";
72 protected static final String FROM_APP_ID_HEADER = "X-FromAppId";
73 protected static final String SUCCESSFUL_API_MESSAGE = " REST api call was successful!";
74 protected static final String URL_DECLARATION = ", url=";
76 public AAIRestInterface(HttpsAuthClient httpsAuthClientFactory, ServletRequestHelper servletRequestHelper, SystemPropertyHelper systemPropertyHelper) {
77 this.httpsAuthClientFactory = httpsAuthClientFactory;
78 this.servletRequestHelper = servletRequestHelper;
79 this.systemPropertyHelper = systemPropertyHelper;
86 AAIRestInterface(Optional<Client> client,
87 HttpsAuthClient httpsAuthClientFactory, ServletRequestHelper servletRequestHelper, SystemPropertyHelper systemPropertyHelper){
88 this.httpsAuthClientFactory = httpsAuthClientFactory;
89 this.servletRequestHelper = servletRequestHelper;
90 this.systemPropertyHelper = systemPropertyHelper;
91 if (client != null && client.isPresent()){
92 this.client = client.get();
100 * @param nodeKey the node key
102 * @throws UnsupportedEncodingException the unsupported encoding exception
104 public String encodeURL (String nodeKey) throws UnsupportedEncodingException {
105 return URLEncoder.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20");
108 private void initRestClient() {
109 initRestClient(false);
113 private void initRestClient(boolean propagateExceptions) {
114 if (client == null) {
116 client = httpsAuthClientFactory.getClient(HttpClientMode.WITH_KEYSTORE);
117 } catch (Exception e) {
118 logger.info(EELFLoggerDelegate.errorLogger, "Exception in REST call to DB in initRestClient" + e.toString());
119 logger.debug(EELFLoggerDelegate.debugLogger, "Exception in REST call to DB : " + e.toString());
120 if (propagateExceptions) {
121 ExceptionUtils.rethrow(e);
130 * Sets the rest srvr base URL.
132 * @param baseURL the base URL
134 public void SetRestSrvrBaseURL(String baseURL)
136 if (baseURL == null) {
137 logger.info(EELFLoggerDelegate.errorLogger, "REST Server base URL cannot be null.");
138 logger.debug(EELFLoggerDelegate.debugLogger, "REST Server base URL cannot be null.");
141 restSrvrBaseURL = baseURL;
145 * Gets the rest srvr base URL.
147 * @return the rest srvr base URL
149 public String getRestSrvrBaseURL() {
150 return restSrvrBaseURL;
157 * @param fromAppId the from app id
158 * @param transId the trans id
159 * @param requestUri the request uri
163 public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml) {
164 return RestGet(fromAppId, transId, requestUri, xml, false);
167 public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml, boolean propagateExceptions) {
168 String methodName = "RestGet";
169 String url = systemPropertyHelper.getFullServicePath(requestUri);
171 initRestClient(propagateExceptions);
173 logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING);
174 logger.debug(EELFLoggerDelegate.debugLogger, url + " for the get REST API");
176 Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
178 final Response response;
179 Invocation.Builder requestBuilder = client.target(url)
181 .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON)
182 .header(TRANSACTION_ID_HEADER, transId)
183 .header(FROM_APP_ID_HEADER, fromAppId)
184 .header("Content-Type", MediaType.APPLICATION_JSON)
185 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId());
186 response = systemPropertyHelper.isClientCertEnabled() ?
187 requestBuilder.get() : authenticateRequest(requestBuilder).get();
188 Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response);
190 if (response.getStatusInfo().equals(Response.Status.OK)) {
191 logger.debug(EELFLoggerDelegate.debugLogger, methodName + SUCCESSFUL_API_MESSAGE);
192 logger.info(EELFLoggerDelegate.errorLogger, methodName + SUCCESSFUL_API_MESSAGE);
194 logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response));
196 return new ResponseWithRequestInfo(response, url, HttpMethod.GET);
197 } catch (Exception e) {
198 logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
199 if (propagateExceptions) {
200 throw new ExceptionWithRequestInfo(HttpMethod.GET, defaultIfNull(url, requestUri), e);
202 return new ResponseWithRequestInfo(null, url, HttpMethod.GET);
207 protected String extractOrGenerateRequestId() {
208 return servletRequestHelper.extractOrGenerateRequestId();
215 * @param sourceID the source ID
216 * @param transId the trans id
217 * @param path the path
218 * @return true, if successful
220 public boolean Delete(String sourceID, String transId, String path) {
221 String methodName = "Delete";
222 transId += ":" + UUID.randomUUID().toString();
223 logger.debug(methodName + START_STRING);
224 Boolean response = false;
225 String url = systemPropertyHelper.getFullServicePath(path);;
229 Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url);
230 final Response cres = client.target(url)
232 .accept(MediaType.APPLICATION_JSON)
233 .header(TRANSACTION_ID_HEADER, transId)
234 .header(FROM_APP_ID_HEADER, sourceID)
235 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
237 Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres);
238 if (cres.getStatusInfo().equals(Response.Status.NOT_FOUND)) {
239 logger.debug(EELFLoggerDelegate.debugLogger, "Resource does not exist...: " + cres.getStatus()
240 + ":" + cres.readEntity(String.class));
242 } else if (cres.getStatusInfo().equals(Response.Status.OK) || cres.getStatusInfo().equals(Response.Status.NO_CONTENT)) {
243 logger.debug(EELFLoggerDelegate.debugLogger, "Resource " + url + " deleted");
244 logger.info(EELFLoggerDelegate.errorLogger, "Resource " + url + " deleted");
247 logger.debug(EELFLoggerDelegate.debugLogger, "Deleting Resource failed: " + cres.getStatus()
248 + ":" + cres.readEntity(String.class));
252 } catch (Exception e) {
253 logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
262 * @param fromAppId the from app id
263 * @param path the path
264 * @param payload the payload
268 public Response RestPut(String fromAppId, String path, String payload, boolean xml) {
269 String methodName = "RestPut";
270 String url=systemPropertyHelper.getFullServicePath(path);
271 String transId = UUID.randomUUID().toString();
272 logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING);
274 Response response = null;
277 Logging.logRequest(outgoingRequestsLogger, HttpMethod.PUT, url, payload);
278 response = authenticateRequest(client.target(url)
280 .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON)
281 .header(TRANSACTION_ID_HEADER, transId)
282 .header(FROM_APP_ID_HEADER, fromAppId))
283 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
284 .put(Entity.entity(payload, MediaType.APPLICATION_JSON));
285 Logging.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, response);
287 if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
288 logger.info(EELFLoggerDelegate.errorLogger, getValidResponseLogMessage(methodName));
289 logger.debug(EELFLoggerDelegate.debugLogger, getValidResponseLogMessage(methodName));
291 logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response));
293 } catch (Exception e) {
294 logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
304 * @param fromAppId the from app id
305 * @param path the path
306 * @param payload the payload
310 public Response RestPost(String fromAppId, String path, String payload, boolean xml) {
311 String methodName = "RestPost";
312 String url=systemPropertyHelper.getServiceBasePath(path);
313 String transId = UUID.randomUUID().toString();
314 logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING);
316 Response response = null;
319 Logging.logRequest(outgoingRequestsLogger, HttpMethod.POST, url, payload);
320 response = authenticateRequest(client.target(systemPropertyHelper.getServiceBasePath(path))
322 .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON)
323 .header(TRANSACTION_ID_HEADER, transId)
324 .header(FROM_APP_ID_HEADER, fromAppId))
325 .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId())
326 .post(Entity.entity(payload, MediaType.APPLICATION_JSON));
327 Logging.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, response);
329 if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
330 logger.info(EELFLoggerDelegate.errorLogger, getValidResponseLogMessage(methodName));
331 logger.debug(EELFLoggerDelegate.debugLogger, getValidResponseLogMessage(methodName));
333 logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response));
335 } catch (Exception e) {
336 logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e));
341 protected String getFailedResponseLogMessage(String path, String methodName, Exception e) {
342 return methodName + URL_DECLARATION + path + ", Exception: " + e.toString();
345 protected String getValidResponseLogMessage(String methodName) {
346 return methodName + URL_DECLARATION;
349 protected String getInvalidResponseLogMessage(String path, String methodName, Response cres) {
350 return methodName + " with status=" + cres.getStatus() + URL_DECLARATION + path;
353 private Invocation.Builder authenticateRequest(Invocation.Builder requestBuilder) throws InvalidPropertyException, UnsupportedEncodingException {
354 return requestBuilder
355 .header("Authorization", "Basic " + systemPropertyHelper.getEncodedCredentials());