Skip to content

Instantly share code, notes, and snippets.

@belano
Created May 11, 2016 07:45
Show Gist options
  • Save belano/c0727a1a9ad24262f07831f408be22eb to your computer and use it in GitHub Desktop.
Save belano/c0727a1a9ad24262f07831f408be22eb to your computer and use it in GitHub Desktop.
Jersey Joda parameter converter provider
package com.belano;
import static java.lang.String.format;
import static org.joda.time.format.ISODateTimeFormat.date;
import static org.joda.time.format.ISODateTimeFormat.dateTime;
import static org.joda.time.format.ISODateTimeFormat.dateTimeNoMillis;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Provider
public class JodaParamConverterProvider implements ParamConverterProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(JodaParamConverterProvider.class);
@SuppressWarnings("unchecked")
@Override
public <T> ParamConverter<T> getConverter(Class<T> type, Type genericType, Annotation[] annotations) {
if (type.equals(DateTime.class)) {
return (ParamConverter<T>) new DateTimeParamConverter();
} else if (type.equals(LocalDate.class)) {
return (ParamConverter<T>) new LocalDateParamConverter();
}
return null;
}
static final class DateTimeParamConverter implements ParamConverter<DateTime> {
@Override
public DateTime fromString(String value) {
DateTime convertedValue = null;
if (value != null) {
try {
convertedValue = dateTimeNoMillis().parseDateTime(value);
} catch (IllegalArgumentException e) {
LOGGER.warn("Parsing exception", e);
try {
convertedValue = dateTime().parseDateTime(value);
} catch (IllegalArgumentException e2) {
throw new BadRequestException(format("Unrecognized date format: %s", value), e2);
}
}
}
return convertedValue;
}
@Override
public String toString(DateTime value) {
return value.toString();
}
}
static final class LocalDateParamConverter implements ParamConverter<LocalDate> {
@Override
public LocalDate fromString(String value) {
if (value != null) {
try {
return date().parseLocalDate(value);
} catch (IllegalArgumentException e) {
throw new BadRequestException(format("Unrecognized date format: %s", value), e);
}
} else {
return null;
}
}
@Override
public String toString(LocalDate value) {
return value.toString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment