Fix for Penetration test _ Session and cookie management
[vid.git] / vid-app-common / src / main / java / org / onap / vid / mso / RestMsoImplementation.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.mso;
22
23 import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER;
24 import static org.onap.vid.utils.Logging.getMethodCallerName;
25 import static org.onap.vid.utils.Logging.getMethodName;
26
27 import com.att.eelf.configuration.EELFLogger;
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.JaxRsMetricLogClientFilter;
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;
48
49 public class RestMsoImplementation {
50
51     protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMsoImplementation.class);
52     private final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("mso");
53
54     private Client client = null;
55
56     protected HttpsAuthClient httpsAuthClient;
57     protected SystemPropertiesWrapper systemProperties;
58     protected final Logging loggingService;
59
60     private static final String APPLICATION_JSON = "application/json";
61     private static final String WITH_STATUS = " with status=";
62     private static final String URL_LOG = ", url=";
63     private static final String NO_RESPONSE_ENTITY_LOG = " No response entity, this is probably ok, e=";
64     private static final String WITH_URL_LOG = " with url=";
65     private static final String EXCEPTION_LOG = ", Exception: ";
66     private static final String REST_API_SUCCESSFULL_LOG = " REST api was successfull!";
67     private static final String REST_MSG_TEMPLATE = "start {}->{}({}, {}, {})";
68
69     @Autowired
70     public RestMsoImplementation(HttpsAuthClient httpsAuthClient, SystemPropertiesWrapper systemProperties, Logging loggingService){
71         this.httpsAuthClient=httpsAuthClient;
72         this.systemProperties = systemProperties;
73         this.loggingService = loggingService;
74     }
75
76     protected MultivaluedHashMap<String, Object> initMsoClient()
77     {
78         final String methodname = "initRestClient()";
79
80         final String username = systemProperties.getProperty(MsoProperties.MSO_USER_NAME);
81         final String password = systemProperties.getProperty(MsoProperties.MSO_PASSWORD);
82         final String mso_url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL);
83         final String decrypted_password = Password.deobfuscate(password);
84
85         String authString = username + ":" + decrypted_password;
86
87         byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
88         String authStringEnc = new String(authEncBytes);
89
90         MultivaluedHashMap<String, Object> commonHeaders = new MultivaluedHashMap<>();
91         commonHeaders.put("Authorization",  Collections.singletonList(("Basic " + authStringEnc)));
92
93         boolean useSsl = true;
94         if ( (mso_url != null) && ( !(mso_url.isEmpty()) ) ) {
95             useSsl = mso_url.startsWith("https");
96         }
97         if (client == null) {
98
99             try {
100                     if ( useSsl ) {
101                         client = httpsAuthClient.getClient(HttpClientMode.WITHOUT_KEYSTORE);
102                         registerClientToMetricLogClientFilter(client);
103                     }
104                 else {
105                     client = HttpBasicClient.getClient();
106                     registerClientToMetricLogClientFilter(client);
107                 }
108             } catch (Exception e) {
109                 logger.info(EELFLoggerDelegate.errorLogger,methodname + " Unable to get the SSL client");
110             }
111         }
112
113         return commonHeaders;
114     }
115
116     private void registerClientToMetricLogClientFilter(Client client) {
117         JaxRsMetricLogClientFilter metricLogClientFilter = new JaxRsMetricLogClientFilter();
118         client.register(metricLogClientFilter);
119     }
120
121     public <T> RestObject<T> GetForObject(String path, Class<T> clazz) {
122         final String methodName = getMethodName();
123         logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {})", getMethodCallerName(), methodName, path, clazz);
124
125         String url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
126         logger.debug(EELFLoggerDelegate.debugLogger, "<== " +  methodName + " sending request to url= " + url);
127
128         MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
129         loggingService.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
130         final Response cres = client.target(url)
131                 .request()
132                 .accept(APPLICATION_JSON)
133                 .headers(commonHeaders)
134                 .get();
135         loggingService.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres);
136         final RestObject<T> restObject = cresToRestObject(cres, clazz);
137         int status = cres.getStatus();
138
139         if (status == 200 || status == 202) {
140             logger.debug(EELFLoggerDelegate.debugLogger, methodName + REST_API_SUCCESSFULL_LOG);
141         } else {
142             logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_STATUS +status+ URL_LOG +url);
143         }
144
145         logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status );
146
147         return restObject;
148     }
149
150     public <T> RestObject<T> PostForObject(Object requestDetails, String path, Class<T> clazz) {
151         logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz);
152         return restCall(HttpMethod.POST, clazz, requestDetails, path);
153     }
154
155     public Invocation.Builder prepareClient(String path, String methodName) {
156         MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
157
158         String url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
159         logger.debug(EELFLoggerDelegate.debugLogger,"<== " +  methodName + " sending request to url= " + url);
160         // Change the content length
161         return client.target(url)
162                 .request()
163                 .accept(APPLICATION_JSON)
164                 .headers(commonHeaders);
165     }
166
167     public <T> RestObject<T> restCall(HttpMethod httpMethod, Class<T> tClass, Object payload, String path) {
168         return restCall(httpMethod, tClass, payload, path, Optional.empty());
169     }
170
171
172     /*
173     user id is needed to be pass as X-RequestorID in new MSO flows like Delete instanceGroup
174      */
175     public <T> RestObject<T> restCall(HttpMethod httpMethod, Class<T> tClass, Object payload, String path, Optional<String> userId)  {
176         String methodName = httpMethod.name();
177         String url="";
178
179         try {
180
181             MultivaluedHashMap<String, Object> commonHeaders = initMsoClient();
182             userId.ifPresent(id->commonHeaders.put("X-RequestorID", Collections.singletonList(id)));
183
184             url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path;
185             loggingService.logRequest(outgoingRequestsLogger, httpMethod, url, payload);
186             // Change the content length
187             final Invocation.Builder restBuilder = client.target(url)
188                     .request()
189                     .accept(APPLICATION_JSON)
190                     .headers(commonHeaders)
191                     .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
192                 ;
193
194             Invocation restInvocation = payload==null ?
195                     restBuilder.build(httpMethod.name()) :
196                     restBuilder.build(httpMethod.name(), Entity.entity(payload, MediaType.APPLICATION_JSON));
197             final Response cres = restInvocation.invoke();
198
199             loggingService.logResponse(outgoingRequestsLogger, httpMethod, url, cres);
200             return cresToRestObject(cres, tClass);
201         }
202         catch (Exception e) {
203             logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString());
204             throw e;
205         }
206
207     }
208
209     private <T> RestObject<T> cresToRestObject(Response cres, Class<T> tClass) {
210         RestObject<T> restObject = new RestObject<>();
211
212         String rawEntity = null;
213         try {
214             cres.bufferEntity();
215             rawEntity = cres.readEntity(String.class);
216             restObject.setRaw(rawEntity);
217             T t = JACKSON_OBJECT_MAPPER.readValue(rawEntity, tClass);
218             restObject.set(t);
219         }
220         catch ( Exception e ) {
221             try {
222                 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + " Error reading response entity as " + tClass + ": , e="
223                         + e.getMessage() + ", Entity=" + rawEntity);
224             } catch (Exception e2) {
225                 logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + NO_RESPONSE_ENTITY_LOG
226                         + e.getMessage());
227             }
228         }
229
230         int status = cres.getStatus();
231         restObject.setStatusCode (status);
232
233         return restObject;
234     }
235
236 }