Thursday, 10 October 2013

JAX-RS Joda DateTime ParamConverterProvider

I have written a JAX-RS ParamConverterProvider for the Joda DateTime class:

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

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.format.ISODateTimeFormat;

@Provider
public class DateTimeParamConverterProvider implements ParamConverterProvider {

 @Override
 public  ParamConverter getConverter(Class type, Type genericType, Annotation[] annotations) {
  if (type.equals(DateTime.class)) {
   return (ParamConverter) new DateTimeParamConverter();
  } else {
   return null;
  }

 }

 private static class DateTimeParamConverter implements ParamConverter {
  @Override
  public DateTime fromString(String value) {
   try {
    return ISODateTimeFormat.dateTimeNoMillis().parseDateTime(value);
   } catch (IllegalArgumentException e) {
    return ISODateTimeFormat.dateTime().parseDateTime(value);
   }
  }

  @Override
  public String toString(DateTime value) {
   return value.toString();
  }

 }
}

No comments:

Post a Comment