@DefaultValue in JAX-RS for dates: now() and MAX

半世苍凉 提交于 2019-12-12 10:07:35

问题


I have a query parameter as following:

@GET
public Response myFunction(@QueryParam("start") final LocalDate start, @QueryParam("end") final LocalDate end) { ... }

For this, I created a ParamConverter<LocalDate> which converts a string to a date, and vice versa.

Now I want to use @DefaultValue annotation to declare a default value. I have two special default values:

  • today (for start)
  • the maximum value/infinity (for end)

Is it possible to use the @DefaultValue annotation for this? How?


回答1:


Yes, @DefaultValue value can be used in this situation:

@GET
public Response foo(@QueryParam("start") @DefaultValue("today") LocalDate start,
                    @QueryParam("end") @DefaultValue("max") LocalDate end) { 

    ...
}

Your ParamConverterProvider and ParamConverter implementations can be like:

@Provider
public class LocalDateParamConverterProvider implements ParamConverterProvider {

    @Override
    public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, 
                                              Annotation[] annotations) {

        if (rawType.getName().equals(LocalDate.class.getName())) {

            return new ParamConverter<T>() {

                @Override
                public T fromString(String value) {
                    return parseString(value, rawType);
                }

                @Override
                public String toString(T value) {
                    return ((LocalDateTime) value)
                            .format(DateTimeFormatter.ISO_LOCAL_DATE);
                }
            };
        }

        return null;
    }

    private <T> T parseString(String value, Class<T> rawType) {

        if (value == null) {
            return null;
        }

        if ("today".equalsIgnoreCase(value)) {
            return rawType.cast(LocalDate.now());
        }

        if ("max".equalsIgnoreCase(value)) {
            return rawType.cast(LocalDate.of(9999, 12, 31));
        }

        try {
            return rawType.cast(LocalDate.parse(value, 
                    DateTimeFormatter.ISO_LOCAL_DATE));
        } catch (Exception e) {
            throw new BadRequestException(e);
        }
    }
}

If, for some reason, you need the parameter name, you can get it from the Annotation array:

Optional<Annotation> optional = Arrays.stream(annotations)
        .filter(annotation -> annotation.annotationType().equals(QueryParam.class))
        .findFirst();

if (optional.isPresent()) {
    QueryParam queryParam = (QueryParam) optional.get();
    String parameterName = queryParam.value();
}


来源:https://stackoverflow.com/questions/48114283/defaultvalue-in-jax-rs-for-dates-now-and-max

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!