001/*
002 *  Copyright 2017 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.odfweb.restrictions.rules;
017
018import java.util.Collection;
019import java.util.Collections;
020
021import org.ametys.cms.search.query.NotQuery;
022import org.ametys.cms.search.query.Query;
023import org.ametys.odf.program.Program;
024import org.ametys.plugins.repository.query.expression.Expression;
025import org.ametys.plugins.repository.query.expression.NotExpression;
026
027/**
028 * Not restriction rule. Negate a set of rules.
029 */
030public class OdfNotRestrictionRule implements OdfRestrictionRule
031{
032    private final OdfRestrictionRule _rule;
033    
034    /**
035     * Not restriction rule constructor.
036     * @param rules The list of rules on which a "not" operator must be applied
037     */
038    public OdfNotRestrictionRule(Collection<OdfRestrictionRule> rules)
039    {
040        rules.removeAll(Collections.<OdfRestrictionRule>singleton(null));
041        
042        if (rules.size() > 1)
043        {
044            _rule = new OdfAndRestrictionRule(rules);
045        }
046        else if (!rules.isEmpty())
047        {
048            _rule = rules.iterator().next();
049        }
050        else
051        {
052            throw new IllegalArgumentException("At least one non-null rule is required.");
053        }
054    }
055    
056    @Override
057    public boolean contains(Program program)
058    {
059        return !_rule.contains(program);
060    }
061    
062    @Override
063    public Expression getExpression()
064    {
065        Expression expr = _rule.getExpression();
066        return expr != null ? new NotExpression(expr) : null;
067    }
068    
069    public Query getQuery()
070    {
071        Query query = _rule.getQuery();
072        return query != null ? new NotQuery(query) : null;
073    }
074    
075    @Override
076    public boolean hasOrgunitRestrictions()
077    {
078        return _rule.hasOrgunitRestrictions();
079    }
080}