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