Fixed health check issue
[portal.git] / portal-BE / src / main / java / org / onap / portal / scheduler / SchedulerRestInterface.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  *
39  */
40
41 package org.onap.portal.scheduler;
42
43 import com.google.gson.Gson;
44 import com.google.gson.GsonBuilder;
45 import com.google.gson.JsonDeserializer;
46 import java.util.Collections;
47 import java.util.Date;
48 import javax.security.auth.login.CredentialException;
49 import javax.ws.rs.client.Client;
50 import javax.ws.rs.client.Entity;
51 import javax.ws.rs.core.MediaType;
52 import javax.ws.rs.core.MultivaluedHashMap;
53 import javax.ws.rs.core.Response;
54 import lombok.NoArgsConstructor;
55 import org.apache.commons.codec.binary.Base64;
56 import org.apache.commons.lang.StringUtils;
57 import org.eclipse.jetty.util.security.Password;
58 import org.json.JSONObject;
59 import org.onap.portal.logging.format.EPAppMessagesEnum;
60 import org.onap.portal.logging.logic.EPLogUtil;
61 import org.onap.portal.scheduler.client.HttpBasicClient;
62 import org.onap.portal.scheduler.client.HttpsBasicClient;
63 import org.onap.portal.scheduler.restobjects.GetTimeSlotsRestObject;
64 import org.onap.portal.scheduler.restobjects.RestObject;
65 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
66 import org.springframework.http.HttpStatus;
67 import org.springframework.stereotype.Service;
68 import org.springframework.web.client.HttpClientErrorException;
69
70 @SuppressWarnings("MalformedFormatString")
71 @Service
72 @NoArgsConstructor
73 public class SchedulerRestInterface {
74
75     private static final String APPLICATION_JSON = "application/json";
76     private static final String PASSWORD_IS_EMPTY = "Password is Empty";
77     private static final String HTTP_CLIENT_ERROR = " HttpClientErrorException: Exception For the POST  ."
78         + " MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON";
79
80     private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
81     private static Client client = null;
82     private static Gson gson = null;
83
84     private MultivaluedHashMap<String, Object> commonHeaders;
85
86     private static void init() {
87         logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
88         GsonBuilder builder = new GsonBuilder();
89
90         // Register an adapter to manage the date types as long values
91         builder.registerTypeAdapter(Date.class,
92             (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()));
93
94         gson = builder.create();
95     }
96
97     public void initRestClient() {
98         logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
99
100         init();
101
102         final String username;
103         final String password;
104
105         /* Setting user name based on properties */
106         String retrievedUsername = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
107         if (retrievedUsername.isEmpty()) {
108             username = "";
109         } else {
110             username = retrievedUsername;
111         }
112
113         /* Setting password based on properties */
114         String retrievedPassword = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
115         if (retrievedPassword.isEmpty()) {
116             password = StringUtils.EMPTY;
117         } else {
118             if (retrievedPassword.contains("OBF:")) {
119                 password = Password.deobfuscate(retrievedPassword);
120             } else {
121                 password = retrievedPassword;
122             }
123         }
124         try {
125             if (StringUtils.isBlank(password)) {
126                 throw new CredentialException(PASSWORD_IS_EMPTY);
127             }
128         } catch (Exception ex) {
129             logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex);
130         }
131         String authString = username + ":" + password;
132         byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
133         String authStringEnc = new String(authEncBytes);
134
135         commonHeaders = new MultivaluedHashMap<>();
136         commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
137
138         try {
139             if (!username.isEmpty()) {
140
141                 client = HttpBasicClient.getClient();
142             } else {
143
144                 client = HttpsBasicClient.getClient();
145             }
146         } catch (Exception e) {
147             logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client", e.getMessage());
148
149         }
150         logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
151
152     }
153
154     public <T> void get(String t, String sourceId, String path, GetTimeSlotsRestObject<String> restObject) {
155
156         String methodName = "Get";
157         String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
158
159         logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
160         try {
161             initRestClient();
162
163             final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
164
165             int status = cres.getStatus();
166             restObject.setStatusCode(status);
167
168             if (cres.getEntity() != null) {
169                 try {
170                     String str = (cres).readEntity(String.class);
171                     if (t.getClass().getName().equals(String.class.getName())) {
172                         t = str;
173                     } else {
174                         t = gson.fromJson(str, t.getClass());
175                     }
176
177                 } catch (Exception e) {
178                     EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
179                 }
180             } else {
181                 t = null;
182                 restObject.setT(null);
183             }
184
185             if ("".equals(t)) {
186                 restObject.setT(null);
187             } else {
188                 restObject.setT(t);
189             }
190         } catch (HttpClientErrorException e) {
191             String message = String.format(
192                 HTTP_CLIENT_ERROR, methodName, url);
193             logger.error(EELFLoggerDelegate.errorLogger, message, e);
194             EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
195         } catch (Exception e) {
196             String message = String
197                 .format("Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName,
198                     url);
199
200             logger.error(EELFLoggerDelegate.errorLogger, message, e);
201             EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
202
203             throw e;
204
205         }
206
207     }
208
209     public <T> void post(String t, JSONObject requestDetails, String path, RestObject<String> restObject) {
210
211         String methodName = "Post";
212         String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
213         logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
214
215         try {
216
217             initRestClient();
218
219             // Change the content length
220             final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders)
221                 .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
222
223             if (cres != null && cres.getEntity() != null) {
224
225                 try {
226                     String str = (cres).readEntity(String.class);
227                     if (t.getClass().getName().equals(String.class.getName())) {
228                         t = str;
229
230                     } else {
231                         t = gson.fromJson(str, t.getClass());
232                     }
233
234                 } catch (Exception e) {
235                     EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
236                 }
237                 restObject.setT(t);
238             } else {
239                 restObject.setT(null);
240             }
241
242             int status = cres != null ? cres.getStatus() : 0;
243             restObject.setStatusCode(status);
244
245             if (status >= 200 && status <= 299) {
246                 String message = String.format(" REST api POST was successful!", methodName);
247                 logger.debug(EELFLoggerDelegate.debugLogger, message);
248
249             } else {
250                 String message = String.format(
251                     " FAILED with http status  . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON",
252                     methodName, status, url);
253                 logger.debug(EELFLoggerDelegate.debugLogger, message);
254             }
255
256         } catch (HttpClientErrorException e) {
257             String message = String.format(
258                 HTTP_CLIENT_ERROR, methodName, url);
259             logger.error(EELFLoggerDelegate.errorLogger, message, e);
260             EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
261         } catch (Exception e) {
262             String message = String.format(
263                 HTTP_CLIENT_ERROR, methodName, url);
264             logger.error(EELFLoggerDelegate.errorLogger, message, e);
265             EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
266             throw e;
267         }
268     }
269
270     public <T> void delete(String t, JSONObject requestDetails, String sourceID, String path, RestObject<String> restObject) {
271
272         String methodName = "Delete";
273         String url = "";
274         Response cres;
275
276         try {
277             initRestClient();
278
279             url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
280
281             cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders)
282                 .build("DELETE", Entity.entity(requestDetails, MediaType.APPLICATION_JSON)).invoke();
283
284             int status = cres.getStatus();
285             restObject.setStatusCode(status);
286             if (cres.getEntity() != null) {
287                 t = cres.readEntity(t.getClass());
288                 restObject.setT(t);
289             }
290
291         } catch (HttpClientErrorException e) {
292             logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception For the Delete",
293                 methodName, url, e);
294             EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
295         } catch (Exception e) {
296             logger.error(EELFLoggerDelegate.errorLogger, "Exception For the Delete", methodName, url, e);
297             EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
298             throw e;
299         }
300     }
301 }