1e8945b06273ecfa1c361e0aa74a62e4592bd720
[portal.git] / portal-BE / src / main / java / org / onap / 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
39 package org.onap.portal.controller;
40
41 import com.fasterxml.jackson.databind.JsonNode;
42 import com.fasterxml.jackson.databind.ObjectMapper;
43 import io.swagger.annotations.ApiOperation;
44 import java.time.LocalDateTime;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Date;
48 import java.util.HashSet;
49 import java.util.List;
50 import java.util.Set;
51 import javax.servlet.http.HttpServletRequest;
52 import javax.servlet.http.HttpServletResponse;
53 import javax.validation.ConstraintViolation;
54 import javax.validation.Validation;
55 import javax.validation.Validator;
56 import javax.validation.ValidatorFactory;
57 import org.onap.portal.domain.db.ep.EpNotification;
58 import org.onap.portal.domain.db.ep.EpRoleNotification;
59 import org.onap.portal.domain.db.fn.FnUser;
60 import org.onap.portal.domain.dto.PortalRestResponse;
61 import org.onap.portal.domain.dto.PortalRestStatusEnum;
62 import org.onap.portal.logging.aop.EPAuditLog;
63 import org.onap.portal.service.epNotification.EpNotificationService;
64 import org.onap.portal.service.user.FnUserService;
65 import org.onap.portal.utils.EPCommonSystemProperties;
66 import org.onap.portal.utils.PortalConstants;
67 import org.onap.portal.validation.SecureString;
68 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
69 import org.onap.portalsdk.core.util.SystemProperties;
70 import org.springframework.beans.factory.annotation.Autowired;
71 import org.springframework.context.annotation.Configuration;
72 import org.springframework.context.annotation.EnableAspectJAutoProxy;
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.REST_AUX_API)
80 @Configuration
81 @EnableAspectJAutoProxy
82 @EPAuditLog
83 public class TicketEventController {
84
85     private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TicketEventController.class);
86
87     private static final String EVENT_DATE = "eventDate";
88     private final ObjectMapper objectMapper = new ObjectMapper();
89     private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
90
91     private final FnUserService fnUserService;
92     private final EpNotificationService epNotificationService;
93
94     @Autowired
95     public TicketEventController(final FnUserService fnUserService,
96         final EpNotificationService epNotificationService) {
97         this.fnUserService = fnUserService;
98         this.epNotificationService = epNotificationService;
99     }
100
101     @ApiOperation(
102         value = "Accepts messages from external ticketing systems and creates notifications for Portal users.",
103         response = PortalRestResponse.class)
104     @RequestMapping(value = { "/ticketevent" }, method = RequestMethod.POST)
105     public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response,
106         @RequestBody String ticketEventJson) {
107
108         logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson);
109         PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
110
111         if (ticketEventJson != null) {
112             SecureString secureString = new SecureString(ticketEventJson);
113             Validator validator = VALIDATOR_FACTORY.getValidator();
114
115             Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
116             if (!constraintViolations.isEmpty()) {
117                 portalResponse.setStatus(PortalRestStatusEnum.ERROR);
118                 portalResponse.setMessage("Data is not valid");
119                 return portalResponse;
120             }
121         }
122
123         try {
124             JsonNode ticketEventNotif = objectMapper.readTree(ticketEventJson);
125
126             // Reject request if required fields are missing.
127             String error = validateTicketEventMessage(ticketEventNotif);
128             if (error != null) {
129                 portalResponse.setStatus(PortalRestStatusEnum.ERROR);
130                 portalResponse.setMessage(error);
131                 response.setStatus(400);
132                 return portalResponse;
133             }
134
135             EpNotification epItem = new EpNotification();
136             epItem.setCreatedDate(LocalDateTime.now());
137             epItem.setIsForOnlineUsers(true);
138             epItem.setIsForAllRoles(false);
139             epItem.setActiveYn(false);
140
141             JsonNode event = ticketEventNotif.get("event");
142             JsonNode header = event.get("header");
143             JsonNode body = event.get("body");
144             JsonNode application = ticketEventNotif.get("application");
145             epItem.setMsgDescription(body.toString());
146             long eventDate = System.currentTimeMillis();
147             if (body.get(EVENT_DATE) != null) {
148                 eventDate = body.get(EVENT_DATE).asLong();
149             }
150             String eventSource = header.get("eventSource").asText();
151             epItem.setMsgSource(eventSource);
152             String ticket = body.get("ticketNum").asText();
153             String hyperlink = this.getNotificationHyperLink(application, ticket, eventSource);
154             if (body.get("notificationHyperlink") != null) {
155                 hyperlink = body.get("notificationHyperlink").asText();
156             }
157             epItem.setNotificationHyperlink(hyperlink);
158             epItem.setStartTime(LocalDateTime.now());
159             epItem.setEndTime(epItem.getStartTime().plusDays(30));
160             String severityString = "1";
161             if (body.get("severity") != null) {
162                 severityString = (body.get("severity").toString()).substring(1, 2);
163             }
164             Long severity = Long.parseLong(severityString);
165             epItem.setPriority(severity);
166             epItem.setCreatorId(null);
167             JsonNode subscriberInfo = ticketEventNotif.get("SubscriberInfo");
168             JsonNode userList = subscriberInfo.get("UserList");
169             String[] userIds = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
170                 .split(",");
171             String assetID = eventSource + ' '
172                 + userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + ' '
173                 + new Date(eventDate);
174             if (body.get("assetID") != null) {
175                 assetID = body.get("assetID").asText();
176             }
177             epItem.setMsgHeader(assetID);
178             List<FnUser> users = fnUserService.getUsersByOrgIds(new ArrayList<>(Arrays.asList(userIds)));
179             Set<EpRoleNotification> roles = new HashSet<>();
180             for (String userId : userIds) {
181                 EpRoleNotification roleNotifItem = new EpRoleNotification();
182                 for (FnUser user : users) {
183                     if (user.getOrgUserId().equals(userId)) {
184                         roleNotifItem.setRecvUserId(user.getId());
185                         roles.add(roleNotifItem);
186                         break;
187                     }
188                 }
189
190             }
191             epItem.setEpRoleNotifications(roles);
192             epNotificationService.saveNotification(epItem);
193
194             portalResponse.setStatus(PortalRestStatusEnum.OK);
195             portalResponse.setMessage("processEventNotification: notification created");
196             portalResponse.setResponse("NotificationId is :" + epItem.getNotificationId());
197         } catch (Exception ex) {
198             logger.error(EELFLoggerDelegate.errorLogger, "Expection in handleRequest", ex);
199             portalResponse.setStatus(PortalRestStatusEnum.ERROR);
200             response.setStatus(400);
201             portalResponse.setMessage(ex.toString());
202         }
203         return portalResponse;
204     }
205
206     private String getNotificationHyperLink(JsonNode application, String ticket, String eventSource) {
207         return (SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_SYSTEM_NOTIFICATION_URL)+ticket);
208     }
209
210     private String validateTicketEventMessage(JsonNode ticketEventNotif) {
211         JsonNode application = ticketEventNotif.get("application");
212         JsonNode event = ticketEventNotif.get("event");
213         JsonNode header = event.get("header");
214         JsonNode eventSource = header.get("eventSource");
215         JsonNode body = event.get("body");
216         JsonNode subscriberInfo = ticketEventNotif.get("SubscriberInfo");
217         JsonNode userList = subscriberInfo.get("UserList");
218
219         if (application == null || application.asText().length() == 0 || "null".equalsIgnoreCase(application.asText()))
220             return "Application is mandatory";
221         if (body == null)
222             return "body is mandatory";
223         if (eventSource == null || eventSource.asText().trim().length() == 0
224             || "null".equalsIgnoreCase(eventSource.asText()))
225             return "Message Source is mandatory";
226         if (userList == null)
227             return "At least one user Id is mandatory";
228         JsonNode eventDate = body.get(EVENT_DATE);
229
230         if (eventDate != null && eventDate.asText().length() == 8)
231             return "EventDate is invalid";
232         String[] userIds = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
233             .split(",");
234         List<FnUser> users = fnUserService.getUsersByOrgIds(new ArrayList<>(Arrays.asList(userIds)));
235             fnUserService.getUsersByOrgIds(new ArrayList<>(Arrays.asList(userIds)));
236         if (users == null || users.isEmpty())
237             return "Invalid Org User ID";
238         return null;
239     }
240
241 }