cb7c0d44d81ba7fe77264c842b36d543357580a9
[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 : \n ", scheduler_request);
103                         String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_GET_TIME_SLOTS)
104                                         + scheduler_request;
105
106                         GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(scheduler_request, path, scheduler_request);
107
108                         Date endTime = new Date();
109                         String endTimeRequest = requestDateFormat.format(endTime);
110                         logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - GET for EndTimeRequest",
111                                         endTimeRequest);
112                         return (new ResponseEntity<String>(schedulerResWrapper.getResponse(),
113                                         HttpStatus.valueOf(schedulerResWrapper.getStatus())));
114                 } catch (Exception e) {
115                         GetTimeSlotsWrapper schedulerResWrapper=new GetTimeSlotsWrapper();
116                         schedulerResWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
117                         schedulerResWrapper.setEntity(e.getMessage());
118                         logger.error(EELFLoggerDelegate.errorLogger, "Exception with getTimeslots", e);
119                         return (new ResponseEntity<String>(schedulerResWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
120                 }
121
122         }
123
124         protected GetTimeSlotsWrapper getTimeSlots(String request, String path, String uuid) throws Exception {
125
126                 try {
127                         // STARTING REST API CALL AS AN FACTORY INSTACE
128                         logger.debug(EELFLoggerDelegate.debugLogger, "Get Time Slots Request START");
129
130                         GetTimeSlotsRestObject<String> restObjStr = new GetTimeSlotsRestObject<String>();
131                         String str = new String();
132
133                         restObjStr.set(str);
134
135                         schedulerRestController.Get(str, uuid, path, restObjStr);
136                         GetTimeSlotsWrapper schedulerRespWrapper = SchedulerUtil.getTimeSlotsWrapResponse(restObjStr);
137                         logger.debug(EELFLoggerDelegate.debugLogger, "Get Time Slots Request END : Response: ",
138                                         schedulerRespWrapper.getResponse());
139                         if (schedulerRespWrapper.getStatus() != 200 && schedulerRespWrapper.getStatus() != 204
140                                         && schedulerRespWrapper.getStatus() != 202) {
141                                 String message = String.format(
142                                                 " getTimeslots Information failed . SchedulerResponseWrapper for gettimeslots: %s", schedulerRespWrapper.getResponse());
143                                 logger.error(EELFLoggerDelegate.errorLogger, message);
144                                 EPLogUtil.schedulerAccessAlarm(logger, schedulerRespWrapper.getStatus());
145
146                         }
147                         return schedulerRespWrapper;
148
149                 } catch (Exception e) {
150                         logger.error(EELFLoggerDelegate.errorLogger,  "Get Time Slots Request ERROR : Exception:",e);
151                         throw e;
152                 }
153         }
154
155         @SuppressWarnings("unchecked")
156         @RequestMapping(value = "/post_create_new_vnf_change", method = RequestMethod.POST, produces = "application/json")
157         public ResponseEntity<String> postCreateNewVNFChange(HttpServletRequest request,
158                         @RequestBody JSONObject scheduler_request) throws Exception {
159                 try {
160                         Date startingTime = new Date();
161                         String startTimeRequest = requestDateFormat.format(startingTime);
162
163                         logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler POST : post_create_new_vnf_change",
164                                         startTimeRequest);
165
166                         // Generating uuid
167                         String uuid = UUID.randomUUID().toString();
168
169                         scheduler_request.put("scheduleId", uuid);
170                         logger.debug(EELFLoggerDelegate.debugLogger, "UUID : ", uuid);
171
172                         // adding uuid to the request payload
173                         scheduler_request.put("scheduleId", uuid);
174                         logger.debug(EELFLoggerDelegate.debugLogger, "Original Request ", scheduler_request.toString());
175
176                         String path = SchedulerProperties
177                                         .getProperty(SchedulerProperties.SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL) + uuid;
178
179                         PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(scheduler_request, path, uuid);
180
181                         Date endTime = new Date();
182                         String endTimeRequest = requestDateFormat.format(endTime);
183                         logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - POST", endTimeRequest);
184
185                         return new ResponseEntity<String>(responseWrapper.getResponse(),
186                                         HttpStatus.valueOf(responseWrapper.getStatus()));
187                 } catch (Exception e) {
188                         PostCreateNewVnfWrapper responseWrapper=new PostCreateNewVnfWrapper();
189                         responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
190                         responseWrapper.setEntity(e.getMessage());
191                         logger.error(EELFLoggerDelegate.errorLogger, "Exception with postCreateNewVNFChange ", e);
192                         return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
193
194                 }
195
196         }
197
198         protected PostCreateNewVnfWrapper postSchedulingRequest(JSONObject request, String path, String uuid)
199                         throws Exception {
200
201                 try {
202                         // STARTING REST API CALL AS AN FACTORY INSTACE
203
204                         PostCreateNewVnfRestObject<String> restObjStr = new PostCreateNewVnfRestObject<String>();
205                         String str = new String();
206
207                         restObjStr.set(str);
208                         schedulerRestController.<String>Post(str, request, path, restObjStr);
209
210                         int status = restObjStr.getStatusCode();
211                         if (status >= 200 && status <= 299) {
212                                 restObjStr.setUUID(uuid);
213                         }
214
215                         PostCreateNewVnfWrapper responseWrapper = SchedulerUtil.postCreateNewVnfWrapResponse(restObjStr);
216
217                         logger.debug(EELFLoggerDelegate.debugLogger, " Post Create New Vnf Scheduling Request END : Response: ",
218                                         responseWrapper.getResponse());
219                         if (responseWrapper.getStatus() != 200 && responseWrapper.getStatus() != 202 && responseWrapper.getStatus() != 204) {
220                                 logger.error(EELFLoggerDelegate.errorLogger, "PostCreateNewVnfWrapper Information failed", responseWrapper.getResponse());
221                                 EPLogUtil.schedulerAccessAlarm(logger, responseWrapper.getStatus());
222
223                         }
224                         return responseWrapper;
225
226                 } catch (Exception e) {
227                         logger.error(EELFLoggerDelegate.errorLogger, "PostCreateNewVnfWrapper failed . Post Create New Vnf Scheduling Request ERROR :",e);
228                         throw e;
229                 }
230         }
231
232         @RequestMapping(value = "/submit_vnf_change_timeslots", method = RequestMethod.POST, produces = "application/json")
233         public ResponseEntity<String> postSubmitVnfChangeTimeslots(HttpServletRequest request,
234                         @RequestBody JSONObject scheduler_request) throws Exception {
235                 try {
236                         Date startingTime = new Date();
237                         String startTimeRequest = requestDateFormat.format(startingTime);
238                         logger.debug(EELFLoggerDelegate.debugLogger, " Controller Scheduler POST : submit_vnf_change_timeslots",
239                                         startTimeRequest);
240
241                         // Generating uuid
242                         String uuid = (String) scheduler_request.get("scheduleId");
243                         logger.debug(EELFLoggerDelegate.debugLogger, "UUID : ", uuid);
244
245                         scheduler_request.remove("scheduleId");
246                         logger.debug(EELFLoggerDelegate.debugLogger, "Original Request for the schedulerId: ",
247                                         scheduler_request.toString());
248
249                         String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)
250                                         .replace("{scheduleId}", uuid);
251
252                         PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = postSubmitSchedulingRequest(scheduler_request, path,
253                                         uuid);
254
255                         Date endTime = new Date();
256                         String endTimeRequest = requestDateFormat.format(endTime);
257                         logger.debug(EELFLoggerDelegate.debugLogger, " Controller Scheduler - POST Submit for end time request",
258                                         endTimeRequest);
259
260                         return (new ResponseEntity<String>(responseWrapper.getResponse(),HttpStatus.valueOf(responseWrapper.getStatus())));
261                 } catch (Exception e) {
262                         PostSubmitVnfChangeTimeSlotsWrapper responseWrapper=new PostSubmitVnfChangeTimeSlotsWrapper();
263                         responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
264                         responseWrapper.setEntity(e.getMessage());
265                         logger.error(EELFLoggerDelegate.errorLogger, "Exception with Post submit Vnf change Timeslots", e);
266                         return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR));
267
268                 }
269         }
270
271         protected PostSubmitVnfChangeTimeSlotsWrapper postSubmitSchedulingRequest(JSONObject request, String path,
272                         String uuid) throws Exception {
273
274                 try {
275                         // STARTING REST API CALL AS AN FACTORY INSTACE
276
277                         PostSubmitVnfChangeRestObject<String> restObjStr = new PostSubmitVnfChangeRestObject<String>();
278                         String str = new String();
279
280                         restObjStr.set(str);
281                         schedulerRestController.<String>Post(str, request, path, restObjStr);
282
283                         int status = restObjStr.getStatusCode();
284                         if (status >= 200 && status <= 299) {
285                                 status=(status==204)?200:status;
286                                 restObjStr.setStatusCode(status);
287                                 restObjStr.setUUID(uuid);
288                         }
289
290                         PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = SchedulerUtil
291                                         .postSubmitNewVnfWrapResponse(restObjStr);
292                         logger.debug(EELFLoggerDelegate.debugLogger, "Post Submit Scheduling Request END : Response = ",
293                                         responseWrapper.getResponse());
294                         if (responseWrapper.getStatus() != 200 && responseWrapper.getStatus() != 202
295                                         && responseWrapper.getStatus() != 204) {
296                                 logger.error(EELFLoggerDelegate.errorLogger, "PostCreateNewVnfWrapper Information failed", responseWrapper.getResponse());
297                                 EPLogUtil.schedulerAccessAlarm(logger, responseWrapper.getStatus());
298
299                         }
300                         return responseWrapper;
301
302                 } catch (Exception e) {
303                         logger.error(EELFLoggerDelegate.errorLogger, " PostCreateNewVnfWrapper failed . Post Submit Scheduling Request ERROR :",e);
304                         throw e;
305                 }
306         }
307
308         /**
309          * Get Scheduler UI constant values from properties file
310          * 
311          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
312          */
313         @RequestMapping(value = "/get_scheduler_constant", method = RequestMethod.GET, produces = "application/json")
314         public PortalRestResponse<Map<String, String>> getSchedulerConstant(HttpServletRequest request,
315                         HttpServletResponse response) {
316                 logger.debug(EELFLoggerDelegate.debugLogger, "get scheduler constant");
317
318                 PortalRestResponse<Map<String, String>> portalRestResponse = null;
319                 String errorMsg = " is not defined in property file. Please check the property file and make sure all the schedule constant values are defined";
320                 HashMap<String, String> constantMap = new HashMap<>();
321                 constantMap.put(SchedulerProperties.SCHEDULER_DOMAIN_NAME, "domainName");
322                 constantMap.put(SchedulerProperties.SCHEDULER_SCHEDULE_NAME, "scheduleName");
323                 constantMap.put(SchedulerProperties.SCHEDULER_WORKFLOW_NAME, "workflowName");
324                 constantMap.put(SchedulerProperties.SCHEDULER_CALLBACK_URL, "callbackUrl");
325                 constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_TYPE, "approvalType");
326                 constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_SUBMIT_STATUS, "approvalSubmitStatus");
327                 constantMap.put(SchedulerProperties.SCHEDULER_APPROVAL_REJECT_STATUS, "approvalRejectStatus");
328                 constantMap.put(SchedulerProperties.SCHEDULER_POLICY_NAME, "policyName");
329                 constantMap.put(SchedulerProperties.SCHEDULER_INTERVAL_GET_TIMESLOT_RATE, "intervalRate");
330                 constantMap.put(SchedulerProperties.SCHEDULER_GROUP_ID, "groupId");
331                 try {
332                         Map<String, String> map = new HashMap<>();
333                         for (Map.Entry<String, String> entry : constantMap.entrySet()) {
334                                 if (SchedulerProperties.containsProperty(entry.getKey()))
335                                         map.put(entry.getValue(), SchedulerProperties.getProperty(entry.getKey()));
336                                 else
337                                         throw new Exception(entry.getKey() + errorMsg);
338                         }
339                         portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.OK, "success", map);
340                 } catch (Exception e) {
341                         logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed", e);
342                         portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR, e.getMessage(),
343                                         null);
344                 }
345                 return portalRestResponse;
346         }
347
348 }