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