Testfix: Expect 4 additional TOSCA `Input` fields
[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             if (status == 200) {
102                 if (t instanceof String) {
103                     restObject.set((T)rawData);
104                 }
105                 else {
106                     restObject.set(JACKSON_OBJECT_MAPPER.readValue(rawData, new TypeReference<T>() {}));
107                 }
108                 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + SUCCESSFUL_API_MESSAGE);
109                 logger.info(EELFLoggerDelegate.errorLogger, "<== " + methodName + SUCCESSFUL_API_MESSAGE);
110             } else {
111                 throw new GenericUncheckedException(new HttpException(String.format("%s with status=%d, url=%s", methodName, status, url)));
112             }
113             return new RestObjectWithRequestInfo<>(HttpMethod.GET, url, restObject, status, rawData);
114         }
115         catch (Exception e) {
116             throw new ExceptionWithRequestInfo(HttpMethod.GET, url, rawData, status, e);
117         }
118     }
119
120     public <T> void Delete(T t, String sourceID, String path, RestObject<T> restObject) {
121         initRestClient();
122         String url = String.format("%s%s", propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path);
123         Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url);
124         Map<String, String> requestHeaders = ImmutableMap.<String, String>builder()
125                 .putAll(commonHeaders)
126                 .put(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()).build();
127         final HttpResponse<T> response = (HttpResponse<T>) syncRestClient.delete(url, requestHeaders, t.getClass());
128
129         Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, response);
130
131         int status = response.getStatus();
132         restObject.setStatusCode(status);
133
134         t = response.getBody();
135         restObject.set(t);
136     }
137
138     public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
139         return clazz.newInstance();
140     }
141
142     private String calcEncodedAuthString() {
143         String retrievedUsername = propertyGetter.apply(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
144         final String username = retrievedUsername.isEmpty() ? "" : retrievedUsername;
145
146         String retrievedPassword = propertyGetter.apply(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
147         final String password = retrievedPassword.isEmpty() ? "" : getDeobfuscatedPassword(retrievedPassword);
148
149         return Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
150     }
151
152     private static String getDeobfuscatedPassword(String password) {
153         return password.contains("OBF:") ? Password.deobfuscate(password) : password;
154     }
155 }