Password Encrypted in portal schedular.prop
[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.onap.portalsdk.core.onboarding.exception.CipherUtilException;
58 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
59 import org.onap.portalsdk.core.onboarding.util.KeyConstants;
60 import org.onap.portalsdk.core.onboarding.util.KeyProperties;
61 import org.springframework.http.HttpStatus;
62 import org.springframework.stereotype.Service;
63 import org.springframework.web.client.HttpClientErrorException;
64
65 import com.google.gson.Gson;
66 import com.google.gson.GsonBuilder;
67 import com.google.gson.JsonDeserializer;
68
69 import lombok.NoArgsConstructor;
70
71 @SuppressWarnings("MalformedFormatString")
72 @Service
73 @NoArgsConstructor
74 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
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 WebClient client = null;
82         private static Gson gson = null;
83
84         private MultivaluedHashMap<String, String> 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(String URI) {
98                 logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
99
100                 init();
101
102                 final String username;
103                 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
119                         try {
120                                 password = CipherUtil.decryptPKC(retrievedPassword,
121                                                 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
122                         } catch (CipherUtilException e) {
123                                 logger.error(EELFLoggerDelegate.errorLogger, "failed to decrypt; Using as is", e);
124                                 password = retrievedPassword;
125                         }
126
127                 }
128                 try {
129                         if (StringUtils.isBlank(password)) {
130                                 throw new CredentialException(PASSWORD_IS_EMPTY);
131                         }
132                 } catch (Exception ex) {
133                         logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex);
134                 }
135                 String authString = username + ":" + password;
136                 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
137                 String authStringEnc = new String(authEncBytes);
138
139                 commonHeaders = new MultivaluedHashMap<>();
140                 commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
141
142                 // try {
143                 // if (!username.isEmpty()) {
144                 //
145                 // client = HttpBasicClient.getClient();
146                 // } else {
147                 //
148                 // client = HttpsBasicClient.getClient();
149                 // }
150                 // } catch (Exception e) {
151                 // logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest
152                 // client",e.getMessage());
153                 //
154                 // }
155
156                 client = WebClient.create(URI);
157                 client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
158                 // client.path("");
159                 client.headers(commonHeaders);
160
161                 logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
162
163         }
164         
165         @SuppressWarnings("unchecked")
166         public <T> void Get(T t, String sourceId, String path,
167                         org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) {
168
169                 String methodName = "Get";
170                 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
171
172                 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
173                 try {
174                         initRestClient(url);
175
176                         // final Response cres =
177                         // client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
178                         final ResponseImpl cres = (ResponseImpl) client.get();
179
180                         logger.debug(EELFLoggerDelegate.debugLogger, "The implemenation class of Response : ",
181                                         cres.getClass().getName());
182                         int status = cres.getStatus();
183                         restObject.setStatusCode(status);
184
185                         if (cres.getEntity() != null) {
186                                 try {
187                                         String str = (cres).readEntity(String.class);
188                                         if (t.getClass().isAssignableFrom(String.class)) {
189                                                 t = (T) str;
190
191                                         } else {
192                                                 t = (T) gson.fromJson(str, t.getClass());
193                                         }
194
195                                 } catch (Exception e) {
196                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
197                                 }
198                         } else {
199                                 t = null;
200                                 restObject.set(null);
201                         }
202
203                         if ("".equals(t)) {
204                                 restObject.set(null);
205                         } else {
206                                 restObject.set(t);
207                         }
208                 } catch (HttpClientErrorException e) {
209                         String message = String.format(HTTP_CLIENT_ERROR, methodName, url);
210                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
211                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
212                 } catch (Exception e) {
213                         String message = String.format(
214                                         "Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName, url);
215
216                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
217                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
218
219                         throw e;
220
221                 }
222
223         }
224
225         @SuppressWarnings("unchecked")
226         public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) {
227
228                 String methodName = "Post";
229                 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
230                 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
231
232                 try {
233
234                         initRestClient(url);
235
236                         // Change the content length
237                         final ResponseImpl cres = (ResponseImpl) client.post(requestDetails.toJSONString());
238
239                         if (cres != null && cres.getEntity() != null) {
240
241                                 try {
242                                         String str = (cres).readEntity(String.class);
243                                         if (t.getClass().isAssignableFrom(String.class)) {
244                                                 t = (T) str;
245
246                                         } else {
247                                                 t = (T) gson.fromJson(str, t.getClass());
248                                         }
249
250                                 } catch (Exception e) {
251                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
252                                 }
253                                 restObject.set(t);
254                         } else {
255                                 restObject.set(null);
256                         }
257
258                         int status = cres != null ? cres.getStatus() : 0;
259                         restObject.setStatusCode(status);
260
261                         if (status >= 200 && status <= 299) {
262                                 String message = String.format(" REST api POST was successful!", methodName);
263                                 logger.debug(EELFLoggerDelegate.debugLogger, message);
264
265                         } else {
266                                 String message = String.format(
267                                                 " FAILED with http status  . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON",
268                                                 methodName, status, url);
269                                 logger.debug(EELFLoggerDelegate.debugLogger, message);
270                         }
271
272                 } catch (HttpClientErrorException e) {
273                         String message = String.format(HTTP_CLIENT_ERROR, methodName, url);
274                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
275                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
276                 } catch (Exception e) {
277                         String message = String.format(HTTP_CLIENT_ERROR, methodName, url);
278                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
279                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
280                         throw e;
281                 }
282         }
283
284         @Override
285         public void logRequest(JSONObject requestDetails) {
286                 throw new UnsupportedOperationException();
287         }
288
289 }