Format java POLICY-SDK-APP
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / admin / PolicyNotificationMail.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * Modifications Copyright (C) 2019 Bell Canada
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file 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  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.admin;
24
25 import java.io.File;
26 import java.text.DateFormat;
27 import java.text.SimpleDateFormat;
28 import java.util.ArrayList;
29 import java.util.Date;
30 import java.util.List;
31 import java.util.Properties;
32
33 import javax.mail.internet.InternetAddress;
34 import javax.mail.internet.MimeMessage;
35 import javax.script.SimpleBindings;
36
37 import org.onap.policy.common.logging.flexlogger.FlexLogger;
38 import org.onap.policy.common.logging.flexlogger.Logger;
39 import org.onap.policy.controller.PolicyController;
40 import org.onap.policy.rest.dao.CommonClassDao;
41 import org.onap.policy.rest.jpa.PolicyVersion;
42 import org.onap.policy.rest.jpa.WatchPolicyNotificationTable;
43 import org.onap.policy.xacml.api.XACMLErrorConstants;
44 import org.springframework.beans.factory.annotation.Configurable;
45 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
46 import org.springframework.context.annotation.Bean;
47 import org.springframework.mail.javamail.JavaMailSenderImpl;
48 import org.springframework.mail.javamail.MimeMessageHelper;
49
50 /**
51  * Send policy notification mail depending on the mode for every policy being watched
52  */
53 @Configurable
54 public class PolicyNotificationMail {
55     private static final String POLICY_WATCHING_MESSAGE = "The Policy Which you are watching in  ";
56     private static final String EMAIL_MESSAGE_POSTSCRIPT =
57             "Policy Notification System  (please don't respond to this email)";
58     private static final String ACTIVE_VERSION = "Active Version  : ";
59     private static final String SCOPE_POLICY_NAME = "Scope + Policy Name  : ";
60     private static final String DELETED_TIME = "Deleted Time  : ";
61     private static final String DELETED_BY = "Deleted By : ";
62     private static Logger policyLogger = FlexLogger.getLogger(PolicyNotificationMail.class);
63
64     @Bean
65     public JavaMailSenderImpl javaMailSenderImpl() {
66         JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
67         mailSender.setHost(PolicyController.getSmtpHost());
68         mailSender.setPort(Integer.parseInt(PolicyController.getSmtpPort()));
69         mailSender.setUsername(PolicyController.getSmtpUsername());
70         mailSender.setPassword(PolicyController.getSmtpPassword());
71         Properties prop = mailSender.getJavaMailProperties();
72         prop.put("mail.transport.protocol", "smtp");
73         prop.put("mail.smtp.auth", "true");
74         prop.put("mail.smtp.starttls.enable", "true");
75         prop.put("mail.debug", "true");
76         return mailSender;
77     }
78
79     /**
80      * Depending on the mode of operation on the policy, compose the subject and message.
81      * Invoke another internal method to actual send the mail. If the watch list is empty , then
82      * this method returns without sending notification mail
83      *
84      * @param entityItem Database item from which policy name could be extracted
85      * @param policyName Name of the policy for which notification is to be sent
86      * @param mode kind of operation done on the policy
87      * @param policyNotificationDao database access object for policy
88      */
89     public void sendMail(PolicyVersion entityItem, String policyName, String mode,
90             CommonClassDao policyNotificationDao) {
91
92         String subject = "";
93         String message = "";
94         DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
95         Date date = new Date();
96         if ("EditPolicy".equalsIgnoreCase(mode)) {
97             subject = "Policy has been Updated : " + entityItem.getPolicyName();
98             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Updated" + '\n'
99                     + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION
100                     + entityItem.getActiveVersion() + '\n' + '\n' + "Modified By : " + entityItem.getModifiedBy() + '\n'
101                     + "Modified Time  : " + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n'
102                     + EMAIL_MESSAGE_POSTSCRIPT;
103         }
104         if ("Rename".equalsIgnoreCase(mode)) {
105             subject = "Policy has been Renamed : " + entityItem.getPolicyName();
106             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Renamed" + '\n'
107                     + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION
108                     + entityItem.getActiveVersion() + '\n' + '\n' + "Renamed By : " + entityItem.getModifiedBy() + '\n'
109                     + "Renamed Time  : " + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n'
110                     + EMAIL_MESSAGE_POSTSCRIPT;
111         }
112         if ("DeleteAll".equalsIgnoreCase(mode)) {
113             subject = "Policy has been Deleted : " + entityItem.getPolicyName();
114             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName()
115                     + " has been Deleted with All Versions" + '\n' + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n'
116                     + '\n' + '\n' + DELETED_BY + entityItem.getModifiedBy() + '\n' + DELETED_TIME
117                     + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
118         }
119         if ("DeleteOne".equalsIgnoreCase(mode)) {
120             subject = "Policy has been Deleted : " + entityItem.getPolicyName();
121             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n'
122                     + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + "Policy Version : "
123                     + entityItem.getActiveVersion() + '\n' + '\n' + DELETED_BY + entityItem.getModifiedBy() + '\n'
124                     + DELETED_TIME + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
125         }
126         if ("DeleteScope".equalsIgnoreCase(mode)) {
127             subject = "Scope has been Deleted : " + entityItem.getPolicyName();
128             message = "The Scope Which you are watching in  " + PolicyController.getSmtpApplicationName()
129                     + " has been Deleted" + '\n' + '\n' + '\n' + "Scope + Scope Name  : " + policyName + '\n' + '\n'
130                     + '\n' + DELETED_BY + entityItem.getModifiedBy() + '\n' + DELETED_TIME + dateFormat.format(date)
131                     + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
132         }
133         if ("SwitchVersion".equalsIgnoreCase(mode)) {
134             subject = "Policy has been SwitchedVersion : " + entityItem.getPolicyName();
135             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been SwitchedVersion"
136                     + '\n' + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION
137                     + entityItem.getActiveVersion() + '\n' + '\n' + "Switched By : " + entityItem.getModifiedBy() + '\n'
138                     + "Switched Time  : " + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n'
139                     + EMAIL_MESSAGE_POSTSCRIPT;
140         }
141         if ("Move".equalsIgnoreCase(mode)) {
142             subject = "Policy has been Moved to Other Scope : " + entityItem.getPolicyName();
143             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName()
144                     + " has been Moved to Other Scope" + '\n' + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n'
145                     + ACTIVE_VERSION + entityItem.getActiveVersion() + '\n' + '\n' + "Moved By : "
146                     + entityItem.getModifiedBy() + '\n' + "Moved Time  : " + dateFormat.format(date) + '\n' + '\n'
147                     + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
148         }
149         String checkPolicyName = findCheckPolicyName(policyName);
150
151         String policyFileName = findPolicyFileName(entityItem);
152         String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
153         List<Object> watchList = findWatchList(policyNotificationDao, policyFileName, query);
154         if (!watchList.isEmpty()) {
155             composeAndSendMail(mode, policyNotificationDao, subject, message, checkPolicyName, watchList);
156         }
157     }
158
159     private List<Object> findWatchList(CommonClassDao policyNotificationDao, String policyFileName, String query) {
160         SimpleBindings params = new SimpleBindings();
161         params.put("policyFileName", policyFileName);
162         List<Object> watchList;
163         if (PolicyController.isjUnit()) {
164             watchList = policyNotificationDao.getDataByQuery(query, null);
165         } else {
166             watchList = policyNotificationDao.getDataByQuery(query, params);
167         }
168
169         if (watchList == null || watchList.isEmpty()) {
170             policyLogger
171                     .debug("List of policy being watched is either null or empty, hence return without sending mail");
172             watchList = new ArrayList<>();
173         }
174         return watchList;
175     }
176
177     private String findPolicyFileName(PolicyVersion entityItem) {
178         String policyFileName = entityItem.getPolicyName();
179         if (policyFileName.contains("/")) {
180             policyFileName = policyFileName.substring(0, policyFileName.indexOf('/'));
181             policyFileName = policyFileName.replace("/", File.separator);
182         }
183         if (policyFileName.contains("\\")) {
184             policyFileName = policyFileName.substring(0, policyFileName.indexOf('\\'));
185             policyFileName = policyFileName.replace("\\", "\\\\");
186         }
187
188         policyFileName += "%";
189         return policyFileName;
190     }
191
192     private String findCheckPolicyName(String policyName) {
193         String checkPolicyName = policyName;
194         if (checkPolicyName.endsWith(".xml") || checkPolicyName.contains(".")) {
195             checkPolicyName = checkPolicyName.substring(0, checkPolicyName.indexOf('.'));
196         }
197         return checkPolicyName;
198     }
199
200     /**
201      * For every policy being watched and when the policy name is one of the Config_, Action_ or Decision_,
202      * send the notification
203      * 
204      * @param mode
205      * @param policyNotificationDao
206      * @param subject
207      * @param message
208      * @param checkPolicyName
209      * @param watchList
210      */
211     private void composeAndSendMail(String mode, CommonClassDao policyNotificationDao, String subject, String message,
212             String checkPolicyName, List<Object> watchList) {
213         String from = PolicyController.getSmtpUsername();
214         String to;
215         for (Object watch : watchList) {
216             WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch;
217             String watchPolicyName = list.getPolicyName();
218             // this conditino check for specific stringin policy name being watched and
219             // also if the policy being checked is different from the watched ones,
220             // then there is no need to send mail, hence continue with next policy in the loop
221             if ((watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_")
222                     || watchPolicyName.contains("Decision_")) && !watchPolicyName.equals(checkPolicyName)) {
223                 continue;
224             }
225             try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
226                 to = list.getLoginIds() + "@" + PolicyController.getSmtpEmailExtension();
227                 to = to.trim();
228                 ctx.register(PolicyNotificationMail.class);
229                 ctx.refresh();
230                 JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class);
231                 MimeMessage mimeMessage = mailSender.createMimeMessage();
232                 MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage);
233                 mailMsg.setFrom(new InternetAddress(from, "Policy Notification System"));
234                 mailMsg.setTo(to);
235                 mailMsg.setSubject(subject);
236                 mailMsg.setText(message);
237                 mailSender.send(mimeMessage);
238                 if ("Rename".equalsIgnoreCase(mode) || mode.contains("Delete") || mode.contains("Move")) {
239                     policyNotificationDao.delete(watch);
240                 }
241             } catch (Exception e) {
242                 policyLogger
243                         .error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured in Policy Notification" + e);
244             }
245
246         }
247     }
248 }