001a8ae6d2e042083038057659385c92dd99c060
[vid.git] / vid-app-common / src / main / java / org / onap / vid / scheduler / SchedulerRestInterface.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.vid.scheduler;
22
23 import com.att.eelf.configuration.EELFLogger;
24 import com.fasterxml.jackson.core.type.TypeReference;
25 import com.google.common.collect.ImmutableMap;
26 import com.google.common.collect.Maps;
27 import io.joshworks.restclient.http.HttpResponse;
28 import org.apache.http.HttpException;
29 import org.eclipse.jetty.util.security.Password;
30 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
31 import org.onap.portalsdk.core.util.SystemProperties;
32 import org.onap.vid.aai.ExceptionWithRequestInfo;
33 import org.onap.vid.client.SyncRestClient;
34 import org.onap.vid.client.SyncRestClientInterface;
35 import org.onap.vid.exceptions.GenericUncheckedException;
36 import org.onap.vid.mso.RestObject;
37 import org.onap.vid.mso.RestObjectWithRequestInfo;
38 import org.onap.vid.utils.Logging;
39 import org.springframework.http.HttpMethod;
40 import org.springframework.stereotype.Service;
41
42 import java.util.Base64;
43 import java.util.Collections;
44 import java.util.Map;
45 import java.util.function.Function;
46
47 import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER;
48 import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY;
49
50 @Service
51 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
52
53     private static final  EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("scheduler");
54     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
55     private static final String SUCCESSFUL_API_MESSAGE=" REST api GET was successful!";
56     private SyncRestClientInterface syncRestClient;
57     private Function<String, String> propertyGetter;
58     private Map<String, String> commonHeaders;
59
60     public SchedulerRestInterface() {
61         this.propertyGetter = SystemProperties::getProperty;
62     }
63
64     public SchedulerRestInterface(Function<String, String> propertyGetter) {
65         this.propertyGetter = propertyGetter;
66     }
67
68     public void initRestClient() {
69         logger.info("Starting to initialize rest client ");
70         String authStringEnc = calcEncodedAuthString();
71
72         commonHeaders = Maps.newHashMap();
73         commonHeaders.put("Authorization", "Basic " + authStringEnc);
74
75         syncRestClient = new SyncRestClient();
76
77         logger.info("\t<== Client Initialized \n");
78     }
79
80     public <T> RestObjectWithRequestInfo<T> Get(T t, String path, RestObject<T> restObject) {
81
82         String url = null;
83         String rawData = null;
84         Integer status = null;
85
86         try {
87             String methodName = "Get";
88             url = String.format("%s%s", propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path);
89             initRestClient();
90             Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
91             Map<String, String> requestHeaders = ImmutableMap.<String, String>builder()
92                     .putAll(commonHeaders)
93                     .put(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId())
94                     .build();
95             final HttpResponse<String> response = syncRestClient.get(url, requestHeaders,
96                     Collections.emptyMap(), String.class);
97             Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response);
98             status = response.getStatus();
99             restObject.setStatusCode(status);
100             rawData = response.getBody();
101             restObject.setRaw(rawData);
102             if (status == 200) {
103                 if (t instanceof String) {
104                     restObject.set((T)rawData);
105                 }
106                 else {
107                     restObject.set(JACKSON_OBJECT_MAPPER.readValue(rawData, (Class<T>)t.getClass()));
108                 }
109                 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + SUCCESSFUL_API_MESSAGE);
110                 logger.info(EELFLoggerDelegate.errorLogger, "<== " + methodName + SUCCESSFUL_API_MESSAGE);
111             } else {
112                 throw new GenericUncheckedException(new HttpException(String.format("%s with status=%d, url=%s", methodName, status, url)));
113             }
114             return new RestObjectWithRequestInfo<>(HttpMethod.GET, url, restObject, status, rawData);
115         }
116         catch (Exception e) {
117             throw new ExceptionWithRequestInfo(HttpMethod.GET, url, rawData, status, e);
118         }
119     }
120
121     public <T> void Delete(T t, String sourceID, String path, RestObject<T> restObject) {
122         initRestClient();
123         String url = String.format("%s%s", propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path);
124         Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url);
125         Map<String, String> requestHeaders = ImmutableMap.<String, String>builder()
126                 .putAll(commonHeaders)
127                 .put(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()).build();
128         final HttpResponse<T> response = (HttpResponse<T>) syncRestClient.delete(url, requestHeaders, t.getClass());
129
130         Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, response);
131
132         int status = response.getStatus();
133         restObject.setStatusCode(status);
134
135         t = response.getBody();
136         restObject.set(t);
137     }
138
139     public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
140         return clazz.newInstance();
141     }
142
143     private String calcEncodedAuthString() {
144         String retrievedUsername = propertyGetter.apply(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
145         final String username = retrievedUsername.isEmpty() ? "" : retrievedUsername;
146
147         String retrievedPassword = propertyGetter.apply(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
148         final String password = retrievedPassword.isEmpty() ? "" : getDeobfuscatedPassword(retrievedPassword);
149
150         return Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
151     }
152
153     private static String getDeobfuscatedPassword(String password) {
154         return password.contains("OBF:") ? Password.deobfuscate(password) : password;
155     }
156 }