org.apache.tapestry5.util.StringToEnumCoercion Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of tapestry-core Show documentation
Show all versions of tapestry-core Show documentation
Central module for Tapestry, containing interfaces to the Java
Servlet API and all core services and components.
// Copyright 2007, 2008, 2010 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.util;
import java.util.Map;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.apache.tapestry5.ioc.internal.util.InternalUtils;
import org.apache.tapestry5.ioc.services.Coercion;
import org.apache.tapestry5.ioc.util.AvailableValues;
import org.apache.tapestry5.ioc.util.UnknownValueException;
/**
* A {@link org.apache.tapestry5.ioc.services.Coercion} for converting strings into an instance of a particular
* enumerated type. The {@link Enum#name() name} is used as the key to identify the enum instance, in a case-insensitive
* fashion.
*
* @param
* the type of enumeration
*/
public final class StringToEnumCoercion implements Coercion
{
private final Class enumClass;
private final Map stringToEnum = CollectionFactory.newCaseInsensitiveMap();
public StringToEnumCoercion(Class enumClass)
{
this(enumClass, enumClass.getEnumConstants());
}
public StringToEnumCoercion(Class enumClass, T... values)
{
this.enumClass = enumClass;
for (T value : values)
stringToEnum.put(value.name(), value);
}
public T coerce(String input)
{
if (InternalUtils.isBlank(input))
return null;
T result = stringToEnum.get(input);
if (result == null)
throw new UnknownValueException(
PublicUtilMessages.missingEnumValue(input, enumClass, stringToEnum.keySet()), new AvailableValues(
enumClass.getName() + " enum constants", stringToEnum));
return result;
}
/**
* Allows an alias value (alternate) string to reference a value.
*
* @since 5.2.2
*/
public StringToEnumCoercion addAlias(String alias, T value)
{
stringToEnum.put(alias, value);
return this;
}
public static StringToEnumCoercion create(Class enumClass)
{
return new StringToEnumCoercion(enumClass);
}
}