package org.seasar.jsf.util;

import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.component.ValueHolder;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.seasar.framework.log.Logger;

/**
 * @author higa
 *  
 */
public final class ValueHolderUtil {

	private static Logger logger_ = Logger.getLogger(ValueHolderUtil.class);

	private ValueHolderUtil() {
	}

	public static String getStringValue(FacesContext facesContext,
			UIComponent component) {

		ValueHolder valueHolder = (ValueHolder) component;
		Object value = valueHolder.getValue();
		Converter converter = valueHolder.getConverter();
		if (converter == null && value != null) {
			if (value instanceof String) {
				return (String) value;
			}
			try {
				converter = facesContext.getApplication().createConverter(
						value.getClass());
			} catch (FacesException e) {
				logger_.log(e);
			}
		}
		if (converter != null) {
			return converter.getAsString(facesContext, component, value);
		} else {
			if (value == null) {
				return "";
			} else {
				return value.toString();
			}
		}
	}
}