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