001    /**
002     * Copyright 2005-2014 The Kuali Foundation
003     *
004     * Licensed under the Educational Community License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.opensource.org/licenses/ecl2.php
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package org.kuali.rice.kcb.deliverer.impl;
017    
018    import java.util.HashMap;
019    import java.util.HashSet;
020    import java.util.LinkedHashMap;
021    import java.util.Set;
022    
023    import org.apache.commons.validator.EmailValidator;
024    import org.apache.log4j.Logger;
025    import org.kuali.rice.kcb.bo.MessageDelivery;
026    import org.kuali.rice.kcb.deliverer.MessageDeliverer;
027    import org.kuali.rice.kcb.exception.ErrorList;
028    import org.kuali.rice.kcb.api.exception.MessageDeliveryException;
029    import org.kuali.rice.kcb.api.exception.MessageDismissalException;
030    import org.kuali.rice.kcb.service.EmailService;
031    import org.kuali.rice.kcb.service.GlobalKCBServiceLocator;
032    import org.kuali.rice.kcb.service.RecipientPreferenceService;
033    
034    /**
035     * This class is responsible for describing the email delivery mechanism for
036     * the system.
037     * @author Kuali Rice Team (rice.collab@kuali.org)
038     */
039    public class EmailMessageDeliverer implements MessageDeliverer {
040        private static Logger LOG = Logger.getLogger(EmailMessageDeliverer.class);
041    
042        private EmailService emailService;
043        private RecipientPreferenceService recipientPreferenceService;
044    
045        public static final String NAME = "Email";
046        public static final String EMAIL_ADDR_PREF_KEY = "email_address";
047        public static final String EMAIL_DELIV_FRMT_PREF_KEY = "email_delivery_format";
048    
049        /**
050         * Constructs a EmailMessageDeliverer.java.
051         */
052        public EmailMessageDeliverer() {
053            this.emailService = GlobalKCBServiceLocator.getInstance().getEmailService();
054            this.recipientPreferenceService = GlobalKCBServiceLocator.getInstance().getRecipientPreferenceService();
055        }
056    
057        /**
058         * This implementation uses the email service to deliver a notification.
059         * @see org.kuali.rice.kcb.deliverer.MessageDeliverer#deliver(MessageDelivery)
060         */
061        public void deliver(MessageDelivery messageDelivery) throws MessageDeliveryException {
062            try {
063                // figure out the proper recipient email address
064                String recipientEmailAddressPrefKey = getName()+"."+EMAIL_ADDR_PREF_KEY;
065                String recipientEmailFormatPrefKey = getName()+"."+EMAIL_DELIV_FRMT_PREF_KEY;
066    
067                String recipientEmailAddress = recipientPreferenceService.getRecipientPreference(messageDelivery.getMessage().getRecipient(), recipientEmailAddressPrefKey).getValue();
068                String recipientEmailFormat = recipientPreferenceService.getRecipientPreference(messageDelivery.getMessage().getRecipient(), recipientEmailFormatPrefKey).getValue();
069    
070                //String recipientEmailAddress = GlobalNotificationServiceLocator.getInstance().getKENAPIService().getRecipientPreference(messageDelivery.getMessage().getRecipient(), recipientEmailAddressPrefKey);
071                //String recipientEmailFormat = GlobalNotificationServiceLocator.getInstance().getKENAPIService().getRecipientPreference(messageDelivery.getMessage().getRecipient(), recipientEmailFormatPrefKey);
072    
073                Long emailMessageId = emailService.sendEmail(messageDelivery, recipientEmailAddress, recipientEmailFormat);
074    
075                String deliverySystemId = null;
076                if (emailMessageId != null) {
077                    deliverySystemId = emailMessageId.toString();
078                }
079                messageDelivery.setDelivererSystemId(deliverySystemId);
080            } catch (Exception we) {
081                LOG.error("Error delivering email notification", we);
082                throw new MessageDeliveryException("Error delivering email notification", we);
083            }
084        }
085    
086        /**
087         * This implementation does an auto-remove by "canceling" the workflow email with the message delivery record. 
088         * In the case of email, it's a noop 
089         * @see org.kuali.rice.kcb.deliverer.MessageDeliverer#autoRemoveMessageDelivery(org.kuali.rice.ken.bo.NotificationMessageDelivery)
090         */
091        public void autoRemoveMessageDelivery(MessageDelivery messageDelivery) /*throws NotificationAutoRemoveException*/ {
092            // we can't remove an email message once it has been sent
093        }
094    
095        /**
096         * @see org.kuali.rice.kcb.deliverer.MessageDeliverer#dismiss(org.kuali.rice.kcb.bo.MessageDelivery, java.lang.String, java.lang.String)
097         */
098        public void dismiss(MessageDelivery messageDelivery, String user, String cause) throws MessageDismissalException {
099            // we can't remove an email message once it has been sent
100        }
101    
102        /**
103         * @see org.kuali.rice.kcb.deliverer.MessageDeliverer#getDescription()
104         */
105        public String getDescription() {
106            return "Enter an Email Address and Email Delivery Format below and select the channels for which you would like email delivery " +
107                   "notifications. Select \"None\" in the channel list to remove a delivery type for all channels.  " +
108                   "Only one Email Address and Email Delivery Format may be specified. Any data entered and " +
109                   "saved will override prior Delivery Type selections.";
110        }
111    
112        /**
113         * @see org.kuali.rice.kcb.deliverer.MessageDeliverer#getName()
114         */
115        public String getName() {
116            return NAME;
117        }
118    
119        /**
120         * @see org.kuali.rice.kcb.deliverer.MessageDeliverer#getTitle()
121         */
122        public String getTitle() {
123            return "Email Message Delivery";
124        }
125    
126        /**
127         * This implementation returns an address field.
128         * @see org.kuali.rice.kcb.deliverer.MessageDeliverer#getPreferenceKeys()
129         */
130        public LinkedHashMap<String, String> getPreferenceKeys() {
131            LinkedHashMap<String, String> prefKeys = new LinkedHashMap<String, String>();
132            prefKeys.put(EMAIL_ADDR_PREF_KEY, "Email Address (\"abc@def.edu\")");
133            prefKeys.put(EMAIL_DELIV_FRMT_PREF_KEY, "Email Delivery Format (text or html)");
134            return prefKeys;
135        }
136    
137        /**
138         * @see org.kuali.rice.kcb.deliverer.MessageDeliverer#validatePreferenceValues(java.util.HashMap)
139         */
140        public void validatePreferenceValues(HashMap<String, String> prefs) throws ErrorList {
141            boolean error = false;
142            ErrorList errorList = new ErrorList();
143            String[] validformats = {"text","html"};
144    
145            if (!prefs.containsKey(getName()+"."+EMAIL_ADDR_PREF_KEY)) {
146                errorList.addError("Email Address is a required field.");
147                error = true;
148            } else {
149                String addressValue = (String) prefs.get(getName()+"."+EMAIL_ADDR_PREF_KEY);
150                EmailValidator validator = EmailValidator.getInstance();
151                if (!validator.isValid(addressValue)) {
152                    errorList.addError("Email Address is required and must be properly formatted - \"abc@def.edu\".");
153                    error = true;
154                }
155            }
156    
157            // validate format
158            if (!prefs.containsKey(getName()+"."+EMAIL_DELIV_FRMT_PREF_KEY)) {
159                errorList.addError("Email Delivery Format is required.");
160                error = true;
161            } else {
162                String formatValue = (String) prefs.get(getName()+"."+EMAIL_DELIV_FRMT_PREF_KEY);
163                Set<String> formats = new HashSet<String>();
164                for (int i=0; i < validformats.length ; i++) {
165                    formats.add(validformats[i]);
166                }
167    
168                if (!formats.contains(formatValue)) {
169                    errorList.addError("Email Delivery Format is required and must be entered as \"text\" or \"html\".");
170                    error = true;
171                }
172            }
173    
174            if (error) throw errorList;
175        }
176    }