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