/*
* Copyright 2009-2010 the original author or authors.
*
* 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.internna.iwebmvc.dwr;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.ConversionException;
import org.directwebremoting.convert.BeanConverter;
import org.directwebremoting.extend.InboundVariable;
import org.directwebremoting.extend.NonNestedOutboundVariable;
import org.directwebremoting.extend.OutboundContext;
import org.directwebremoting.extend.OutboundVariable;
import org.internna.iwebmvc.spring.i18n.WebContextLocale;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.MessageSource;
/**
* Converts any enum value to ant integer indicating the position inside
* the enumeration (easier to set/get in comboboxes).
*
* @author Jose Noheda
* @since 2.0
*
*/
public class I18nEnumConverter extends BeanConverter {
protected final Log logger = LogFactory.getLog(getClass());
protected MessageSource messageResolver;
@Required public void setMessageResolver(MessageSource messageResolver) {
this.messageResolver = messageResolver;
}
@Override public Object convertInbound(Class<?> paramType, InboundVariable data) throws ConversionException {
if (data.isNull() | !paramType.isEnum()) return null;
int value = Integer.parseInt(data.getValue());
return value < 0 ? null : paramType.getEnumConstants()[value];
}
@Override public OutboundVariable convertOutbound(Object data, OutboundContext outctx) {
Class<?> enumClass = data.getClass();
if (!enumClass.isEnum()) throw new ConversionException(enumClass);
int pos = -1;
Object[] enums = enumClass.getEnumConstants();
for (int index = 0; index < enums.length; index++)
if (enums[index] == data)
pos = index;
if (pos < 0) throw new ConversionException(enumClass);
return new NonNestedOutboundVariable("{position: " + pos + ", displayable: \'" + messageResolver.getMessage(enumClass.getSimpleName() + "." + ((Enum<?>) data).name(), null, WebContextLocale.getActiveLocale()) + "\'}");
}
}