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