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.Arrays;
019import java.util.Collections;
020import java.util.Optional;
021
022import org.ametys.cms.search.query.Query;
023import org.ametys.cms.search.query.StringQuery;
024import org.ametys.odf.program.Program;
025import org.ametys.plugins.repository.query.expression.Expression;
026import org.ametys.plugins.repository.query.expression.Expression.Operator;
027import org.ametys.plugins.repository.query.expression.StringExpression;
028import org.ametys.runtime.model.type.ElementType;
029
030/**
031 * Attribute restriction rule
032 */
033public class OdfAttributeRestrictionRule implements OdfRestrictionRule
034{
035    private final String _attributePath;
036    private final String _untypedValue;
037    
038    /**
039     * Constructor for rule relating to the value of an attribute
040     * @param attributePath The path of the attribute
041     * @param untypedValue The attribute untyped value
042     */
043    public OdfAttributeRestrictionRule(String attributePath, String untypedValue)
044    {
045        _attributePath = attributePath;
046        _untypedValue = untypedValue;
047    }
048    
049    @Override
050    public Expression getExpression()
051    {
052        return new StringExpression(_attributePath, Operator.EQ, _untypedValue);
053    }
054    
055    public Query getQuery()
056    {
057        return new StringQuery(_attributePath, _untypedValue);
058    }
059    
060    @Override
061    public boolean contains(Program program)
062    {
063        ElementType type = (ElementType) program.getDefinition(_attributePath).getType();
064        Object typedValue = type.castValue(_untypedValue);
065        
066        return Optional.ofNullable(program.getValue(_attributePath))
067                       .map(value -> Arrays.asList(value))
068                       .orElse(Collections.EMPTY_LIST)
069                       .stream()
070                       .anyMatch(value -> value.equals(typedValue));
071    }
072    
073    @Override
074    public boolean hasOrgunitRestrictions()
075    {
076        return false;
077    }
078}