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