Deliver centralized role management feature
[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.UserNotificationService;
37 import org.openecomp.portalapp.portal.transport.EpNotificationItem;
38 import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem;
39 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
40 import org.openecomp.portalapp.portal.utils.PortalConstants;
41 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
42 import org.openecomp.portalsdk.core.util.SystemProperties;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.context.annotation.Configuration;
45 import org.springframework.context.annotation.EnableAspectJAutoProxy;
46 import org.springframework.web.bind.annotation.RequestBody;
47 import org.springframework.web.bind.annotation.RequestMapping;
48 import org.springframework.web.bind.annotation.RequestMethod;
49 import org.springframework.web.bind.annotation.RestController;
50
51 import com.fasterxml.jackson.databind.JsonNode;
52 import com.fasterxml.jackson.databind.ObjectMapper;
53
54 import io.swagger.annotations.ApiOperation;
55
56 /**
57  * Receives messages from the Collaboration Bus (C-BUS) notification and event
58  * brokering tool. Creates notifications for ECOMP Portal users.
59  */
60 @RestController
61 @RequestMapping(PortalConstants.REST_AUX_API)
62 @Configuration
63 @EnableAspectJAutoProxy
64 @EPAuditLog
65 public class TicketEventController implements BasicAuthenticationController {
66
67
68         @Autowired
69         private UserNotificationService userNotificationService;
70
71         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TicketEventController.class);
72
73         public boolean isAuxRESTfulCall() {
74                 return true;
75         }
76
77         private final ObjectMapper mapper = new ObjectMapper();
78
79
80
81         @ApiOperation(value = "Accepts messages from external ticketing systems and creates notifications for Portal users.", response = PortalRestResponse.class)
82         @RequestMapping(value = { "/ticketevent" }, method = RequestMethod.POST)
83         public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response,
84                         @RequestBody String ticketEventJson) throws Exception {
85
86                 logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson);
87                 PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
88                 try {
89                         JsonNode ticketEventNotif = mapper.readTree(ticketEventJson);
90
91                         // Reject request if required fields are missing.
92                         String error = validateTicketEventMessage(ticketEventNotif);
93                         if (error != null) {
94                                 portalResponse.setStatus(PortalRestStatusEnum.ERROR);
95                                 portalResponse.setMessage(error);
96                                 response.setStatus(400);
97                                 return portalResponse;
98                         }
99
100                         EpNotificationItem epItem = new EpNotificationItem();
101                         epItem.setCreatedDate(new Date());
102                         epItem.setIsForOnlineUsers("Y");
103                         epItem.setIsForAllRoles("N");
104                         epItem.setActiveYn("Y");
105
106                         JsonNode event = ticketEventNotif.get("event");
107                         JsonNode header = event.get("header");
108                         JsonNode body = event.get("body");
109                         epItem.setMsgDescription(body.toString());
110                         Long eventDate = System.currentTimeMillis();
111                         if (body.get("eventDate") != null) {
112                                 eventDate = body.get("eventDate").asLong();
113                         }
114                         String eventSource = header.get("eventSource").asText();
115                         epItem.setMsgSource(eventSource);
116                         String ticket = body.get("ticketNum").asText();
117                         String hyperlink = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_SYSTEM_NOTIFICATION_URL)+eventSource+"num="+ticket;
118                         if(body.get("notificationHyperlink")!=null){
119                                 hyperlink=body.get("notificationHyperlink").asText();
120                         }
121                         epItem.setNotificationHyperlink(hyperlink);
122                         epItem.setStartTime(new Date(eventDate));
123                         Calendar calendar = Calendar.getInstance();
124                         calendar.setTime(epItem.getStartTime());
125                         int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
126                         calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth + 30);
127                         epItem.setEndTime(calendar.getTime());
128                         String severityString = "1";
129                         if (body.get("severity") != null) {
130                                 severityString = (body.get("severity").toString()).substring(1, 2);
131                         }
132                         Long severity = Long.parseLong(severityString);
133                         epItem.setPriority(severity);
134                         epItem.setCreatorId(null);
135                         Set<EpRoleNotificationItem> roles = new HashSet<>();
136                         JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
137                         JsonNode userList = SubscriberInfo.get("UserList");
138                         String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
139                                         .split(",");
140                         String assetID = eventSource + ' '
141                                         + userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + ' '
142                                         + new Date(eventDate);
143                         if (body.get("assetID") != null) {
144                                 assetID = body.get("assetID").asText();
145                         }
146                         epItem.setMsgHeader(assetID);
147                         List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds));
148                         for (String userId : UserIds) {
149                                 EpRoleNotificationItem roleNotifItem = new EpRoleNotificationItem();
150                                 for (EPUser user : users) {
151                                         if (user.getOrgUserId().equals(userId)) {
152                                                 roleNotifItem.setRecvUserId(user.getId().intValue());
153                                                 roles.add(roleNotifItem);
154                                                 break;
155                                         }
156                                 }
157
158                         }
159                         epItem.setRoles(roles);
160                         userNotificationService.saveNotification(epItem);
161
162                         portalResponse.setStatus(PortalRestStatusEnum.OK);
163                         portalResponse.setMessage("processEventNotification: notification created");
164                         portalResponse.setResponse("NotificationId is :" + epItem.notificationId);
165                 } catch (Exception ex) {
166                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
167                         response.setStatus(400);
168                         portalResponse.setMessage(ex.toString());
169                 }
170                 return portalResponse;
171         }
172
173         /**
174          * Validates that mandatory fields are present.
175          * 
176          * @param ticketEventNotif
177          * @return Error message if a problem is found; null if all is well.
178          */
179         private String validateTicketEventMessage(JsonNode ticketEventNotif) {
180                 JsonNode application = ticketEventNotif.get("application");
181                 JsonNode event = ticketEventNotif.get("event");
182                 JsonNode header = event.get("header");
183                 JsonNode body = event.get("body");
184                 JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
185                 JsonNode userList = SubscriberInfo.get("UserList");
186
187                 if (application == null)
188                         return "Application is mandatory";
189                 if (body == null)
190                         return "body is mandatory";
191                 if (header.get("eventSource") == null)
192                         return "Message Source is mandatory";
193                 if (userList == null)
194                         return "At least one user Id is mandatory";
195                 JsonNode eventDate=body.get("eventDate");
196                 
197                 if(eventDate!=null&&eventDate.asText().length()==8)
198                         return "EventDate is invalid";
199                 String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
200                                 .split(",");            
201                 List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds));
202                 if(users==null||users.size()==0)
203                         return "Invalid Attuid";
204                 return null;
205         }
206         
207 }