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