7a5196ca6e2294e74da76b21897ac7e51cee3aee
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / controller / TicketEventController.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.controller;
21
22 import java.util.Arrays;
23 import java.util.Calendar;
24 import java.util.Date;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Set;
28
29 import javax.servlet.http.HttpServletRequest;
30 import javax.servlet.http.HttpServletResponse;
31
32 import org.openecomp.portalapp.portal.domain.EPUser;
33 import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
34 import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
35 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
36 import org.openecomp.portalapp.portal.service.TicketEventService;
37 import org.openecomp.portalapp.portal.service.UserNotificationService;
38 import org.openecomp.portalapp.portal.transport.EpNotificationItem;
39 import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem;
40 import org.openecomp.portalapp.portal.utils.PortalConstants;
41 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.context.annotation.Configuration;
44 import org.springframework.context.annotation.EnableAspectJAutoProxy;
45 import org.springframework.web.bind.annotation.RequestBody;
46 import org.springframework.web.bind.annotation.RequestMapping;
47 import org.springframework.web.bind.annotation.RequestMethod;
48 import org.springframework.web.bind.annotation.RestController;
49
50 import com.fasterxml.jackson.databind.JsonNode;
51 import com.fasterxml.jackson.databind.ObjectMapper;
52
53 import io.swagger.annotations.ApiOperation;
54
55 /**
56  * Receives messages from the Collaboration Bus (C-BUS) notification and event
57  * brokering tool. Creates notifications for ECOMP Portal users.
58  */
59 @RestController
60 @RequestMapping(PortalConstants.REST_AUX_API)
61 @Configuration
62 @EnableAspectJAutoProxy
63 @EPAuditLog
64 public class TicketEventController implements BasicAuthenticationController {
65
66
67         @Autowired
68         private UserNotificationService userNotificationService;
69         
70         @Autowired
71         private TicketEventService ticketEventService;
72
73         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TicketEventController.class);
74
75         public boolean isAuxRESTfulCall() {
76                 return true;
77         }
78
79         private final ObjectMapper mapper = new ObjectMapper();
80
81
82
83         @ApiOperation(value = "Accepts messages from external ticketing systems and creates notifications for Portal users.", response = PortalRestResponse.class)
84         @RequestMapping(value = { "/ticketevent" }, method = RequestMethod.POST)
85         public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response,
86                         @RequestBody String ticketEventJson) throws Exception {
87
88                 logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson);
89                 PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
90                 try {
91                         JsonNode ticketEventNotif = mapper.readTree(ticketEventJson);
92
93                         // Reject request if required fields are missing.
94                         String error = validateTicketEventMessage(ticketEventNotif);
95                         if (error != null) {
96                                 portalResponse.setStatus(PortalRestStatusEnum.ERROR);
97                                 portalResponse.setMessage(error);
98                                 response.setStatus(400);
99                                 return portalResponse;
100                         }
101
102                         EpNotificationItem epItem = new EpNotificationItem();
103                         epItem.setCreatedDate(new Date());
104                         epItem.setIsForOnlineUsers("Y");
105                         epItem.setIsForAllRoles("N");
106                         epItem.setActiveYn("Y");
107
108                         JsonNode event = ticketEventNotif.get("event");
109                         JsonNode header = event.get("header");
110                         JsonNode body = event.get("body");
111                         JsonNode application = ticketEventNotif.get("application");
112                         epItem.setMsgDescription(body.toString());
113                         Long eventDate = System.currentTimeMillis();
114                         if (body.get("eventDate") != null) {
115                                 eventDate = body.get("eventDate").asLong();
116                         }
117                         String eventSource = header.get("eventSource").asText();
118                         epItem.setMsgSource(eventSource);
119                         String ticket = body.get("ticketNum").asText();
120                         String hyperlink = ticketEventService.getNotificationHyperLink(application, ticket, eventSource);                       
121                         if(body.get("notificationHyperlink")!=null){
122                                 hyperlink=body.get("notificationHyperlink").asText();
123                         }
124                         epItem.setNotificationHyperlink(hyperlink);
125                         epItem.setStartTime(new Date(eventDate));
126                         Calendar calendar = Calendar.getInstance();
127                         calendar.setTime(epItem.getStartTime());
128                         int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
129                         calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth + 30);
130                         epItem.setEndTime(calendar.getTime());
131                         String severityString = "1";
132                         if (body.get("severity") != null) {
133                                 severityString = (body.get("severity").toString()).substring(1, 2);
134                         }
135                         Long severity = Long.parseLong(severityString);
136                         epItem.setPriority(severity);
137                         epItem.setCreatorId(null);
138                         Set<EpRoleNotificationItem> roles = new HashSet<>();
139                         JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
140                         JsonNode userList = SubscriberInfo.get("UserList");
141                         String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
142                                         .split(",");
143                         String assetID = eventSource + ' '
144                                         + userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + ' '
145                                         + new Date(eventDate);
146                         if (body.get("assetID") != null) {
147                                 assetID = body.get("assetID").asText();
148                         }
149                         epItem.setMsgHeader(assetID);
150                         List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds));
151                         for (String userId : UserIds) {
152                                 EpRoleNotificationItem roleNotifItem = new EpRoleNotificationItem();
153                                 for (EPUser user : users) {
154                                         if (user.getOrgUserId().equals(userId)) {
155                                                 roleNotifItem.setRecvUserId(user.getId().intValue());
156                                                 roles.add(roleNotifItem);
157                                                 break;
158                                         }
159                                 }
160
161                         }
162                         epItem.setRoles(roles);
163                         userNotificationService.saveNotification(epItem);
164
165                         portalResponse.setStatus(PortalRestStatusEnum.OK);
166                         portalResponse.setMessage("processEventNotification: notification created");
167                         portalResponse.setResponse("NotificationId is :" + epItem.notificationId);
168                 } catch (Exception ex) {
169                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
170                         response.setStatus(400);
171                         portalResponse.setMessage(ex.toString());
172                 }
173                 return portalResponse;
174         }
175
176         /**
177          * Validates that mandatory fields are present.
178          * 
179          * @param ticketEventNotif
180          * @return Error message if a problem is found; null if all is well.
181          */
182         private String validateTicketEventMessage(JsonNode ticketEventNotif) {
183                 JsonNode application = ticketEventNotif.get("application");
184                 JsonNode event = ticketEventNotif.get("event");
185                 JsonNode header = event.get("header");
186                 JsonNode eventSource=header.get("eventSource");
187                 JsonNode body = event.get("body");
188                 JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
189                 JsonNode userList = SubscriberInfo.get("UserList");
190
191                 if (application == null||application.asText().length()==0||application.asText().equalsIgnoreCase("null"))
192                         return "Application is mandatory";
193                 if (body == null)
194                         return "body is mandatory";
195                 if (eventSource == null||eventSource.asText().trim().length()==0||eventSource.asText().equalsIgnoreCase("null"))
196                         return "Message Source is mandatory";
197                 if (userList == null)
198                         return "At least one user Id is mandatory";
199                 JsonNode eventDate=body.get("eventDate");
200                 
201                 if(eventDate!=null&&eventDate.asText().length()==8)
202                         return "EventDate is invalid";
203                 String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
204                                 .split(",");            
205                 List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds));
206                 if(users==null||users.size()==0)
207                         return "Invalid Org User ID";
208                 return null;
209         }
210         
211 }