cz.jalasoft.util.converter.StringConverters Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of JalasoftUtils Show documentation
Show all versions of JalasoftUtils Show documentation
A collection of utility classes that might be useful.
package cz.jalasoft.util.converter;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* Created by honzales on 18.4.15.
*/
public final class StringConverters {
public static StringConverter identity() {
return new StringConverter() {
@Override
public String convert(String from) throws ConversionException {
return from;
}
};
}
public static StringConverter toInteger() {
return new StringConverter() {
@Override
public Integer convert(String from) throws ConversionException {
try {
return Integer.parseInt(from);
} catch (NumberFormatException exc) {
throw new ConversionException(from, String.class, Integer.class);
}
}
};
}
public static StringConverter toLong() {
return new StringConverter() {
@Override
public Long convert(String from) throws ConversionException {
try {
return Long.parseLong(from);
} catch (NumberFormatException exc) {
throw new ConversionException(from, String.class, Long.class);
}
}
};
}
public static StringConverter toDouble() {
return new StringConverter() {
@Override
public Double convert(String from) throws ConversionException {
try {
return Double.parseDouble(from);
} catch (NumberFormatException exc) {
throw new ConversionException(from, String.class, Double.class);
}
}
};
}
public static StringConverter toIntegerOrElse(final StringConverter alternative) {
return new StringConverter() {
@Override
public Integer convert(String from) throws ConversionException {
try {
return Integer.parseInt(from);
} catch (NumberFormatException exc) {
return alternative.convert(from);
}
}
};
}
public static StringConverter valueIfStringEqualTo(final String pattern, final T value) {
return new StringConverter() {
@Override
public T convert(String from) throws ConversionException {
if (from.equals(pattern)) {
return value;
} else {
throw new ConversionException(from, String.class, Object.class);
}
}
};
}
public static StringConverter toDateTime(final String pattern) {
return new StringConverter() {
@Override
public DateTime convert(String from) throws ConversionException {
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
return DateTime.parse(from, formatter);
}
};
}
private StringConverters() {}
}