001/*
002 * (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Alexandre Russel
016 *
017 * $Id$
018 */
019
020package org.nuxeo.ecm.platform.mail.action;
021
022import javax.mail.Folder;
023import javax.mail.Message;
024import javax.mail.MessagingException;
025
026/**
027 * @author Alexandre Russel
028 */
029public class Visitor {
030
031    private final MessageActionPipe pipe;
032
033    public Visitor(MessageActionPipe pipe) {
034        this.pipe = pipe;
035    }
036
037    public void visit(Folder folder) throws MessagingException {
038        visit(folder, null);
039    }
040
041    /**
042     * Visit every message of given folder and every message of its subfolders.
043     *
044     * @param folder
045     * @param initialContext context variables passed to each execution context
046     */
047    public void visit(Folder folder, ExecutionContext initialContext) throws MessagingException {
048        for (Message message : folder.getMessages()) {
049            ExecutionContext context = new ExecutionContext(message, initialContext);
050            for (MessageAction action : pipe) {
051                action.reset(context);
052                boolean result = action.execute(context);
053                if (!result) {
054                    break;
055                }
056            }
057        }
058        Folder[] folders = {};
059        try {
060            folders = folder.list();
061        } catch (MessagingException e) {
062            // do, nothing, list() not implemented.
063        }
064        for (Folder f : folders) {
065            visit(f, initialContext);
066        }
067    }
068
069    /**
070     * Visit given messages
071     *
072     * @param messages
073     * @param initialContext context variables passed to each execution context
074     */
075    public void visit(Message[] messages, ExecutionContext initialContext) throws MessagingException {
076        for (Message message : messages) {
077            ExecutionContext context = new ExecutionContext(message, initialContext);
078            for (MessageAction action : pipe) {
079                action.reset(context);
080                boolean result = action.execute(context);
081                if (!result) {
082                    break;
083                }
084            }
085        }
086    }
087
088}