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