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