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