Merge "Fix sql injection vulnerability"
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / scheduleraux / SchedulerAuxRestInterface.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 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 package org.onap.portalapp.portal.scheduleraux;
41
42 import com.fasterxml.jackson.databind.ObjectMapper;
43 import com.google.gson.Gson;
44 import com.google.gson.GsonBuilder;
45 import com.google.gson.JsonDeserializationContext;
46 import com.google.gson.JsonDeserializer;
47 import com.google.gson.JsonElement;
48 import com.google.gson.JsonParseException;
49 import org.apache.commons.codec.binary.Base64;
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.SchedulerProperties;
56 import org.onap.portalapp.portal.scheduler.client.HttpBasicClient;
57 import org.onap.portalapp.portal.scheduler.policy.rest.RequestDetails;
58 import org.onap.portalapp.util.DateUtil;
59 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
60 import org.springframework.http.HttpStatus;
61 import org.springframework.web.client.HttpClientErrorException;
62
63 import javax.ws.rs.client.Client;
64 import javax.ws.rs.client.Entity;
65 import javax.ws.rs.core.MediaType;
66 import javax.ws.rs.core.MultivaluedHashMap;
67 import javax.ws.rs.core.Response;
68 import java.lang.reflect.Type;
69 import java.text.SimpleDateFormat;
70 import java.util.Collections;
71 import java.util.Date;
72
73 public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements SchedulerAuxRestInterfaceIfc {
74
75         /** The logger. */
76         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class);
77
78         /** The client. */
79         private static Client client = null;
80
81         /** The common headers. */
82         private MultivaluedHashMap<String, Object> commonHeaders;
83
84         public SchedulerAuxRestInterface() {
85                 super();
86         }
87
88         Gson gson = null;
89
90         private final ObjectMapper mapper = new ObjectMapper();
91
92         private void init() {
93                 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
94                 GsonBuilder builder = new GsonBuilder();
95
96                 // Register an adapter to manage the date types as long values
97                 builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
98                         public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
99                                         throws JsonParseException {
100                                 return new Date(json.getAsJsonPrimitive().getAsLong());
101                         }
102                 });
103
104                 gson = builder.create();
105         }
106         
107         public void initRestClient() {
108                 init();
109                 final String methodname = "initRestClient()";
110                 final String mechId = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_CLIENT_MECHID_VAL);
111                 final String clientPassword = SchedulerProperties
112                                 .getProperty(SchedulerProperties.SCHEDULERAUX_CLIENT_PASSWORD_VAL);
113                 final String username = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_USERNAME_VAL);
114                 final String password = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_PASSWORD_VAL);
115                 final String environment = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_ENVIRONMENT_VAL);
116                 final String clientAuth = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_CLIENTAUTH_VAL);
117                 final String decrypted_client_password = Password.deobfuscate(clientPassword);
118                 String mechAuthString = mechId + ":" + decrypted_client_password;
119                 byte[] mechAuthEncBytes = Base64.encodeBase64(mechAuthString.getBytes());
120                 final String decrypted_password = Password.deobfuscate(password);
121                 String authString = username + ":" + decrypted_password;
122                 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
123                 String authorization = new String(authEncBytes);
124
125                 commonHeaders = new MultivaluedHashMap<String, Object>();
126                 commonHeaders.put("ClientAuth", Collections.singletonList((Object) ("Basic " + clientAuth)));
127                 commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authorization)));
128                 commonHeaders.put("Environment", Collections.singletonList((Object) (environment)));
129
130                 if (client == null) {
131
132                         try {
133                                 client = HttpBasicClient.getClient();
134                         } catch (Exception e) {
135                                 logger.debug(EELFLoggerDelegate.debugLogger, " Unable to get the SSL client", methodname);
136
137                         }
138                 }
139         }
140
141         @SuppressWarnings("unchecked")
142         public <T> void Get(T t, String sourceId, String path, RestObject<T> restObject) throws Exception {
143                 String methodName = "Get";
144
145                 logger.debug(EELFLoggerDelegate.debugLogger, " start", methodName);
146                 SimpleDateFormat dateFormat = DateUtil.getDateFormat();
147
148                 String url = "";
149                 restObject.set(t);
150
151                 url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
152                 logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url: ", dateFormat.format(new Date()),
153                                 methodName, url);
154
155                 initRestClient();
156
157                 final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders).get();
158
159                 int status = cres.getStatus();
160                 restObject.setStatusCode(status);
161
162                 if (status == 200) {
163                         t = (T) cres.readEntity(t.getClass());
164                         restObject.set(t);
165                         logger.debug(EELFLoggerDelegate.debugLogger, " REST api was successfull!",
166                                 dateFormat.format(new Date()), methodName);
167
168                 } else {
169                         throw new Exception(methodName + " with status=" + status + ", url= " + url);
170                 }
171
172                 logger.debug(EELFLoggerDelegate.debugLogger, " received status", methodName, status);
173
174                 return;
175         }
176
177         @SuppressWarnings("unchecked")
178         public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) {
179
180                 String methodName = "Delete";
181                 String url = "";
182                 Response cres = null;
183                 SimpleDateFormat dateFormat = DateUtil.getDateFormat();
184
185                 logRequest(r);
186
187                 try {
188                         initRestClient();
189
190                         url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
191                         logger.debug(EELFLoggerDelegate.debugLogger, " methodName sending request to: ",
192                                 dateFormat.format(new Date()), url, methodName);
193
194                         cres = client.target(url).request().accept("application/json").headers(commonHeaders)
195                                         // .entity(r)
196                                         .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke();
197                         // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON));
198                         // .delete(Entity.entity(r, MediaType.APPLICATION_JSON));
199
200                         int status = cres.getStatus();
201                         restObject.setStatusCode(status);
202
203                         if (status == 404) { // resource not found
204                                 String msg = "Resource does not exist...: " + cres.getStatus();
205                                 logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg);
206                         } else if (status == 200 || status == 204) {
207                                 logger.debug(EELFLoggerDelegate.debugLogger, "Resource--deleted:url", dateFormat.format(new Date()),
208                                                 url);
209                         } else if (status == 202) {
210                                 String msg = "Delete in progress: " + status;
211                                 logger.debug(EELFLoggerDelegate.debugLogger, "msg ", dateFormat.format(new Date()), msg);
212                         } else {
213                                 String msg = "Deleting Resource failed: " + status;
214                                 logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg);
215                         }
216
217                         try {
218                                 t = (T) cres.readEntity(t.getClass());
219                                 restObject.set(t);
220                         } catch (HttpClientErrorException e) {
221                                 logger.error(EELFLoggerDelegate.errorLogger,
222                                                 " HttpClientErrorException:No response entity, this is probably ok, e=", methodName, e);
223                                 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
224                         } catch (Exception e) {
225                                 logger.error(EELFLoggerDelegate.errorLogger, "No response entity, this is probably ok, e=", methodName,
226                                                 e);
227                                 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
228
229                         }
230
231                 } catch (HttpClientErrorException e) {
232                         logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception with the URL", methodName,
233                                         url, e);
234                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
235                 } catch (Exception e) {
236                         logger.error(EELFLoggerDelegate.errorLogger, "Exception with the URL ",
237                                 dateFormat.format(new Date()), methodName, url, e);
238                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
239
240                         throw e;
241
242                 }
243         }
244
245         @SuppressWarnings("unchecked")
246         public <T> void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject)
247                         throws HttpClientErrorException, Exception {
248
249                 String methodName = "Post";
250                 String url = "";
251                 Response cres = null;
252                 logger.debug(EELFLoggerDelegate.debugLogger, "POST policy rest interface");
253                 // logRequest (requestDetails);
254                 try {
255
256                         initRestClient();
257
258                         url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
259                         logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url= ", methodName, url);
260                         // Change the content length
261
262                         cres = client.target(url).request().accept("application/json").headers(commonHeaders)
263                                         // .header("content-length", 201)
264                                         // .header("X-FromAppId", sourceID)
265                                         .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
266
267                         /* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code, 
268                         but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which 
269                         doesn't work as expected. Created Portal-253 for tracking */
270                         String str = ((ResponseImpl)cres).readEntity(String.class);
271                         
272                         try {
273                                 if(t.getClass().getName().equals(String.class.getName())){
274                                         t=(T) str;
275                                         
276                                 }else{
277                                         t = (T) gson.fromJson(str, t.getClass());
278                                 }
279                                 
280                         } catch (Exception e) {
281                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
282                         }
283                         
284                         //t = (T) cres.readEntity(t.getClass());
285                         if (t.equals("")) {
286                                 restObject.set(null);
287                         } else {
288                                 restObject.set(t);
289                         }
290
291                         int status = cres.getStatus();
292
293                         restObject.setStatusCode(status);
294
295                         if (status >= 200 && status <= 299) {
296                                 logger.debug(EELFLoggerDelegate.debugLogger, " REST api POST was successful!", methodName);
297
298                         } else {
299                                 logger.debug(EELFLoggerDelegate.debugLogger, "methodname with Status and URL", methodName, status, url);
300                         }
301
302                 } catch (HttpClientErrorException e) {
303                         String message = String.format(
304                                         " HttpClientErrorException:Exception with the URL . MethodName: %s, Url: %s", methodName,url);
305                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
306                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
307                 } catch (Exception e) {
308                         String message = String.format(
309                                         " Exception with the URL . MethodName: %s, Url: %s", methodName,url);
310                         logger.error(EELFLoggerDelegate.errorLogger, message, e);                       
311                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.BAD_REQUEST.value());
312                         throw e;
313
314                 }
315         }
316
317         public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
318                 return clazz.newInstance();
319         }
320
321         @Override
322         public void logRequest(RequestDetails r) {
323                 // TODO Auto-generated method stub
324         }
325 }