All Downloads are FREE. Search and download functionalities are using the official Maven repository.

atom.app.kie.EventNotificationTaskWorkItemHandler Maven / Gradle / Ivy

The newest version!
/*
 * Copyright © 2015 Geeoz, and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * The Research Projects is dual-licensed under the GNU General Public
 * License, version 2.0 (GPLv2) and the Geeoz Commercial License.
 *
 * Solely for non-commercial purposes. A purpose is non-commercial only if
 * it is in no manner primarily intended for or directed toward commercial
 * advantage or private monetary compensation.
 *
 * This Geeoz Software is supplied to you by Geeoz in consideration of your
 * agreement to the following terms, and your use, installation, modification
 * or redistribution of this Geeoz Software constitutes acceptance of these
 * terms. If you do not agree with these terms, please do not use, install,
 * modify or redistribute this Geeoz Software.
 *
 * Neither the name, trademarks, service marks or logos of Geeoz may be used
 * to endorse or promote products derived from the Geeoz Software without
 * specific prior written permission from Geeoz.
 *
 * The Geeoz Software is provided by Geeoz on an "AS IS" basis. GEEOZ MAKES NO
 * WARRANTIES, EXPRESS  OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
 * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE, REGARDING THE GEEOZ SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
 * COMBINATION WITH YOUR PRODUCTS.
 *
 * IN NO EVENT SHALL GEEOZ BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION
 * AND/OR DISTRIBUTION OF THE GEEOZ SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER
 * THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
 * OTHERWISE, EVEN IF GEEOZ HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * A copy of the GNU General Public License is included in the distribution in
 * the file LICENSE and at
 *
 *     http://www.gnu.org/licenses/gpl-2.0.html
 *
 * If you are using the Research Projects for commercial purposes, we
 * encourage you to visit
 *
 *     http://products.geeoz.com/license
 *
 * for more details.
 *
 * This software or hardware and documentation may provide access to
 * or information on content, products, and services from third parties.
 * Geeoz and its affiliates are not responsible for and expressly disclaim
 * all warranties of any kind with respect to third-party content, products,
 * and services. Geeoz and its affiliates will not be responsible for any loss,
 * costs, or damages incurred due to your access to or use of third-party
 * content, products, or services. If a third-party content exists, the
 * additional copyright notices and license terms applicable to portions of the
 * software are set forth in the THIRD_PARTY_LICENSE_README file.
 *
 * Please contact Geeoz or visit www.geeoz.com if you need additional
 * information or have any questions.
 */

package atom.app.kie;

import atom.app.Activity;
import atom.app.KieActivity;
import atom.app.TemplateManager;
import atom.content.Context;
import atom.kie.AbstractTask;
import atom.view.ResourceBundleFilter;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.ObjectWrapper;
import freemarker.template.SimpleHash;
import org.kie.api.runtime.process.WorkItem;
import org.kie.api.runtime.process.WorkItemManager;
import org.kie.internal.runtime.StatefulKnowledgeSession;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.InputStream;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

/**
 * Event notification task work item handler with KIE session.
 *
 * @author Alex Voloshyn
 * @author Eugene Shevchenko
 * @version 1.8 3/10/15
 */
@Deprecated
public final class EventNotificationTaskWorkItemHandler extends AbstractTask {
    /**
     * Template manager service.
     */
    private static final TemplateManager MANAGER =
            Context.getSystemService(TemplateManager.class);
    /**
     * Mail senders executors pool.
     */
    private static final ForkJoinPool POOL = new ForkJoinPool();
    /**
     * Mail server configuration.
     */
    private static final Properties CONFIG;
    /**
     * Mime type of the object.
     */
    private static final String CONTENT_TYPE_KEY = "mail.content.type";
    /**
     * Attempt to authenticate the user using the AUTH command.
     */
    private static final String SMTP_AUTH_KEY = "mail.smtp.auth";
    /**
     * The user name key for authentication.
     */
    private static final String SMTP_USER_KEY = "mail.smtp.auth.user";
    /**
     * The user's password key for authentication.
     */
    private static final String SMTP_PASS_KEY = "mail.smtp.auth.pass";
    /**
     * If true, attempt to authenticate the user using the AUTH command.
     * Defaults to false.
     */
    private static final boolean SMTP_AUTH;
    /**
     * The user name for authentication.
     */
    private static final String SMTP_USER;
    /**
     * The user's password for authentication.
     */
    private static final String SMTP_PASS;

