I am updating my application from Wicket 1.4.18 to Wicket 6.2 and my
currency converter no longer works once I add the generics into it. I am
using the converter to allow the user to enter an amount of money. The
problem is that when something like "asdfasdf" is entered, I get an
exception like this:
java.lang.ClassCastException: java.lang.String cannot be cast to
java.lang.Number
at
org.apache.wicket.util.convert.converter.AbstractNumberConverter.convertToString(AbstractNumberConverter.java:31)
Is there a currency converter already in Wicket that I haven't seen?
Does anybody have a good example of a working converter for currency in
Wicket 6.x?
Here is my code from 1.4 that was working:
public class CurrencyConverter extends AbstractNumberConverter {
private static final long serialVersionUID = 1L;
public CurrencyConverter() {
}
@Override
public NumberFormat getNumberFormat(Locale locale) {
return NumberFormat.getCurrencyInstance(locale);
}
@Override
public Class<?> getTargetType() {
return Double.class;
}
public Object convertToObject(String value, Locale locale) {
try {
if(value.startsWith("$")) {
value = value.replace("$", "");
}
value = String.valueOf( Double.valueOf( value ) * 100 );
value = "$" + value;
return getNumberFormat(locale).parse(value).doubleValue();
} catch (ParseException ex) {
ConversionException conv = new ConversionException("'" +
value + "' is not a valid dollar amount.");
conv.setResourceKey("CurrencyConverter");
throw conv;
} catch(NumberFormatException ex){
ConversionException conv = new ConversionException("'" +
value + "' is not a valid dollar amount.");
conv.setResourceKey("CurrencyConverter");
throw conv;
}
}
@Override
public String convertToString(Object value, Locale locale) {
if( value == null )
return null;
int cents;
if( value instanceof Integer ) {
cents = (Integer) value;
return getNumberFormat(locale).format((double) cents / 100.0);
} else if( value instanceof String ) {
cents = Integer.parseInt( (String) value );
return getNumberFormat(locale).format((double) cents / 100.0);
}
return value.toString();
}
}
--
Jered Myers