001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     troger
011 *
012 * $Id$
013 */
014
015package org.nuxeo.ecm.core.api.impl;
016
017import java.util.ArrayList;
018import java.util.List;
019
020import org.nuxeo.ecm.core.api.DocumentModel;
021import org.nuxeo.ecm.core.api.Filter;
022
023/**
024 * A filter based on the document's life cycle.
025 *
026 * @author <a href="mailto:troger@nuxeo.com">Thomas Roger</a>
027 */
028public class LifeCycleFilter implements Filter {
029
030    private static final long serialVersionUID = -6222667096842773182L;
031
032    private final List<String> accepted;
033
034    private final List<String> excluded;
035
036    /**
037     * Generic constructor.
038     * <p>
039     * To be accepted, the document must have its lifecycle state in the {@code required} list and the {@code excluded}
040     * list must not contain its lifecycle state.
041     *
042     * @param accepted the list of accepted lifecycle states
043     * @param excluded the list of excluded lifecycle states
044     */
045    public LifeCycleFilter(List<String> accepted, List<String> excluded) {
046        this.accepted = accepted;
047        this.excluded = excluded;
048    }
049
050    /**
051     * Convenient constructor to filter on a lifecycle state.
052     *
053     * @param lifeCycle the lifecycle to filter on
054     * @param isRequired if {@code true} accepted documents must have this lifecycle state, if {@code false} accepted
055     *            documents must not have this lifecycle state.
056     */
057    public LifeCycleFilter(String lifeCycle, boolean isRequired) {
058        if (isRequired) {
059            accepted = new ArrayList<String>();
060            excluded = null;
061            accepted.add(lifeCycle);
062        } else {
063            excluded = new ArrayList<String>();
064            accepted = null;
065            excluded.add(lifeCycle);
066        }
067    }
068
069    @Override
070    public boolean accept(DocumentModel docModel) {
071        String lifeCycleState = docModel.getCurrentLifeCycleState();
072        if (excluded != null) {
073            if (excluded.contains(lifeCycleState)) {
074                return false;
075            }
076        }
077        if (accepted != null) {
078            if (!accepted.contains(lifeCycleState)) {
079                return false;
080            }
081        }
082        return true;
083    }
084
085}