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