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