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 *     bstefanescu
016 *
017 * $Id$
018 */
019
020package org.nuxeo.ecm.webengine.security.guards;
021
022import java.util.Collection;
023
024import org.nuxeo.ecm.webengine.security.Guard;
025import org.nuxeo.runtime.model.Adaptable;
026
027/**
028 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
029 */
030public class And implements Guard {
031
032    protected Guard[] perms;
033
034    public And(Collection<Guard> guards) {
035        this(guards.toArray(new Guard[guards.size()]));
036    }
037
038    public And(Guard... perms) {
039        if (perms == null) {
040            throw new IllegalArgumentException("Argument cannot be null");
041        }
042        this.perms = perms;
043    }
044
045    public boolean check(Adaptable context) {
046        for (Guard perm : perms) {
047            if (!perm.check(context)) {
048                return false;
049            }
050        }
051        return true;
052    }
053
054    @Override
055    public String toString() {
056        StringBuilder buf = new StringBuilder();
057        if (perms == null) {
058            return "[AND]";
059        }
060        buf.append('(').append(perms[0]);
061        for (int i = 1; i < perms.length; i++) {
062            buf.append(" AND ").append(perms[i]);
063        }
064        return buf.append(')').toString();
065    }
066
067}