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.logging.Headers.PARTNER_NAME;
24 import static org.onap.vid.utils.Logging.ONAP_REQUEST_ID_HEADER_KEY;
25 import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY;
26 import static org.onap.vid.utils.Logging.getMethodCallerName;
27 import static org.onap.vid.utils.Logging.getMethodName;
29 import com.att.eelf.configuration.EELFLogger;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import java.util.Collections;
32 import java.util.Optional;
33 import javax.ws.rs.client.Client;
34 import javax.ws.rs.client.Entity;
35 import javax.ws.rs.client.Invocation;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.MultivaluedHashMap;
38 import javax.ws.rs.core.Response;
39 import org.apache.commons.codec.binary.Base64;
40 import org.apache.http.HttpException;
41 import org.eclipse.jetty.util.security.Password;
42 import org.glassfish.jersey.client.ClientProperties;
43 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
44 import org.onap.vid.aai.ExceptionWithRequestInfo;
45 import org.onap.vid.aai.util.HttpClientMode;
46 import org.onap.vid.aai.util.HttpsAuthClient;
47 import org.onap.vid.client.HttpBasicClient;
48 import org.onap.vid.exceptions.GenericUncheckedException;
49 import org.onap.vid.mso.rest.RestInterface;
50 import org.onap.vid.utils.Logging;
51 import org.onap.vid.utils.SystemPropertiesWrapper;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.http.HttpMethod;
56 * Created by pickjonathan on 26/06/2017.
58 public class RestMsoImplementation implements RestInterface {
64 protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMsoImplementation.class);
65 private final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("mso");
68 private Client client = null;
71 protected HttpsAuthClient httpsAuthClient;
72 protected SystemPropertiesWrapper systemProperties;
73 protected final Logging loggingService;
75 private static final String START_LOG = " start";
76 private static final String APPLICATION_JSON = "application/json";
77 private static final String WITH_STATUS = " with status=";
78 private static final String URL_LOG = ", url=";
79 private static final String NO_RESPONSE_ENTITY_LOG = " No response entity, this is probably ok, e=";
80 private static final String WITH_URL_LOG = " with url=";
81 private static final String EXCEPTION_LOG = ", Exception: ";
82 private static final String REST_API_SUCCESSFULL_LOG = " REST api was successfull!";
83 private static final String REST_MSG_TEMPLATE = "start {}->{}({}, {}, {})";
84 /** The common headers. */
86 * Instantiates a new mso rest interface.
90 public RestMsoImplementation(HttpsAuthClient httpsAuthClient, SystemPropertiesWrapper systemProperties, Logging loggingService){
91 this.httpsAuthClient=httpsAuthClient;
92 this.systemProperties = systemProperties;
93 this.loggingService = loggingService;
96 @SuppressWarnings("Duplicates")
97 protected MultivaluedHashMap<String, Object> initMsoClient()
99 final String methodname = "initRestClient()";
101 final String username = systemProperties.getProperty(MsoProperties.MSO_USER_NAME);
102 final String password = systemProperties.getProperty(MsoProperties.MSO_PASSWORD);
103 final String mso_url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL);
104 final String decrypted_password = Password.deobfuscate(password);
106 String authString = username + ":" + decrypted_password;
108 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
109 String authStringEnc = new String(authEncBytes);
111 MultivaluedHashMap<String, Object> commonHeaders = new MultivaluedHashMap();
112 commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
113 commonHeaders.put(PARTNER_NAME.getHeaderName(), Collections.singletonList(PARTNER_NAME.getHeaderValue()));
115 String requestIdValue = Logging.extractOrGenerateRequestId();
116 commonHeaders.put(REQUEST_ID_HEADER_KEY, Collections.singletonList(requestIdValue));
117 commonHeaders.put(ONAP_REQUEST_ID_HEADER_KEY, Collections.singletonList(requestIdValue));
120 boolean useSsl = true;
121 if ( (mso_url != null) && ( !(mso_url.isEmpty()) ) ) {
122 useSsl = mso_url.startsWith("https");
124 if (client == null) {
128 client = httpsAuthClient.getClient(HttpClientMode.WITHOUT_KEYSTORE);
131 client = HttpBasicClient.getClient();
133 } catch (Exception e) {
134 logger.info(EELFLoggerDelegate.errorLogger,methodname + " Unable to get the SSL client");
138 return commonHeaders;
141 public <T> RestObjectWithRequestInfo<T> Get(T t, String path, RestObject<T> restObject, boolean warpException) {
142 String methodName = "Get";
144 logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_LOG);
147 String rawData = null;
148 Integer status = null;
152 url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
154 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
155 loggingService.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
156 final Response cres = client.target(url)
158 .accept(APPLICATION_JSON)
159 .headers(commonHeaders)
161 loggingService.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres);
164 status = cres.getStatus();
165 rawData = cres.readEntity(String.class);
167 restObject.setStatusCode(status);
169 if (status == 200 || status == 202) {
170 t = (T) cres.readEntity(t.getClass());
172 logger.debug(EELFLoggerDelegate.debugLogger, methodName + REST_API_SUCCESSFULL_LOG);
175 throw new GenericUncheckedException(new HttpException(methodName + WITH_STATUS + status + " (200 or 202 expected), url= " + url));
178 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " received status=" + status);
180 return new RestObjectWithRequestInfo<>(HttpMethod.GET, url, restObject, status, rawData);
181 } catch (RuntimeException e) {
182 throw warpException ? new ExceptionWithRequestInfo(HttpMethod.GET, url, rawData, status, e) : e;
187 public <T> RestObject<T> GetForObject(String path, Class<T> clazz) {
188 final String methodName = getMethodName();
189 logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {})", getMethodCallerName(), methodName, path, clazz);
191 String url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
192 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " sending request to url= " + url);
194 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
195 loggingService.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
196 final Response cres = client.target(url)
198 .accept(APPLICATION_JSON)
199 .headers(commonHeaders)
201 loggingService.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres);
202 final RestObject<T> restObject = cresToRestObject(cres, clazz);
203 int status = cres.getStatus();
205 if (status == 200 || status == 202) {
206 logger.debug(EELFLoggerDelegate.debugLogger, methodName + REST_API_SUCCESSFULL_LOG);
208 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_STATUS +status+ URL_LOG +url);
211 logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status );
216 public <T> RestObject<T> PostForObject(Object requestDetails, String path, Class<T> clazz) {
217 logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz);
218 return restCall(HttpMethod.POST, clazz, requestDetails, path);
221 public <T> RestObject<T> DeleteForObject(Object requestDetails, String path, Class<T> clazz) {
222 logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz);
223 return restCall(HttpMethod.DELETE, clazz, requestDetails, path);
227 public void Post(String t, Object r, String path, RestObject<String> restObject) {
228 logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), t.getClass(), r, path);
229 restObject.copyFrom(restCall(HttpMethod.POST, String.class, r, path));
232 public Invocation.Builder prepareClient(String path, String methodName) {
233 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
235 String url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
236 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + " sending request to url= " + url);
237 // Change the content length
238 return client.target(url)
240 .accept(APPLICATION_JSON)
241 .headers(commonHeaders);
244 public <T> RestObject<T> restCall(HttpMethod httpMethod, Class<T> tClass, Object payload, String path) {
245 return restCall(httpMethod, tClass, payload, path, Optional.empty());
250 user id is needed to be pass as X-RequestorID in new MSO flows like Delete instanceGroup
252 public <T> RestObject<T> restCall(HttpMethod httpMethod, Class<T> tClass, Object payload, String path, Optional<String> userId) {
253 String methodName = httpMethod.name();
258 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
259 userId.ifPresent(id->commonHeaders.put("X-RequestorID", Collections.singletonList(id)));
261 url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
262 loggingService.logRequest(outgoingRequestsLogger, httpMethod, url, payload);
263 // Change the content length
264 final Invocation.Builder restBuilder = client.target(url)
266 .accept(APPLICATION_JSON)
267 .headers(commonHeaders)
268 .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
271 Invocation restInvocation = payload==null ?
272 restBuilder.build(httpMethod.name()) :
273 restBuilder.build(httpMethod.name(), Entity.entity(payload, MediaType.APPLICATION_JSON));
274 final Response cres = restInvocation.invoke();
276 loggingService.logResponse(outgoingRequestsLogger, httpMethod, url, cres);
277 return cresToRestObject(cres, tClass);
279 catch (Exception e) {
280 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString());
286 private <T> RestObject<T> cresToRestObject(Response cres, Class<?> tClass) {
287 RestObject<T> restObject = new RestObject<>();
289 String rawEntity = null;
292 rawEntity = cres.readEntity(String.class);
293 restObject.setRaw(rawEntity);
294 T t = (T) new ObjectMapper().readValue(rawEntity, tClass);
297 catch ( Exception e ) {
299 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + " Error reading response entity as " + tClass + ": , e="
300 + e.getMessage() + ", Entity=" + rawEntity);
301 } catch (Exception e2) {
302 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + NO_RESPONSE_ENTITY_LOG
307 int status = cres.getStatus();
308 restObject.setStatusCode (status);
314 public <T> void Put(T t, org.onap.vid.changeManagement.RequestDetailsWrapper r, String path, RestObject<T> restObject) {
316 String methodName = "Put";
319 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + START_LOG);
323 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
325 url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
326 loggingService.logRequest(outgoingRequestsLogger, HttpMethod.PUT, url, r);
327 // Change the content length
328 final Response cres = client.target(url)
330 .accept(APPLICATION_JSON)
331 .headers(commonHeaders)
332 //.header("content-length", 201)
333 .put(Entity.entity(r, MediaType.APPLICATION_JSON));
335 loggingService.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, cres);
338 t = (T) cres.readEntity(t.getClass());
341 catch ( Exception e ) {
342 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + NO_RESPONSE_ENTITY_LOG
347 int status = cres.getStatus();
348 restObject.setStatusCode (status);
350 if ( status >= 200 && status <= 299 ) {
351 logger.info(EELFLoggerDelegate.errorLogger, "<== " + methodName + REST_API_SUCCESSFULL_LOG);
352 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + REST_API_SUCCESSFULL_LOG);
355 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_STATUS +status+ URL_LOG +url);
358 } catch (Exception e)
360 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString());