com.seajas.search.codex.service.task.ExpirationNotifierTask.java Source code

Java tutorial

Introduction

Here is the source code for com.seajas.search.codex.service.task.ExpirationNotifierTask.java

Source

/**
 * Copyright (C) 2013 Seajas, the Netherlands.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.seajas.search.codex.service.task;

import com.seajas.search.codex.model.identity.Identity;
import com.seajas.search.codex.model.identity.IdentityAccount;
import com.seajas.search.codex.model.identity.IdentityAccountToken;
import com.seajas.search.codex.service.codex.CodexService;
import com.seajas.search.codex.service.mail.MailService;
import com.seajas.search.utilities.logging.SearchLogger;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.stereotype.Component;

/**
 * Quartz job for notifying subscribers of new results.
 * 
 * @author Jasper van Veghel <jasper@seajas.com>
 */
@Component
public class ExpirationNotifierTask {
    /**
     * The logger.
     */
    @Autowired
    protected SearchLogger logger;

    /**
     * Codex service.
     */
    @Autowired
    private CodexService codexService;

    /**
     * The mail service.
     */
    @Autowired
    private MailService mailService;

    /**
     * The message source.
     */
    @Autowired
    private MessageSource messageSource;

    /**
     * The maximum thread pool size.
     */
    @Value("${codex.project.concurrent.threads.maximum}")
    private Integer threadMaximum;

    /**
     * Send out the actual notification e-mails.
     */
    public void send() {
        if (Boolean.getBoolean("com.seajas.search.codex.notifications.disabled")) {
            logger.info(
                    "Notifications have been explicitly disabled using 'com.seajas.search.codex.notifications.disabled=true'. Skipping notification expiration checks.");

            return;
        }

        logger.info("Started expiration notifier task");

        // Also use a regular date for reference, to pass to the search engine

        final Date currentDate = new Date();

        // Retrieve the list of profile profiles to attend to

        List<Identity> identities = codexService.getNotifiableIdentities(currentDate);

        if (identities.size() == 0) {
            logger.info("No notifiable identities found - finishing expiration notifier task");

            return;
        }

        // Now process the profiles using a thread-pool of at most threadMaximum threads

        ExecutorService threadPool = Executors.newFixedThreadPool(Math.min(identities.size(), threadMaximum));

        for (final Identity identity : identities)
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    List<IdentityAccount> accounts = codexService.getNotifiableAccounts(currentDate,
                            identity.getAccounts());

                    for (IdentityAccount account : accounts) {
                        // Retrieve the most recently expired unreported token

                        IdentityAccountToken relevantToken = null;

                        for (IdentityAccountToken token : account.getTokens())
                            if (token.getExpireTime() > currentDate.getTime() && !token.getIsReported()) {
                                relevantToken = token;

                                break;
                            }

                        if (relevantToken == null) {
                            logger.error(
                                    "No relevant token could be found - despite this account having been found to be notifiable");

                            break;
                        }

                        // Take the subject in the given language, or resort to the default language if it doesn't exist (yet)

                        String subject = null;

                        try {
                            subject = messageSource.getMessage("mail.result.subject.token.expired", null,
                                    new Locale(identity.getNotifierLanguage()));
                        } catch (NoSuchMessageException e) {
                            logger.warn("Could not retrieve results message subject header in language "
                                    + identity.getNotifierLanguage() + ", resorting to the default language "
                                    + codexService.getDefaultApplicationLanguage());

                            subject = messageSource.getMessage("mail.confirmation.subject", null,
                                    new Locale(codexService.getDefaultApplicationLanguage()));
                        }

                        // And send out the actual e-mail

                        if (!mailService.sendMessage(identity.getNotifierEmail(), subject, "TODO"))
                            logger.error(
                                    "Could not e-mail the notification expiration message - attender failed to send message.");

                        // Update the processed subscribers' lastNotification indicator

                        codexService.markAccountNotified(account);
                    }
                }
            });

        logger.info("Finishing expiration notifier task");
    }
}