001/*
002 *  Copyright 2025 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.core.util;
017
018import java.util.Collection;
019import java.util.Map;
020import java.util.Optional;
021
022import org.apache.commons.lang.StringUtils;
023
024import org.ametys.runtime.model.ElementDefinition;
025import org.ametys.runtime.model.ModelItem;
026import org.ametys.runtime.model.ModelItemAccessor;
027import org.ametys.runtime.model.disableconditions.DisableCondition;
028import org.ametys.runtime.model.disableconditions.VoidStaticRelativeDisableCondition;
029import org.ametys.runtime.model.exception.UndefinedItemPathException;
030
031/**
032 * {@link DisableCondition} for users and groups data
033 * Users and groups data can not be accessed by a specific object, so {@link #getStoredRelativeValue(String, Optional, Object, Map)} can not be implemented
034 */
035public class UsersAndGroupsDataDisableCondition extends VoidStaticRelativeDisableCondition
036{
037    /** The contextual parameter key for parameter's definitions */
038    public static final String DEFINITIONS_PARAMETER_KEY = "definitions";
039    /** The contextual parameter key for values prefix */
040    public static final String PREFIX_PARAMETER_KEY = "prefix";
041    
042    @Override
043    protected ModelItem getModelItem(Collection<? extends ModelItemAccessor> modelItemAccessors, String dataPath, Map<String, Object> contextualParameters) throws UndefinedItemPathException
044    {
045        // Users and groups data do not have models. Check for definition in the contextual parameters
046        @SuppressWarnings("unchecked")
047        Map<String, ? extends ElementDefinition> definitions = (Map<String, ? extends ElementDefinition>) contextualParameters.get(DEFINITIONS_PARAMETER_KEY);
048        String prefix = (String) contextualParameters.get(PREFIX_PARAMETER_KEY);
049        
050        String pathWithoutPrefix = StringUtils.removeStart(dataPath, prefix);
051        if (definitions.containsKey(pathWithoutPrefix))
052        {
053            return definitions.get(pathWithoutPrefix);
054        }
055        else
056        {
057            throw new UndefinedItemPathException("Unable to evaluate diable condition '" + dataPath + "'. This condition references a non existing data");
058        }
059    }
060}