2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2019 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=========================================================
21 package org.onap.vid.mso;
23 import static org.onap.vid.utils.Logging.ONAP_REQUEST_ID_HEADER_KEY;
24 import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY;
25 import static org.onap.vid.utils.Logging.getMethodCallerName;
26 import static org.onap.vid.utils.Logging.getMethodName;
28 import com.att.eelf.configuration.EELFLogger;
29 import com.fasterxml.jackson.databind.ObjectMapper;
30 import java.util.Collections;
31 import java.util.Optional;
32 import javax.ws.rs.client.Client;
33 import javax.ws.rs.client.Entity;
34 import javax.ws.rs.client.Invocation;
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.MultivaluedHashMap;
37 import javax.ws.rs.core.Response;
38 import org.apache.commons.codec.binary.Base64;
39 import org.apache.http.HttpException;
40 import org.eclipse.jetty.util.security.Password;
41 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
42 import org.onap.vid.aai.ExceptionWithRequestInfo;
43 import org.onap.vid.aai.util.HttpClientMode;
44 import org.onap.vid.aai.util.HttpsAuthClient;
45 import org.onap.vid.client.HttpBasicClient;
46 import org.onap.vid.exceptions.GenericUncheckedException;
47 import org.onap.vid.mso.rest.RestInterface;
48 import org.onap.vid.utils.Logging;
49 import org.onap.vid.utils.SystemPropertiesWrapper;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.http.HttpMethod;
54 * Created by pickjonathan on 26/06/2017.
56 public class RestMsoImplementation implements RestInterface {
62 protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMsoImplementation.class);
63 private final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("mso");
66 private Client client = null;
69 protected HttpsAuthClient httpsAuthClient;
70 protected SystemPropertiesWrapper systemProperties;
71 protected final Logging loggingService;
73 private static final String START_LOG = " start";
74 private static final String APPLICATION_JSON = "application/json";
75 private static final String WITH_STATUS = " with status=";
76 private static final String URL_LOG = ", url=";
77 private static final String NO_RESPONSE_ENTITY_LOG = " No response entity, this is probably ok, e=";
78 private static final String WITH_URL_LOG = " with url=";
79 private static final String EXCEPTION_LOG = ", Exception: ";
80 private static final String REST_API_SUCCESSFULL_LOG = " REST api was successfull!";
81 private static final String REST_MSG_TEMPLATE = "start {}->{}({}, {}, {})";
82 /** The common headers. */
84 * Instantiates a new mso rest interface.
88 protected RestMsoImplementation(HttpsAuthClient httpsAuthClient, SystemPropertiesWrapper systemProperties, Logging loggingService){
89 this.httpsAuthClient=httpsAuthClient;
90 this.systemProperties = systemProperties;
91 this.loggingService = loggingService;
94 @SuppressWarnings("Duplicates")
95 protected MultivaluedHashMap<String, Object> initMsoClient()
97 final String methodname = "initRestClient()";
99 final String username = systemProperties.getProperty(MsoProperties.MSO_USER_NAME);
100 final String password = systemProperties.getProperty(MsoProperties.MSO_PASSWORD);
101 final String mso_url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL);
102 final String decrypted_password = Password.deobfuscate(password);
104 String authString = username + ":" + decrypted_password;
106 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
107 String authStringEnc = new String(authEncBytes);
109 MultivaluedHashMap<String, Object> commonHeaders = new MultivaluedHashMap();
110 commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
111 commonHeaders.put("X-ONAP-PartnerName", Collections.singletonList("VID"));
113 String requestIdValue = Logging.extractOrGenerateRequestId();
114 commonHeaders.put(REQUEST_ID_HEADER_KEY, Collections.singletonList(requestIdValue));
115 commonHeaders.put(ONAP_REQUEST_ID_HEADER_KEY, Collections.singletonList(requestIdValue));
118 boolean useSsl = true;
119 if ( (mso_url != null) && ( !(mso_url.isEmpty()) ) ) {
120 useSsl = mso_url.startsWith("https");
122 if (client == null) {
126 client = httpsAuthClient.getClient(HttpClientMode.WITHOUT_KEYSTORE);
129 client = HttpBasicClient.getClient();
131 } catch (Exception e) {
132 logger.info(EELFLoggerDelegate.errorLogger,methodname + " Unable to get the SSL client");
136 return commonHeaders;
139 public <T> RestObjectWithRequestInfo<T> Get(T t, String path, RestObject<T> restObject, boolean warpException) {
140 String methodName = "Get";
142 logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_LOG);
145 String rawData = null;
146 Integer status = null;
150 url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
152 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
153 loggingService.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
154 final Response cres = client.target(url)
156 .accept(APPLICATION_JSON)
157 .headers(commonHeaders)
159 loggingService.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres);
162 status = cres.getStatus();
163 rawData = cres.readEntity(String.class);
165 restObject.setStatusCode(status);
167 if (status == 200 || status == 202) {
168 t = (T) cres.readEntity(t.getClass());
170 logger.debug(EELFLoggerDelegate.debugLogger, methodName + REST_API_SUCCESSFULL_LOG);
173 throw new GenericUncheckedException(new HttpException(methodName + WITH_STATUS + status + " (200 or 202 expected), url= " + url));
176 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " received status=" + status);
178 return new RestObjectWithRequestInfo<>(HttpMethod.GET, url, restObject, status, rawData);
179 } catch (RuntimeException e) {
180 throw warpException ? new ExceptionWithRequestInfo(HttpMethod.GET, url, rawData, status, e) : e;
185 public <T> RestObject<T> GetForObject(String path, Class<T> clazz) {
186 final String methodName = getMethodName();
187 logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {})", getMethodCallerName(), methodName, path, clazz);
189 String url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
190 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " sending request to url= " + url);
192 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
193 loggingService.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
194 final Response cres = client.target(url)
196 .accept(APPLICATION_JSON)
197 .headers(commonHeaders)
199 loggingService.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres);
200 final RestObject<T> restObject = cresToRestObject(cres, clazz);
201 int status = cres.getStatus();
203 if (status == 200 || status == 202) {
204 logger.debug(EELFLoggerDelegate.debugLogger, methodName + REST_API_SUCCESSFULL_LOG);
206 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_STATUS +status+ URL_LOG +url);
209 logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status );
215 public <T> void Delete(T t, Object r, String path, RestObject<T> restObject) {
217 String methodName = "Delete";
221 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + START_LOG);
224 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
226 url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
227 loggingService.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url, r);
228 cres = client.target(url)
231 .accept(APPLICATION_JSON)
232 .headers(commonHeaders)
234 .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON))
236 loggingService.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres);
237 int status = cres.getStatus();
238 restObject.setStatusCode (status);
240 if (status == 404) { // resource not found
241 String msg = "Resource does not exist...: " + cres.getStatus();
242 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg);
243 } else if (status == 200 || status == 204){
244 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + "Resource " + url + " deleted");
245 } else if (status == 202) {
246 String msg = "Delete in progress: " + status;
247 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg);
250 String msg = "Deleting Resource failed: " + status;
251 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg);
255 t = (T) cres.readEntity(t.getClass());
258 catch ( Exception e ) {
259 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + NO_RESPONSE_ENTITY_LOG
267 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString());
272 public <T> RestObject<T> PostForObject(Object requestDetails, String path, Class<T> clazz) {
273 logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz);
274 return restCall(HttpMethod.POST, clazz, requestDetails, path);
277 public <T> RestObject<T> DeleteForObject(Object requestDetails, String path, Class<T> clazz) {
278 logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz);
279 return restCall(HttpMethod.DELETE, clazz, requestDetails, path);
283 public void Post(String t, Object r, String path, RestObject<String> restObject) {
284 logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), t.getClass(), r, path);
285 restObject.copyFrom(restCall(HttpMethod.POST, String.class, r, path));
288 public Invocation.Builder prepareClient(String path, String methodName) {
289 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
291 String url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
292 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + " sending request to url= " + url);
293 // Change the content length
294 return client.target(url)
296 .accept(APPLICATION_JSON)
297 .headers(commonHeaders);
300 public <T> RestObject<T> restCall(HttpMethod httpMethod, Class<T> tClass, Object payload, String path) {
301 return restCall(httpMethod, tClass, payload, path, Optional.empty());
306 user id is needed to be pass as X-RequestorID in new MSO flows like Delete instanceGroup
308 public <T> RestObject<T> restCall(HttpMethod httpMethod, Class<T> tClass, Object payload, String path, Optional<String> userId) {
309 String methodName = httpMethod.name();
314 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
315 userId.ifPresent(id->commonHeaders.put("X-RequestorID", Collections.singletonList(id)));
317 url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
318 loggingService.logRequest(outgoingRequestsLogger, httpMethod, url, payload);
319 // Change the content length
320 final Invocation.Builder restBuilder = client.target(url)
322 .accept(APPLICATION_JSON)
323 .headers(commonHeaders);
325 Invocation restInvocation = payload==null ?
326 restBuilder.build(httpMethod.name()) :
327 restBuilder.build(httpMethod.name(), Entity.entity(payload, MediaType.APPLICATION_JSON));
328 final Response cres = restInvocation.invoke();
330 loggingService.logResponse(outgoingRequestsLogger, httpMethod, url, cres);
331 return cresToRestObject(cres, tClass);
333 catch (Exception e) {
334 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString());
340 private <T> RestObject<T> cresToRestObject(Response cres, Class<?> tClass) {
341 RestObject<T> restObject = new RestObject<>();
343 String rawEntity = null;
346 rawEntity = cres.readEntity(String.class);
347 restObject.setRaw(rawEntity);
348 T t = (T) new ObjectMapper().readValue(rawEntity, tClass);
351 catch ( Exception e ) {
353 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + " Error reading response entity as " + tClass + ": , e="
354 + e.getMessage() + ", Entity=" + rawEntity);
355 } catch (Exception e2) {
356 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + NO_RESPONSE_ENTITY_LOG
361 int status = cres.getStatus();
362 restObject.setStatusCode (status);
368 public <T> void Put(T t, org.onap.vid.changeManagement.RequestDetailsWrapper r, String path, RestObject<T> restObject) {
370 String methodName = "Put";
373 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + START_LOG);
377 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
379 url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
380 loggingService.logRequest(outgoingRequestsLogger, HttpMethod.PUT, url, r);
381 // Change the content length
382 final Response cres = client.target(url)
384 .accept(APPLICATION_JSON)
385 .headers(commonHeaders)
386 //.header("content-length", 201)
387 .put(Entity.entity(r, MediaType.APPLICATION_JSON));
389 loggingService.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, cres);
392 t = (T) cres.readEntity(t.getClass());
395 catch ( Exception e ) {
396 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + NO_RESPONSE_ENTITY_LOG
401 int status = cres.getStatus();
402 restObject.setStatusCode (status);
404 if ( status >= 200 && status <= 299 ) {
405 logger.info(EELFLoggerDelegate.errorLogger, "<== " + methodName + REST_API_SUCCESSFULL_LOG);
406 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + REST_API_SUCCESSFULL_LOG);
409 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_STATUS +status+ URL_LOG +url);
412 } catch (Exception e)
414 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString());