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.getMethodCallerName;
24 import static org.onap.vid.utils.Logging.getMethodName;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.fasterxml.jackson.databind.ObjectMapper;
28 import java.util.Collections;
29 import java.util.Optional;
30 import javax.ws.rs.client.Client;
31 import javax.ws.rs.client.Entity;
32 import javax.ws.rs.client.Invocation;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.MultivaluedHashMap;
35 import javax.ws.rs.core.Response;
36 import org.apache.commons.codec.binary.Base64;
37 import org.eclipse.jetty.util.security.Password;
38 import org.glassfish.jersey.client.ClientProperties;
39 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
40 import org.onap.vid.aai.util.HttpClientMode;
41 import org.onap.vid.aai.util.HttpsAuthClient;
42 import org.onap.vid.client.HttpBasicClient;
43 import org.onap.vid.logging.VidMetricLogClientFilter;
44 import org.onap.vid.utils.Logging;
45 import org.onap.vid.utils.SystemPropertiesWrapper;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.http.HttpMethod;
50 * Created by pickjonathan on 26/06/2017.
52 public class RestMsoImplementation {
58 protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMsoImplementation.class);
59 private final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("mso");
62 private Client client = null;
65 protected HttpsAuthClient httpsAuthClient;
66 protected SystemPropertiesWrapper systemProperties;
67 protected final Logging loggingService;
69 private static final String START_LOG = " start";
70 private static final String APPLICATION_JSON = "application/json";
71 private static final String WITH_STATUS = " with status=";
72 private static final String URL_LOG = ", url=";
73 private static final String NO_RESPONSE_ENTITY_LOG = " No response entity, this is probably ok, e=";
74 private static final String WITH_URL_LOG = " with url=";
75 private static final String EXCEPTION_LOG = ", Exception: ";
76 private static final String REST_API_SUCCESSFULL_LOG = " REST api was successfull!";
77 private static final String REST_MSG_TEMPLATE = "start {}->{}({}, {}, {})";
78 /** The common headers. */
80 * Instantiates a new mso rest interface.
84 public RestMsoImplementation(HttpsAuthClient httpsAuthClient, SystemPropertiesWrapper systemProperties, Logging loggingService){
85 this.httpsAuthClient=httpsAuthClient;
86 this.systemProperties = systemProperties;
87 this.loggingService = loggingService;
90 @SuppressWarnings("Duplicates")
91 protected MultivaluedHashMap<String, Object> initMsoClient()
93 final String methodname = "initRestClient()";
95 final String username = systemProperties.getProperty(MsoProperties.MSO_USER_NAME);
96 final String password = systemProperties.getProperty(MsoProperties.MSO_PASSWORD);
97 final String mso_url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL);
98 final String decrypted_password = Password.deobfuscate(password);
100 String authString = username + ":" + decrypted_password;
102 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
103 String authStringEnc = new String(authEncBytes);
105 MultivaluedHashMap<String, Object> commonHeaders = new MultivaluedHashMap();
106 commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
108 String requestIdValue = Logging.extractOrGenerateRequestId();
110 boolean useSsl = true;
111 if ( (mso_url != null) && ( !(mso_url.isEmpty()) ) ) {
112 useSsl = mso_url.startsWith("https");
114 if (client == null) {
118 client = httpsAuthClient.getClient(HttpClientMode.WITHOUT_KEYSTORE);
119 registerClientToMetricLogClientFilter(client);
122 client = HttpBasicClient.getClient();
123 registerClientToMetricLogClientFilter(client);
125 } catch (Exception e) {
126 logger.info(EELFLoggerDelegate.errorLogger,methodname + " Unable to get the SSL client");
130 return commonHeaders;
133 private void registerClientToMetricLogClientFilter(Client client) {
134 VidMetricLogClientFilter metricLogClientFilter = new VidMetricLogClientFilter();
135 client.register(metricLogClientFilter);
138 public <T> RestObject<T> GetForObject(String path, Class<T> clazz) {
139 final String methodName = getMethodName();
140 logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {})", getMethodCallerName(), methodName, path, clazz);
142 String url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
143 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " sending request to url= " + url);
145 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
146 loggingService.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
147 final Response cres = client.target(url)
149 .accept(APPLICATION_JSON)
150 .headers(commonHeaders)
152 loggingService.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres);
153 final RestObject<T> restObject = cresToRestObject(cres, clazz);
154 int status = cres.getStatus();
156 if (status == 200 || status == 202) {
157 logger.debug(EELFLoggerDelegate.debugLogger, methodName + REST_API_SUCCESSFULL_LOG);
159 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_STATUS +status+ URL_LOG +url);
162 logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status );
167 public <T> RestObject<T> PostForObject(Object requestDetails, String path, Class<T> clazz) {
168 logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz);
169 return restCall(HttpMethod.POST, clazz, requestDetails, path);
172 public Invocation.Builder prepareClient(String path, String methodName) {
173 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
175 String url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
176 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + " sending request to url= " + url);
177 // Change the content length
178 return client.target(url)
180 .accept(APPLICATION_JSON)
181 .headers(commonHeaders);
184 public <T> RestObject<T> restCall(HttpMethod httpMethod, Class<T> tClass, Object payload, String path) {
185 return restCall(httpMethod, tClass, payload, path, Optional.empty());
190 user id is needed to be pass as X-RequestorID in new MSO flows like Delete instanceGroup
192 public <T> RestObject<T> restCall(HttpMethod httpMethod, Class<T> tClass, Object payload, String path, Optional<String> userId) {
193 String methodName = httpMethod.name();
198 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
199 userId.ifPresent(id->commonHeaders.put("X-RequestorID", Collections.singletonList(id)));
201 url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
202 loggingService.logRequest(outgoingRequestsLogger, httpMethod, url, payload);
203 // Change the content length
204 final Invocation.Builder restBuilder = client.target(url)
206 .accept(APPLICATION_JSON)
207 .headers(commonHeaders)
208 .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
211 Invocation restInvocation = payload==null ?
212 restBuilder.build(httpMethod.name()) :
213 restBuilder.build(httpMethod.name(), Entity.entity(payload, MediaType.APPLICATION_JSON));
214 final Response cres = restInvocation.invoke();
216 loggingService.logResponse(outgoingRequestsLogger, httpMethod, url, cres);
217 return cresToRestObject(cres, tClass);
219 catch (Exception e) {
220 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString());
226 private <T> RestObject<T> cresToRestObject(Response cres, Class<?> tClass) {
227 RestObject<T> restObject = new RestObject<>();
229 String rawEntity = null;
232 rawEntity = cres.readEntity(String.class);
233 restObject.setRaw(rawEntity);
234 T t = (T) new ObjectMapper().readValue(rawEntity, tClass);
237 catch ( Exception e ) {
239 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + " Error reading response entity as " + tClass + ": , e="
240 + e.getMessage() + ", Entity=" + rawEntity);
241 } catch (Exception e2) {
242 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + NO_RESPONSE_ENTITY_LOG
247 int status = cres.getStatus();
248 restObject.setStatusCode (status);