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