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