Merge "Fix NPE & other issues"
[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 java.util.Collections;
41 import java.util.Date;
42
43 import javax.security.auth.login.CredentialException;
44 import javax.ws.rs.core.MediaType;
45 import javax.ws.rs.core.MultivaluedHashMap;
46
47 import org.apache.commons.codec.binary.Base64;
48 import org.apache.commons.lang.StringUtils;
49 import org.apache.cxf.jaxrs.client.WebClient;
50 import org.apache.cxf.jaxrs.impl.ResponseImpl;
51 import org.eclipse.jetty.util.security.Password;
52 import org.json.simple.JSONObject;
53 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
54 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
55 import org.onap.portalapp.portal.scheduler.restobjects.RestObject;
56 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
57 import org.springframework.http.HttpStatus;
58 import org.springframework.stereotype.Service;
59 import org.springframework.web.client.HttpClientErrorException;
60
61 import com.google.gson.Gson;
62 import com.google.gson.GsonBuilder;
63 import com.google.gson.JsonDeserializer;
64
65 import lombok.NoArgsConstructor;
66
67 @SuppressWarnings("MalformedFormatString")
68 @Service
69 @NoArgsConstructor
70 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
71         private static final String APPLICATION_JSON = "application/json";
72         private static final String PASSWORD_IS_EMPTY = "Password is Empty";
73         private static final String HTTP_CLIENT_ERROR = " HttpClientErrorException: Exception For the POST  ." 
74                                                                                                         + " MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON";
75
76         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
77         private static WebClient client = null;
78         private static Gson gson = null;
79
80         private MultivaluedHashMap<String, String> commonHeaders;
81
82         private static void init() {
83                 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
84                 GsonBuilder builder = new GsonBuilder();
85
86                 // Register an adapter to manage the date types as long values
87                 builder.registerTypeAdapter(Date.class,
88                         (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()));
89
90                 gson = builder.create();
91         }
92
93         public void initRestClient(String URI) {
94                 logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
95
96                 init();
97
98                 final String username;
99                 final String password;
100
101                 /* Setting user name based on properties */
102                 String retrievedUsername = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
103                 if (retrievedUsername.isEmpty()) {
104                         username = "";
105                 } else {
106                         username = retrievedUsername;
107                 }
108
109                 /* Setting password based on properties */
110                 String retrievedPassword = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
111                 if (retrievedPassword.isEmpty()) {
112                         password = StringUtils.EMPTY;
113                 } else {
114                         if (retrievedPassword.contains("OBF:")) {
115                                 password = Password.deobfuscate(retrievedPassword);
116                         } else {
117                                 password = retrievedPassword;
118                         }
119                 }
120                 try {
121                         if (StringUtils.isBlank(password)) {
122                                 throw new CredentialException(PASSWORD_IS_EMPTY);
123                         }
124                 } catch (Exception ex) {
125                         logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex);
126                 }
127                 String authString = username + ":" + password;
128                 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
129                 String authStringEnc = new String(authEncBytes);
130
131                 commonHeaders = new MultivaluedHashMap<>();
132                 commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
133
134                 //              try {
135                 //                      if (!username.isEmpty()) {
136                 //
137                 //                              client = HttpBasicClient.getClient();
138                 //                      } else {
139                 //
140                 //                              client = HttpsBasicClient.getClient();
141                 //                      }
142                 //              } catch (Exception e) {
143                 //                      logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client",e.getMessage());
144                 //
145                 //              }
146                 
147                 client = WebClient.create(URI);
148                 client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
149                 //client.path("");
150                 client.headers(commonHeaders);
151                                 
152                 logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
153                 
154         }
155
156         @SuppressWarnings("unchecked")
157         public <T> void Get(T t, String sourceId, String path,
158                         org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) {
159
160                 String methodName = "Get";
161                 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
162
163                 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
164                 try {
165                         initRestClient(url);
166                         
167                         
168                         //final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
169                         final ResponseImpl cres = (ResponseImpl)client.get();
170
171                         logger.debug(EELFLoggerDelegate.debugLogger, "The implemenation class of Response : ", cres.getClass().getName());
172                         int status = cres.getStatus();
173                         restObject.setStatusCode(status);
174
175                         if (cres.getEntity() != null) {
176                                 try {
177                                         String str = (cres).readEntity(String.class);
178                                         if (t.getClass().isAssignableFrom(String.class)) {
179                                                 t = (T) str;
180
181                                         } else {
182                                                 t = (T) gson.fromJson(str, t.getClass());
183                                         }
184
185                                 } catch (Exception e) {
186                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
187                                 }
188                         } else {
189                                 t = null;
190                                 restObject.set(null);
191                         }
192
193                         if ("".equals(t)) {
194                                 restObject.set(null);
195                         } else {
196                                 restObject.set(t);
197                         }
198                 } catch (HttpClientErrorException e) {
199                         String message = String.format(
200                                         HTTP_CLIENT_ERROR, methodName, url);
201                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
202                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
203                 } catch (Exception e) {
204                         String message = String.format("Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName, url);
205
206                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
207                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
208
209                         throw e;
210
211                 }
212
213         }
214
215         @SuppressWarnings("unchecked")
216         public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) {
217
218                 String methodName = "Post";
219                 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
220                 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
221
222                 try {
223
224                         initRestClient(url);
225
226                         // Change the content length
227                         final ResponseImpl cres = (ResponseImpl)client.post(requestDetails.toJSONString());
228
229                         if (cres != null && cres.getEntity() != null) {
230
231                                 try {
232                                         String str = (cres).readEntity(String.class);
233                                         if (t.getClass().isAssignableFrom(String.class)) {
234                                                 t = (T) str;
235
236                                         } else {
237                                                 t = (T) gson.fromJson(str, t.getClass());
238                                         }
239
240                                 } catch (Exception e) {
241                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
242                                 }
243                                 restObject.set(t);
244                         } else {
245                                 restObject.set(null);
246                         }
247
248                         int status = cres != null ? cres.getStatus() : 0;
249                         restObject.setStatusCode(status);
250
251                         if (status >= 200 && status <= 299) {
252                                 String message = String.format(" REST api POST was successful!", methodName);
253                                 logger.debug(EELFLoggerDelegate.debugLogger, message);
254
255                         } else {
256                                 String message = String.format(" FAILED with http status  . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON",
257                                                 methodName, status, url);
258                                 logger.debug(EELFLoggerDelegate.debugLogger, message);
259                         }
260
261                 } catch (HttpClientErrorException e) {
262                         String message = String.format(
263                                         HTTP_CLIENT_ERROR, methodName, url);
264                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
265                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
266                 } catch (Exception e) {
267                         String message = String.format(
268                                         HTTP_CLIENT_ERROR, methodName, url);
269                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
270                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
271                         throw e;
272                 }
273         }
274
275         @Override
276         public void logRequest(JSONObject requestDetails) {
277                 throw new UnsupportedOperationException();
278         }
279
280
281 }