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.data.ContentValue;
023import org.ametys.odf.program.Program;
024import org.ametys.plugins.repository.query.expression.Expression;
025import org.ametys.plugins.repository.query.expression.Expression.Operator;
026import org.ametys.plugins.repository.query.expression.StringExpression;
027
028/**
029 * Metadata restriction rule
030 */
031public class OdfMetadataRestrictionRule implements OdfRestrictionRule
032{
033    private final String _metadataPath;
034    private final String _value;
035    
036    /**
037     * Constructor for rule relating to the value of a metadata
038     * @param metadataPath The path of metadata
039     * @param value The metadata value
040     */
041    public OdfMetadataRestrictionRule(String metadataPath, String value)
042    {
043        _metadataPath = metadataPath;
044        _value = value;
045    }
046    
047    @Override
048    public Expression getExpression()
049    {
050        return new StringExpression(_metadataPath, Operator.EQ, _value);
051    }
052    
053    @Override
054    public boolean contains(Program program)
055    {
056        return Optional.ofNullable(program.getValue(_metadataPath))
057                       .map(value -> Arrays.asList(value))
058                       .orElse(Collections.EMPTY_LIST)
059                       .stream()
060                       .anyMatch(value -> value.equals(_value) || value instanceof ContentValue && ((ContentValue) value).getContentId().equals(_value));
061    }
062    
063    @Override
064    public boolean hasOrgunitRestrictions()
065    {
066        return false;
067    }
068}