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