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 com.att.eelf.configuration.EELFLogger;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import org.apache.commons.codec.binary.Base64;
26 import org.apache.http.HttpException;
27 import org.eclipse.jetty.util.security.Password;
28 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
29 import org.onap.portalsdk.core.util.SystemProperties;
30 import org.onap.vid.aai.ExceptionWithRequestInfo;
31 import org.onap.vid.aai.util.HttpClientMode;
32 import org.onap.vid.aai.util.HttpsAuthClient;
33 import org.onap.vid.client.HttpBasicClient;
34 import org.onap.vid.exceptions.GenericUncheckedException;
35 import org.onap.vid.mso.rest.RestInterface;
36 import org.onap.vid.utils.Logging;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.http.HttpMethod;
40 import javax.ws.rs.client.Client;
41 import javax.ws.rs.client.Entity;
42 import javax.ws.rs.client.Invocation;
43 import javax.ws.rs.core.MediaType;
44 import javax.ws.rs.core.MultivaluedHashMap;
45 import javax.ws.rs.core.Response;
46 import java.util.Collections;
47 import java.util.Optional;
49 import static org.onap.vid.utils.Logging.*;
52 * Created by pickjonathan on 26/06/2017.
54 public abstract class RestMsoImplementation implements RestInterface {
59 protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMsoImplementation.class);
60 private final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("mso");
63 private Client client = null;
66 protected HttpsAuthClient httpsAuthClient;
68 private static final String START_LOG = " start";
69 private static final String APPLICATION_JSON = "application/json";
70 private static final String WITH_STATUS = " with status=";
71 private static final String URL_LOG = ", url=";
72 private static final String NO_RESPONSE_ENTITY_LOG = " No response entity, this is probably ok, e=";
73 private static final String WITH_URL_LOG = " with url=";
74 private static final String EXCEPTION_LOG = ", Exception: ";
75 private static final String REST_API_SUCCESSFULL_LOG = " REST api was successfull!";
76 private static final String REST_MSG_TEMPLATE = "start {}->{}({}, {}, {})";
77 /** The common headers. */
79 * Instantiates a new mso rest interface.
82 @SuppressWarnings("Duplicates")
83 protected MultivaluedHashMap<String, Object> initMsoClient()
85 final String methodname = "initRestClient()";
87 final String username = SystemProperties.getProperty(MsoProperties.MSO_USER_NAME);
88 final String password = SystemProperties.getProperty(MsoProperties.MSO_PASSWORD);
89 final String mso_url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL);
90 final String decrypted_password = Password.deobfuscate(password);
92 String authString = username + ":" + decrypted_password;
94 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
95 String authStringEnc = new String(authEncBytes);
97 MultivaluedHashMap<String, Object> commonHeaders = new MultivaluedHashMap();
98 commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
99 commonHeaders.put("X-ONAP-PartnerName", Collections.singletonList("VID"));
101 String requestIdValue = Logging.extractOrGenerateRequestId();
102 commonHeaders.put(REQUEST_ID_HEADER_KEY, Collections.singletonList(requestIdValue));
103 commonHeaders.put(ONAP_REQUEST_ID_HEADER_KEY, Collections.singletonList(requestIdValue));
106 boolean useSsl = true;
107 if ( (mso_url != null) && ( !(mso_url.isEmpty()) ) ) {
108 useSsl = mso_url.startsWith("https");
110 if (client == null) {
114 client = httpsAuthClient.getClient(HttpClientMode.WITHOUT_KEYSTORE);
117 client = HttpBasicClient.getClient();
119 } catch (Exception e) {
120 logger.info(EELFLoggerDelegate.errorLogger,methodname + " Unable to get the SSL client");
124 return commonHeaders;
127 public <T> RestObjectWithRequestInfo<T> Get(T t, String path, RestObject<T> restObject, boolean warpException) {
128 String methodName = "Get";
130 logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_LOG);
133 String rawData = null;
134 Integer status = null;
138 url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
140 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
141 Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
142 final Response cres = client.target(url)
144 .accept(APPLICATION_JSON)
145 .headers(commonHeaders)
147 Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres);
150 status = cres.getStatus();
151 rawData = cres.readEntity(String.class);
153 restObject.setStatusCode(status);
155 if (status == 200 || status == 202) {
156 t = (T) cres.readEntity(t.getClass());
158 logger.debug(EELFLoggerDelegate.debugLogger, methodName + REST_API_SUCCESSFULL_LOG);
161 throw new GenericUncheckedException(new HttpException(methodName + WITH_STATUS + status + " (200 or 202 expected), url= " + url));
164 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " received status=" + status);
166 return new RestObjectWithRequestInfo<>(HttpMethod.GET, url, restObject, status, rawData);
167 } catch (RuntimeException e) {
168 throw warpException ? new ExceptionWithRequestInfo(HttpMethod.GET, url, rawData, status, e) : e;
173 public <T> RestObject<T> GetForObject(String path, Class<T> clazz) {
174 final String methodName = getMethodName();
175 logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {})", getMethodCallerName(), methodName, path, clazz);
177 String url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
178 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " sending request to url= " + url);
180 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
181 Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
182 final Response cres = client.target(url)
184 .accept(APPLICATION_JSON)
185 .headers(commonHeaders)
187 Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres);
188 final RestObject<T> restObject = cresToRestObject(cres, clazz);
189 int status = cres.getStatus();
191 if (status == 200 || status == 202) {
192 logger.debug(EELFLoggerDelegate.debugLogger, methodName + REST_API_SUCCESSFULL_LOG);
194 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_STATUS +status+ URL_LOG +url);
197 logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status );
203 public <T> void Delete(T t, Object r, String path, RestObject<T> restObject) {
205 String methodName = "Delete";
209 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + START_LOG);
212 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
214 url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
215 Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url, r);
216 cres = client.target(url)
219 .accept(APPLICATION_JSON)
220 .headers(commonHeaders)
222 .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke();
223 Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres);
224 int status = cres.getStatus();
225 restObject.setStatusCode (status);
227 if (status == 404) { // resource not found
228 String msg = "Resource does not exist...: " + cres.getStatus();
229 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg);
230 } else if (status == 200 || status == 204){
231 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + "Resource " + url + " deleted");
232 } else if (status == 202) {
233 String msg = "Delete in progress: " + status;
234 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg);
237 String msg = "Deleting Resource failed: " + status;
238 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg);
242 t = (T) cres.readEntity(t.getClass());
245 catch ( Exception e ) {
246 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + NO_RESPONSE_ENTITY_LOG
253 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString());
259 public <T> RestObject<T> PostForObject(Object requestDetails, String path, Class<T> clazz) {
260 logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz);
261 return restCall(HttpMethod.POST, clazz, requestDetails, path);
264 public <T> RestObject<T> DeleteForObject(Object requestDetails, String path, Class<T> clazz) {
265 logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz);
266 return restCall(HttpMethod.DELETE, clazz, requestDetails, path);
270 public void Post(String t, Object r, String path, RestObject<String> restObject) {
271 logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), t.getClass(), r, path);
272 restObject.copyFrom(restCall(HttpMethod.POST, String.class, r, path));
275 public Invocation.Builder prepareClient(String path, String methodName) {
276 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
278 String url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
279 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + " sending request to url= " + url);
280 // Change the content length
281 return client.target(url)
283 .accept(APPLICATION_JSON)
284 .headers(commonHeaders);
287 public <T> RestObject<T> restCall(HttpMethod httpMethod, Class<T> tClass, Object payload, String path) {
288 return restCall(httpMethod, tClass, payload, path, Optional.empty());
293 user id is needed to be pass as X-RequestorID in new MSO flows like Delete instanceGroup
295 public <T> RestObject<T> restCall(HttpMethod httpMethod, Class<T> tClass, Object payload, String path, Optional<String> userId) {
296 String methodName = httpMethod.name();
301 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
302 userId.ifPresent(id->commonHeaders.put("X-RequestorID", Collections.singletonList(id)));
304 url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
305 Logging.logRequest(outgoingRequestsLogger, httpMethod, url, payload);
306 // Change the content length
307 final Invocation.Builder restBuilder = client.target(url)
309 .accept(APPLICATION_JSON)
310 .headers(commonHeaders);
312 Invocation restInvocation = payload==null ?
313 restBuilder.build(httpMethod.name()) :
314 restBuilder.build(httpMethod.name(), Entity.entity(payload, MediaType.APPLICATION_JSON));
315 final Response cres = restInvocation.invoke();
317 Logging.logResponse(outgoingRequestsLogger, httpMethod, url, cres);
318 return cresToRestObject(cres, tClass);
320 catch (Exception e) {
321 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString());
327 private <T> RestObject<T> cresToRestObject(Response cres, Class<?> tClass) {
328 RestObject<T> restObject = new RestObject<>();
330 String rawEntity = null;
333 rawEntity = cres.readEntity(String.class);
334 restObject.setRaw(rawEntity);
335 T t = (T) new ObjectMapper().readValue(rawEntity, tClass);
338 catch ( Exception e ) {
340 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + " Error reading response entity as " + tClass + ": , e="
341 + e.getMessage() + ", Entity=" + rawEntity);
342 } catch (Exception e2) {
343 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + NO_RESPONSE_ENTITY_LOG
348 int status = cres.getStatus();
349 restObject.setStatusCode (status);
356 public <T> void Put(T t, org.onap.vid.changeManagement.RequestDetailsWrapper r, String path, RestObject<T> restObject) {
358 String methodName = "Put";
361 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + START_LOG);
365 MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
367 url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
368 Logging.logRequest(outgoingRequestsLogger, HttpMethod.PUT, url, r);
369 // Change the content length
370 final Response cres = client.target(url)
372 .accept(APPLICATION_JSON)
373 .headers(commonHeaders)
374 //.header("content-length", 201)
375 .put(Entity.entity(r, MediaType.APPLICATION_JSON));
377 Logging.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, cres);
380 t = (T) cres.readEntity(t.getClass());
383 catch ( Exception e ) {
384 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + NO_RESPONSE_ENTITY_LOG
388 int status = cres.getStatus();
389 restObject.setStatusCode (status);
391 if ( status >= 200 && status <= 299 ) {
392 logger.info(EELFLoggerDelegate.errorLogger, "<== " + methodName + REST_API_SUCCESSFULL_LOG);
393 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + REST_API_SUCCESSFULL_LOG);
396 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_STATUS +status+ URL_LOG +url);
399 } catch (Exception e)
401 logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString());