001/*
002 *  Copyright 2022 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.core.ui.util;
017
018import java.util.ArrayList;
019import java.util.List;
020import java.util.Map;
021
022import org.apache.avalon.framework.component.Component;
023import org.apache.avalon.framework.service.ServiceException;
024import org.apache.avalon.framework.service.ServiceManager;
025import org.apache.avalon.framework.service.Serviceable;
026
027import org.ametys.core.ui.Callable;
028import org.ametys.runtime.i18n.I18nizableText;
029import org.ametys.runtime.model.Enumerator;
030
031/**
032 * Helper for getting entries from a given enumerator
033 */
034public class ParameterEnumeratorHelper implements Component, Serviceable
035{
036    /** Avalon role */
037    public static final String ROLE = ParameterEnumeratorHelper.class.getName();
038        
039    private ServiceManager _manager;
040    
041    @Override
042    public void service(ServiceManager manager) throws ServiceException
043    {
044        _manager = manager;
045    }
046
047    /**
048     * Provides the enumerated values with their optional label.
049     * @param enumeratorRole enumerator role
050     * @return the enumerated values and their label.
051     * @throws Exception if an error occurs.
052     */
053    @Callable
054    public Map<String, Object> getTypedEntries(String enumeratorRole) throws Exception
055    {
056        List<Map<String, Object>> entries = new ArrayList<>();
057        Enumerator enumerator = (Enumerator) _manager.lookup(enumeratorRole);
058        Map<String, I18nizableText> typedEntries = enumerator.getTypedEntries();
059        
060        for (Map.Entry<String, I18nizableText> entry : typedEntries.entrySet())
061        {
062            entries.add(Map.of("id", entry.getKey(), "label", entry.getValue()));
063        }
064        return Map.of("data", entries, "success", true);
065    }
066    
067}