/*
* Copyright 2004, 2005, 2006 Odysseus Software GmbH
*
* 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 de.odysseus.calyxo.forms.convert;
import java.text.Format;
import java.text.ParsePosition;
import java.text.ParseException;
import java.util.Locale;
/**
* Format based converter.
*
* @author Christoph Beck
* @author Oliver Stuhr
*/
public abstract class FormatBasedConverter extends SimpleConverter {
private Format format;
private String formattedNull;
private Object parsedNullOrEmpty;
/**
* Default Constructor.
*/
protected FormatBasedConverter() {
this(null, "");
}
/**
* Constructor.
* @param parsedEmptyString empty string is converted into this value
* @param formattedNull null is formatted into this value
*/
protected FormatBasedConverter(Object parsedEmptyString, String formattedNull) {
setParsedNullOrEmpty(parsedEmptyString);
setFormattedNull(formattedNull);
}
/**
* Cretate new format instamce
*/
protected abstract Format createFormat(Locale locale);
/**
* Get format instance.
* Lazily initialize format using {@link #createFormat(Locale)} (using default locale)
*/
protected Format getFormat() {
if (format == null) {
setFormat(createFormat(Locale.getDefault()));
}
return format;
}
protected String getFormattedNull() {
return formattedNull;
}
protected void setFormattedNull(String formattedNull) {
this.formattedNull = formattedNull;
}
protected Object getParsedNullOrEmpty() {
return parsedNullOrEmpty;
}
protected void setParsedNullOrEmpty(Object parsedNullOrEmpty) {
this.parsedNullOrEmpty = parsedNullOrEmpty;
}
protected void setFormat(Format format) {
this.format = format;
}
/**
* Localize the receiver
*/
public void localize(Locale locale) {
setFormat(createFormat(locale));
}
/**
* Format method.
*/
public String format(Object value) {
return value == null ? formattedNull : getFormat().format(value);
}
/**
* Parse method.
*/
public Object parse(String value) throws ParseException {
if (value == null || value.length() == 0)
return parsedNullOrEmpty;
else if (value.equals(formattedNull))
return null;
else {
ParsePosition pos = new ParsePosition(0);
Object result = getFormat().parseObject(value, pos);
if (pos.getIndex() < value.length())
throw new ParseException("Found garbage suffix!", pos.getIndex());
return result;
}
}
}