Fix major sonar issues in SDK APP admin mod
[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 Logger policyLogger  = FlexLogger.getLogger(PolicyNotificationMail.class);
60
61     @Bean
62     public JavaMailSenderImpl javaMailSenderImpl(){
63         JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
64         mailSender.setHost(PolicyController.getSmtpHost());
65         mailSender.setPort(Integer.parseInt(PolicyController.getSmtpPort()));
66         mailSender.setUsername(PolicyController.getSmtpUsername());
67         mailSender.setPassword(PolicyController.getSmtpPassword());
68         Properties prop = mailSender.getJavaMailProperties();
69         prop.put("mail.transport.protocol", "smtp");
70         prop.put("mail.smtp.auth", "true");
71         prop.put("mail.smtp.starttls.enable", "true");
72         prop.put("mail.debug", "true");
73         return mailSender;
74     }
75
76     /**
77      * Depending on the mode of operation on the policy, compose the subject and message.
78      * Invoke another internal method to actual send the mail. If the watch list is empty , then
79      * this method returns without sending notification mail
80      * @param entityItem Database item from which policy name could be extracted
81      * @param policyName Name of the policy for which notification is to be sent
82      * @param mode kind of operation done on the policy
83      * @param policyNotificationDao database access object for policy
84      * @throws MessagingException
85      */
86     public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) throws MessagingException {
87
88         String subject = "";
89         String message = "";
90         DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
91         Date date = new Date();
92         if("EditPolicy".equalsIgnoreCase(mode)){
93             subject = "Policy has been Updated : "+entityItem.getPolicyName();
94             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Updated" + '\n'  + '\n'  + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion()
95                      + '\n'  + '\n' + "Modified By : " +entityItem.getModifiedBy() + '\n' + "Modified Time  : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
96         }
97         if("Rename".equalsIgnoreCase(mode)){
98             subject = "Policy has been Renamed : "+entityItem.getPolicyName();
99             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Renamed" + '\n'  + '\n'  + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion()
100                      + '\n'  + '\n' + "Renamed By : " +entityItem.getModifiedBy() + '\n' + "Renamed Time  : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
101         }
102         if("DeleteAll".equalsIgnoreCase(mode)){
103             subject = "Policy has been Deleted : "+entityItem.getPolicyName();
104             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Deleted with All Versions" + '\n'  + '\n'  + '\n'+ SCOPE_POLICY_NAME + policyName + '\n'
105                      + '\n'  + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + DELETED_TIME +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
106         }
107         if("DeleteOne".equalsIgnoreCase(mode)){
108             subject = "Policy has been Deleted : "+entityItem.getPolicyName();
109             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n'  + '\n'  + '\n'+ SCOPE_POLICY_NAME + policyName + '\n'  +"Policy Version : " +entityItem.getActiveVersion()
110                      + '\n'  + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + DELETED_TIME +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
111         }
112         if("DeleteScope".equalsIgnoreCase(mode)){
113             subject = "Scope has been Deleted : "+entityItem.getPolicyName();
114             message = "The Scope Which you are watching in  " + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n'  + '\n'  + '\n'+ "Scope + Scope Name  : "  + policyName + '\n'
115                      + '\n'  + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + DELETED_TIME +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
116         }
117         if("SwitchVersion".equalsIgnoreCase(mode)){
118             subject = "Policy has been SwitchedVersion : "+entityItem.getPolicyName();
119             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been SwitchedVersion" + '\n'  + '\n'  + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion()
120                      + '\n'  + '\n' + "Switched By : " +entityItem.getModifiedBy() + '\n' + "Switched Time  : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
121         }
122         if("Move".equalsIgnoreCase(mode)){
123             subject = "Policy has been Moved to Other Scope : "+entityItem.getPolicyName();
124             message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Moved to Other Scope" + '\n'  + '\n'  + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion()
125                      + '\n'  + '\n' + "Moved By : " +entityItem.getModifiedBy() + '\n' + "Moved Time  : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
126         }
127         String checkPolicyName = findCheckPolicyName(policyName);
128
129         String policyFileName = findPolicyFileName(entityItem);
130         String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
131         List<Object> watchList = findWatchList(policyNotificationDao, policyFileName, query);
132         if (watchList == null) return;
133
134         composeAndSendMail(mode, policyNotificationDao, subject, message, checkPolicyName, watchList);
135     }
136
137     private List<Object> findWatchList(CommonClassDao policyNotificationDao, String policyFileName, String query) {
138         SimpleBindings params = new SimpleBindings();
139         params.put("policyFileName", policyFileName);
140         List<Object> watchList;
141         if(PolicyController.isjUnit()){
142             watchList = policyNotificationDao.getDataByQuery(query, null);
143         }else{
144             watchList = policyNotificationDao.getDataByQuery(query, params);
145         }
146
147         if(watchList == null || watchList.isEmpty()) {
148             policyLogger.debug("List of policy being watched is either null or empty, hence return without sending mail");
149             return null;
150         }
151         return watchList;
152     }
153
154     private String findPolicyFileName(PolicyVersion entityItem) {
155         String policyFileName = entityItem.getPolicyName();
156         if(policyFileName.contains("/")){
157             policyFileName = policyFileName.substring(0, policyFileName.indexOf('/'));
158             policyFileName = policyFileName.replace("/", File.separator);
159         }
160         if(policyFileName.contains("\\")){
161             policyFileName = policyFileName.substring(0, policyFileName.indexOf('\\'));
162             policyFileName = policyFileName.replace("\\", "\\\\");
163         }
164
165         policyFileName += "%";
166         return policyFileName;
167     }
168
169     private String findCheckPolicyName(String policyName) {
170         String checkPolicyName = policyName;
171         if(checkPolicyName.endsWith(".xml") || checkPolicyName.contains(".")){
172             checkPolicyName = checkPolicyName.substring(0, checkPolicyName.indexOf('.'));
173         }
174         return checkPolicyName;
175     }
176
177     /**
178      * For every policy being watched and when the policy name is one of the Config_, Action_ or Decision_,
179      * send the notification
180      * @param mode
181      * @param policyNotificationDao
182      * @param subject
183      * @param message
184      * @param checkPolicyName
185      * @param watchList
186      */
187     private void composeAndSendMail(String mode, CommonClassDao policyNotificationDao, String subject, String message, String checkPolicyName, List<Object> watchList) {
188         String from = PolicyController.getSmtpUsername();
189         String to;
190         for(Object watch : watchList){
191             WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch;
192             String watchPolicyName = list.getPolicyName();
193             //this conditino check for specific stringin policy name being watched and
194             //also if the policy being checked is different from the watched ones,
195             //then there is no need to send mail, hence continue with next policy in the loop
196             if((watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_") || watchPolicyName.contains("Decision_"))
197                     && !watchPolicyName.equals(checkPolicyName)){
198                 continue;
199             }
200             try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
201                 to = list.getLoginIds()+"@"+PolicyController.getSmtpEmailExtension();
202                 to = to.trim();
203                 ctx.register(PolicyNotificationMail.class);
204                 ctx.refresh();
205                 JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class);
206                 MimeMessage mimeMessage = mailSender.createMimeMessage();
207                 MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage);
208                 mailMsg.setFrom(new InternetAddress(from, "Policy Notification System"));
209                 mailMsg.setTo(to);
210                 mailMsg.setSubject(subject);
211                 mailMsg.setText(message);
212                 mailSender.send(mimeMessage);
213                 if("Rename".equalsIgnoreCase(mode) || mode.contains("Delete") || mode.contains("Move")){
214                     policyNotificationDao.delete(watch);
215                 }
216             } catch (Exception e) {
217                 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e);
218             }
219
220         }
221     }
222 }