001// Copyright 2010 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007// http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.commons.util;
016
017import java.util.Collection;
018import java.util.Collections;
019import java.util.List;
020import java.util.Map;
021
022import org.apache.tapestry5.commons.internal.util.InternalCommonsUtils;
023
024/**
025 * Used (as part of a {@link UnknownValueException} to identify what available values
026 * are present.
027 * 
028 * @since 5.2.0
029 */
030public class AvailableValues
031{
032    private final String valueType;
033
034    private final List<String> values;
035
036    /**
037     * @param valueType
038     *            a word or phrase that describes what the values are such as "component types" or "service ids"
039     *@param values
040     *            a set of objects defining the values; the values will be converted to strings and sorted into
041     *            ascending order
042     */
043    public AvailableValues(String valueType, Collection<?> values)
044    {
045        this.valueType = valueType;
046        this.values = sortValues(values);
047    }
048
049    public AvailableValues(String valueType, Map<?, ?> map)
050    {
051        this(valueType, map.keySet());
052    }
053
054    private static List<String> sortValues(Collection<?> values)
055    {
056        List<String> result = CollectionFactory.newList();
057
058        for (Object v : values)
059        {
060            result.add(String.valueOf(v));
061        }
062
063        Collections.sort(result);
064
065        return Collections.unmodifiableList(result);
066    }
067
068    /** The type of value, i.e., "component types" or "service ids". */
069    public String getValueType()
070    {
071        return valueType;
072    }
073
074    /** The values, as strings, in sorted order. */
075    public List<String> getValues()
076    {
077        return values;
078    }
079
080    @Override
081    public String toString()
082    {
083        return String.format("AvailableValues[%s: %s]", valueType, InternalCommonsUtils.join(values));
084    }
085
086}