    static {
        Properties properties;
        // Load  the  properties file
        try {
            properties = new Properties();
            final InputStream inputStream =
                    EventNotificationTaskWorkItemHandler.class.getClassLoader()
                            .getResourceAsStream("META-INF/drools.mail.conf");
            properties.load(inputStream);
        } catch (Exception e) {
            // Catching  the  exception as null condition
            // is handled in the methods.
            properties = new Properties();
        }
        CONFIG = properties;
        SMTP_AUTH = Boolean.parseBoolean(
                CONFIG.getProperty(SMTP_AUTH_KEY, "false"));
        SMTP_USER = CONFIG.getProperty(SMTP_USER_KEY);
        SMTP_PASS = CONFIG.getProperty(SMTP_PASS_KEY);
    }

    /**
     * Default constructor with KIE session.
     *
     * @param kieSession KIE session to use
     */
    public EventNotificationTaskWorkItemHandler(
            final StatefulKnowledgeSession kieSession) {
        super(kieSession);
    }

    @Override
    public void executeWorkItem(final WorkItem item,
                                final WorkItemManager manager) {
        final Activity activity =
                (Activity) getVariable(item, KieActivity.ACTIVITY);
        final Locale locale = activity.getActivityThread().getLocale();
        final String template = (String) item.getParameter("template");
        final String email = (String) item.getParameter("email");
        if (email != null) {
            POOL.execute(new SendAction(template, email, locale,
                    item.getParameters(), activity.getClassLoader()));
        }
        manager.completeWorkItem(item.getId(), item.getResults());
    }

    @Override
    public void abortWorkItem(final WorkItem item,
                              final WorkItemManager manager) {
        manager.abortWorkItem(item.getId());
    }

    /**
     * Authenticator with username and password.
     */
    private static class DefaultAuthenticator extends Authenticator {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(SMTP_USER, SMTP_PASS);
        }
    }

    /**
     * Retrieve email message and send it in separate thread.
     */
    private static final class SendAction extends RecursiveAction {
        /**
         * Use serialVersionUID from JDK 1.0.2 for interoperability.
         */
        private static final long serialVersionUID = 1086325989963873319L;
        /**
         * Template key for message.
         */
        private final String template;
        /**
         * Recipient to email.
         */
        private final String recipientTo;
        /**
         * Locale to use.
         */
        private final Locale locale;
        /**
         * Additional parameters.
         */
        private final Map parameters;
        /**
         * Class loader.
         */
        private transient ClassLoader loader = null;

        /**
         * Default constructor for send action.
         *
         * @param templateKey template key for message
         * @param email       recipient to email
         * @param lang        locale to use
         * @param map         additional parameters
         * @param classLoader class loader for external templates
         */
        private SendAction(final String templateKey,
                           final String email,
                           final Locale lang,
                           final Map map,
                           final ClassLoader classLoader) {
            template = templateKey;
            recipientTo = email;
            locale = lang;
            parameters = map;
            loader = classLoader;
        }

        @Override
        protected void compute() {
            final Session session;
            if (SMTP_AUTH) {
                session = Session.getDefaultInstance(
                        CONFIG, new DefaultAuthenticator());
            } else {
                session = Session.getDefaultInstance(CONFIG);
            }
            try {
                final MimeMessage message = new MimeMessage(session);
                message.addRecipient(Message.RecipientType.TO,
                        new InternetAddress(recipientTo));
                final ObjectWrapper wrapper
                        = new DefaultObjectWrapperBuilder(
                        Configuration.getVersion()).build();
                final SimpleHash params = new SimpleHash(wrapper);
                params.put("context", parameters);
                final ResourceBundle bundle = ResourceBundle.getBundle(
                        "values.distribution", locale, loader,
                        ResourceBundleFilter.utf8());
                params.put("strings", bundle);
                final String emailSubject = String.format(
                        "templates/%s/email.subject.ftl", template);
                message.setSubject(MANAGER.process(
                        emailSubject, locale, params, loader));
                final String emailBody = String.format(
                        "templates/%s/email.body.ftl", template);
                final Multipart multipart = new MimeMultipart();
                final MimeBodyPart htmlPart = new MimeBodyPart();
                htmlPart.setContent(MANAGER.process(
                                emailBody, locale, params, loader),
                        CONFIG.getProperty(CONTENT_TYPE_KEY,
                                "text/html; charset=UTF-8"));
                multipart.addBodyPart(htmlPart);
                message.setContent(multipart);
                Transport.send(message);
            } catch (MessagingException ex) {
                ex.printStackTrace();
            }
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy