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

br.com.caelum.vraptor.simplemail.DefaultAsyncMailer Maven / Gradle / Ivy

The newest version!
package br.com.caelum.vraptor.simplemail;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.spi.Producer;
import javax.inject.Inject;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.caelum.vraptor.environment.Environment;

/**
 * A simple implementation of an asynchronous mailer. It relies upon an instance
 * of {@link ExecutorService} to distribute tasks among threads. This
 * {@link ExecutorService} must be provided by a CDI {@link Producer}.
 *
 * @author luiz
 * @author victorkendy
 */
@RequestScoped
public class DefaultAsyncMailer implements AsyncMailer {

	private static final Logger LOGGER = LoggerFactory.getLogger(DefaultAsyncMailer.class);

	private ExecutorService executor;
	private Mailer mailer;
	private Queue mailQueue = new LinkedList();

	@Deprecated //CDI eyes only
	public DefaultAsyncMailer() {}
	
	@Inject
	public DefaultAsyncMailer(ExecutorService executor, Mailer mailer) {
		this.executor = executor;
		this.mailer = mailer;
	}

	@Override
	public Future asyncSend(final Email email) {
		LOGGER.debug("New email to be sent asynchronously: {} to {}", email.getSubject(), email.getToAddresses());
		Callable task = new Callable() {
			@Override
			public Void call()  {
				try {
					DefaultAsyncMailer.this.mailer.send(email);
				} catch (EmailException e) {
					LOGGER.error(
							"Error while sending async email "
									+ email.getSubject() + " to "
									+ email.getToAddresses(), e);
				}
				return null;
			}
		};
		return this.executor.submit(task);
	}

	@Override
	public void sendLater(Email email) {
		this.mailQueue.add(email);
	}

	@Override
	public List clearPostponedMails() {
		List undeliveredMails = new ArrayList(this.mailQueue);
		this.mailQueue.clear();
		return undeliveredMails;
	}

	@Override
	public Map> deliverPostponedMails() {
		Map> deliveries = new HashMap>();
		LOGGER.debug("Delivering all {} postponed emails", this.mailQueue.size());
		while (!this.mailQueue.isEmpty()) {
			Email nextMail = this.mailQueue.poll();
			Future sendingResult = this.asyncSend(nextMail);
			deliveries.put(nextMail, sendingResult);
		}
		return deliveries;
	}

	@Override
	public boolean hasMailToDeliver() {
		return !this.mailQueue.isEmpty();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy