Merge "Fix sql injection vulnerability"
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / SchedulerController.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.controller;
39
40 import java.text.DateFormat;
41 import java.text.SimpleDateFormat;
42 import java.util.Date;
43 import java.util.HashMap;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Set;
47 import java.util.UUID;
48
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51
52 import org.json.simple.JSONObject;
53 import org.onap.portalapp.controller.EPRestrictedBaseController;
54 import org.onap.portalapp.portal.domain.EPUser;
55 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
56 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
57 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
58 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
59 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
60 import org.onap.portalapp.portal.scheduler.SchedulerProperties;
61 import org.onap.portalapp.portal.scheduler.SchedulerRestInterface;
62 import org.onap.portalapp.portal.scheduler.SchedulerUtil;
63 import org.onap.portalapp.portal.scheduler.restobjects.GetTimeSlotsRestObject;
64 import org.onap.portalapp.portal.scheduler.restobjects.PostCreateNewVnfRestObject;
65 import org.onap.portalapp.portal.scheduler.restobjects.PostSubmitVnfChangeRestObject;
66 import org.onap.portalapp.portal.scheduler.wrapper.GetTimeSlotsWrapper;
67 import org.onap.portalapp.portal.scheduler.wrapper.PostCreateNewVnfWrapper;
68 import org.onap.portalapp.portal.scheduler.wrapper.PostSubmitVnfChangeTimeSlotsWrapper;
69 import org.onap.portalapp.portal.service.AdminRolesService;
70 import org.onap.portalapp.portal.utils.PortalConstants;
71 import org.onap.portalapp.util.EPUserUtils;
72 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
73 import org.onap.portalsdk.core.service.DataAccessService;
74 import org.springframework.beans.factory.annotation.Autowired;
75 import org.springframework.context.annotation.Configuration;
76 import org.springframework.context.annotation.EnableAspectJAutoProxy;
77 import org.springframework.http.HttpStatus;
78 import org.springframework.http.ResponseEntity;
79 import org.springframework.web.bind.annotation.PathVariable;
80 import org.springframework.web.bind.annotation.RequestBody;
81 import org.springframework.web.bind.annotation.RequestMapping;
82 import org.springframework.web.bind.annotation.RequestMethod;
83 import org.springframework.web.bind.annotation.RestController;
84
85 @RestController
86 @RequestMapping(PortalConstants.PORTAL_AUX_API)
87 @Configuration
88 @EnableAspectJAutoProxy
89 @EPAuditLog
90 public class SchedulerController extends EPRestrictedBaseController {
91
92         @Autowired
93         private SchedulerRestInterface schedulerRestController;
94         
95         @Autowired
96         private AdminRolesService adminRolesService;
97
98         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerController.class);
99
100         /** The request date format. */
101         public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z");
102
103         @RequestMapping(value = "/get_time_slots/{scheduler_request}", method = RequestMethod.GET, produces = "application/json")
104         public ResponseEntity<String> getTimeSlots(HttpServletRequest request,
105                         @PathVariable("scheduler_request") String scheduler_request) throws Exception {
106                 if (checkIfUserISValidToMakeSchedule(request)) {
107                         try {
108                                 Date startingTime = new Date();
109                                 String startTimeRequest = requestDateFormat.format(startingTime);
110                                 logger.debug(EELFLoggerDelegate.debugLogger,
111                                                 "Controller Scheduler GET Timeslots for startTimeRequest: ", startTimeRequest);
112                                 logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {} ", scheduler_request);
113
114                                 String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_GET_TIME_SLOTS)
115                                                 + scheduler_request;
116
117                                 GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(scheduler_request, path, scheduler_request);
118
119                                 Date endTime = new Date();
120                                 String endTimeRequest = requestDateFormat.format(endTime);
121                                 logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - GET for EndTimeRequest = {}",
122                                                 endTimeRequest);
123                                 return (new ResponseEntity<String>(schedulerResWrapper.getResponse(),
124                                                 HttpStatus.valueOf(schedulerResWrapper.getStatus())));
125                         } catch (Exception e) {
126                                 GetTimeSlotsWrapper schedulerResWrapper = new GetTimeSlotsWrapper();
127                                 schedulerResWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
128                                 schedulerResWrapper.setEntity(e.getMessage());
129                                 logger.error(EELFLoggerDelegate.errorLogger, "Exception with getTimeslots", e);
130                                 return (new ResponseEntity<String>(schedulerResWrapper.getResponse(),
131                                                 HttpStatus.INTERNAL_SERVER_ERROR));
132                         }
133                 }else{
134                         return (new ResponseEntity<String>("User is unauthorized to make this call", HttpStatus.UNAUTHORIZED));
135                 }
136         }
137
138         protected GetTimeSlotsWrapper getTimeSlots(String request, String path, String uuid) throws Exception {
139
140                 try {
141                         // STARTING REST API CALL AS AN FACTORY INSTACE
142                         logger.debug(EELFLoggerDelegate.debugLogger, "Get Time Slots Request START");
143
144                         GetTimeSlotsRestObject<String> restObjStr = new GetTimeSlotsRestObject<String>();
145                         String str = new String();
146
147                         restObjStr.set(str);
148
149                         schedulerRestController.Get(str, uuid, path, restObjStr);
150                         GetTimeSlotsWrapper schedulerRespWrapper = SchedulerUtil.getTimeSlotsWrapResponse(restObjStr);
151                         logger.debug(EELFLoggerDelegate.debugLogger, "Get Time Slots Request END : Response: {}",
152                                         schedulerRespWrapper.getResponse());
153                         if (schedulerRespWrapper.getStatus() != 200 && schedulerRespWrapper.getStatus() != 204
154                                         && schedulerRespWrapper.getStatus() != 202) {
155                                 String message = String.format(
156                                                 " getTimeslots Information failed . SchedulerResponseWrapper for gettimeslots: {}", schedulerRespWrapper.getResponse());
157                                 logger.error(EELFLoggerDelegate.errorLogger, message);
158                                 EPLogUtil.schedulerAccessAlarm(logger, schedulerRespWrapper.getStatus());
159
160                         }
161                         return schedulerRespWrapper;
162
163                 } catch (Exception e) {
164                         logger.error(EELFLoggerDelegate.errorLogger,  "Get Time Slots Request ERROR : Exception:",e);
165                         throw e;
166                 }
167         }
168
169         @SuppressWarnings("unchecked")
170         @RequestMapping(value = "/post_create_new_vnf_change", method = RequestMethod.POST, produces = "application/json")
171         public ResponseEntity<String> postCreateNewVNFChange(HttpServletRequest request,
172                         @RequestBody JSONObject scheduler_request) throws Exception {
173                 if (checkIfUserISValidToMakeSchedule(request)) {
174                         try {
175                                 Date startingTime = new Date();
176                                 String startTimeRequest = requestDateFormat.format(startingTime);
177
178                                 logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler POST : post_create_new_vnf_change",
179                                                 startTimeRequest);
180
181                                 // Generating uuid
182                                 String uuid = UUID.randomUUID().toString();
183
184                                 scheduler_request.put("scheduleId", uuid);
185                                 logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid);
186
187                                 // adding uuid to the request payload
188                                 scheduler_request.put("scheduleId", uuid);
189                                 logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {}", scheduler_request.toString());
190
191                                 String path = SchedulerProperties
192                                                 .getProperty(SchedulerProperties.SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL) + uuid;
193
194                                 PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(scheduler_request, path, uuid);
195
196                                 Date endTime = new Date();
197                                 String endTimeRequest = requestDateFormat.format(endTime);
198                                 logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - POST= {}", endTimeRequest);
199
200                                 return new ResponseEntity<String>(responseWrapper.getResponse(),
201                                                 HttpStatus.valueOf(responseWrapper.getStatus()));
202                         } catch (Exception e) {
203                                 PostCreateNewVnfWrapper responseWrapper = new PostCreateNewVnfWrapper();
204                                 responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
205                                 responseWrapper.setEntity(e.getMessage());
206                                 logger.error(EELFLoggerDelegate.errorLogger, "Exception with postCreateNewVNFChange ", e);
207                                 return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
208
209                         }
210                 }else{
211                         return (new ResponseEntity<String>("User is unauthorized to make this call",HttpStatus.UNAUTHORIZED));
212                 }
213
214         }
215
216         protected PostCreateNewVnfWrapper postSchedulingRequest(JSONObject request, String path, String uuid)
217                         throws Exception {
218
219                 try {
220                         // STARTING REST API CALL AS AN FACTORY INSTACE
221
222                         PostCreateNewVnfRestObject<String> restObjStr = new PostCreateNewVnfRestObject<String>();
223                         String str = new String();
224
225                         restObjStr.set(str);
226                         schedulerRestController.<String>Post(str, request, path, restObjStr);
227
228                         int status = restObjStr.getStatusCode();
229                         if (status >= 200 && status <= 299) {
230                                 restObjStr.setUUID(uuid);
231                         }
232
233                         PostCreateNewVnfWrapper responseWrapper = SchedulerUtil.postCreateNewVnfWrapResponse(restObjStr);
234
235                         logger.debug(EELFLoggerDelegate.debugLogger, " Post Create New Vnf Scheduling Request END : Response = {}",
236                                         responseWrapper.getResponse());
237                         if (responseWrapper.getStatus() != 200 && responseWrapper.getStatus() != 202 && responseWrapper.getStatus() != 204) {
238                                 logger.error(EELFLoggerDelegate.errorLogger, "PostCreateNewVnfWrapper Information failed", responseWrapper.getResponse());
239                                 EPLogUtil.schedulerAccessAlarm(logger, responseWrapper.getStatus());
240
241                         }
242                         return responseWrapper;
243
244                 } catch (Exception e) {
245                         logger.error(EELFLoggerDelegate.errorLogger, "PostCreateNewVnfWrapper failed . Post Create New Vnf Scheduling Request ERROR :",e);
246                         throw e;
247                 }
248         }
249
250         @RequestMapping(value = "/submit_vnf_change_timeslots", method = RequestMethod.POST, produces = "application/json")
251         public ResponseEntity<String> postSubmitVnfChangeTimeslots(HttpServletRequest request,
252                         @RequestBody JSONObject scheduler_request) throws Exception {
253                 if (checkIfUserISValidToMakeSchedule(request)) {
254                 try {
255                         Date startingTime = new Date();
256                         String startTimeRequest = requestDateFormat.format(startingTime);
257                         logger.debug(EELFLoggerDelegate.debugLogger, " Controller Scheduler POST : submit_vnf_change_timeslots = {}",
258                                         startTimeRequest);
259
260                         // Generating uuid
261                         String uuid = (String) scheduler_request.get("scheduleId");
262                         logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid);
263
264                         scheduler_request.remove("scheduleId");
265                         logger.debug(EELFLoggerDelegate.debugLogger, "Original Request for the schedulerId= {} ",
266                                         scheduler_request.toString());
267
268                         String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)
269                                         .replace("{scheduleId}", uuid);
270
271                         PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = postSubmitSchedulingRequest(scheduler_request, path,
272                                         uuid);
273
274                         Date endTime = new Date();
275                         String endTimeRequest = requestDateFormat.format(endTime);
276                         logger.debug(EELFLoggerDelegate.debugLogger, " Controller Scheduler - POST Submit for end time request= {}",
277                                         endTimeRequest);
278
279                         return (new ResponseEntity<String>(responseWrapper.getResponse(),HttpStatus.valueOf(responseWrapper.getStatus())));
280                         } catch (Exception e) {
281                                 PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = new PostSubmitVnfChangeTimeSlotsWrapper();
282                                 responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
283                                 responseWrapper.setEntity(e.getMessage());
284                                 logger.error(EELFLoggerDelegate.errorLogger, "Exception with Post submit Vnf change Timeslots", e);
285                                 return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
286
287                         }
288                 }else{
289                         return (new ResponseEntity<String>("User is unauthorized to make this call",HttpStatus.UNAUTHORIZED));
290                 }
291         }
292
293         protected PostSubmitVnfChangeTimeSlotsWrapper postSubmitSchedulingRequest(JSONObject request, String path,
294                         String uuid) throws Exception {
295
296                 try {
297                         // STARTING REST API CALL AS AN FACTORY INSTACE
298
299                         PostSubmitVnfChangeRestObject<String> restObjStr = new PostSubmitVnfChangeRestObject<String>();
300                         String str = new String();
301
302                         restObjStr.set(str);
303                         schedulerRestController.<String>Post(str, request, path, restObjStr);
304
305                         int status = restObjStr.getStatusCode();
306                         if (status >= 200 && status <= 299) {
307                                 status=(status==204)?200:status;
308                                 restObjStr.setStatusCode(status);
309                                 restObjStr.setUUID(uuid);
310                         }
311
312                         PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = SchedulerUtil
313                                         .postSubmitNewVnfWrapResponse(restObjStr);
314                         logger.debug(EELFLoggerDelegate.debugLogger, "Post Submit Scheduling Request END : Response = {}",
315                                         responseWrapper.getResponse());
316                         if (responseWrapper.getStatus() != 200 && responseWrapper.getStatus() != 202
317                                         && responseWrapper.getStatus() != 204) {
318                                 logger.error(EELFLoggerDelegate.errorLogger, "PostCreateNewVnfWrapper Information failed", responseWrapper.getResponse());
319                                 EPLogUtil.schedulerAccessAlarm(logger, responseWrapper.getStatus());
320
321                         }
322                         return responseWrapper;
323
324                 } catch (Exception e) {
325                         logger.error(EELFLoggerDelegate.errorLogger, " PostCreateNewVnfWrapper failed . Post Submit Scheduling Request ERROR :",e);
326                         throw e;
327                 }
328         }
329
330         /**
331          * Get Scheduler UI constant values from properties file
332          * 
333          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
334          * @throws Exception 
335          */
336         @RequestMapping(value = "/get_scheduler_constant", method = RequestMethod.GET, produces = "application/json")
337         public PortalRestResponse<Map<String, String>> getSchedulerConstant(HttpServletRequest request,
338                         HttpServletResponse response) throws Exception {
339                 logger.debug(EELFLoggerDelegate.debugLogger, "get scheduler constant");
340
341                 PortalRestResponse<Map<String, String>> portalRestResponse = null;
342
343                 if (checkIfUserISValidToMakeSchedule(request)) {
344                         String errorMsg = " is not defined in property file. Please check the property file and make sure all the schedule constant values are defined";
345                         HashMap<String, String> constantMap = new HashMap<>();
346                         constantMap.put(SchedulerProperties.SCHEDULER_DOMAIN_NAME, "domainName");
347                         constantMap.put(SchedulerProperties.SCHEDULER_SCHEDULE_NAME, "scheduleName");
348                         constantMap.put(SchedulerProperties.SCHEDULER_WORKFLOW_NAME, "workflowName");
349                         constantMap.put(SchedulerProperties.SCHEDULER_CALLBACK_URL, "callbackUrl");
350                         constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_TYPE, "approvalType");
351                         constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_SUBMIT_STATUS, "approvalSubmitStatus");
352                         constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_REJECT_STATUS, "approvalRejectStatus");
353                         constantMap.put(SchedulerProperties.SCHEDULER_POLICY_NAME, "policyName");
354                         constantMap.put(SchedulerProperties.SCHEDULER_INTERVAL_GET_TIMESLOT_RATE, "intervalRate");
355                         constantMap.put(SchedulerProperties.SCHEDULER_GROUP_ID, "groupId");
356                         try {
357                                 Map<String, String> map = new HashMap<>();
358                                 for (Map.Entry<String, String> entry : constantMap.entrySet()) {
359                                         if (SchedulerProperties.containsProperty(entry.getKey()))
360                                                 map.put(entry.getValue(), SchedulerProperties.getProperty(entry.getKey()));
361                                         else
362                                                 throw new Exception(entry.getKey() + errorMsg);
363                                 }
364                                 logger.debug(EELFLoggerDelegate.debugLogger, " portalRestResponse - getSchedulerConstant= {}", map);
365                                 portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.OK, "success",
366                                                 map);
367
368                         } catch (Exception e) {
369                                 logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed", e);
370                                 portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR,
371                                                 e.getMessage(), null);
372                         }
373
374                 }
375         else{
376                         logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed: User unauthorized to make this call");
377                 portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR, "failed : Unauthorized", null);
378         }
379                                 return portalRestResponse;
380         }
381
382         private String getPath(HttpServletRequest request)
383         {
384                 String requestURI = request.getRequestURI();
385                 String portalApiPath = "";
386                 if (requestURI != null) {
387                         String[] uriArray = requestURI.split("/portalApi/");
388                         if (uriArray.length > 1) {
389                                 portalApiPath = uriArray[1];
390                         }
391                 }
392                 return portalApiPath;
393         }
394         
395         private boolean checkIfUserISValidToMakeSchedule(HttpServletRequest request) throws Exception
396         {
397                 EPUser user = EPUserUtils.getUserSession(request);
398                 String portalApiPath = getPath(request);
399                 Set<String> functionCodeList = adminRolesService.getAllAppsFunctionsOfUser(user.getId().toString());
400                 boolean isValidUser =   EPUserUtils.matchRoleFunctions(portalApiPath, functionCodeList);
401 //              boolean isValidUser = functionCodeList.stream().anyMatch(x -> functionCodeList.contains(portalApiPath));
402                 return isValidUser;
403         }
404 }