阅读泽西的ParamConverter中的另一个参数

时间:2014-12-20 20:42:45

标签: java jersey jax-rs jersey-2.0

我创建了一个ParamConverter,当给定一个格式化为Instant的原生ISO-8601的字符串时,它提供Instant(日期),或者作为自纪元以来的整数毫秒。这工作正常,但我还需要能够支持其他日期格式(客户很挑剔)。

为避免经典dd/mm/yyyy vs mm/dd/yyyy歧义,我希望客户指定其首选格式作为请求*的一部分。 e.g:

GET http://api.example.com/filter?since=01/02/2000&dateformat=dd/mm/yyyy

传递给一个看似如下的方法:

@GET
String getFilteredList( final @QueryParam( "since" ) Instant since ) {
    ...
}

(为清楚起见省略了时间和时区部分)

所以我希望我的ParamConverter<Instant>能够阅读dateformat参数。

我已经能够使用设置ContainerRequestContext属性的过滤器和AbstractValueFactoryProvider的组合来做类似的事情,但是这需要参数来应用自定义注释并且不会让它与QueryParam / FormParam / etc一起使用,使它变得不那么有用了。

有没有办法从ParamConverter中获取其他参数或请求对象本身?

[*]在现实世界中,这将来自一系列预先批准的格式,但现在只是假设他们正在为DateTimeFormatter 提供输入


为清楚起见,这是我的代码:

public class InstantParameterProvider implements ParamConverterProvider {
    private static final ParamConverter<Instant> INSTANT_CONVERTER =
            new ParamConverter<Instant>( ) {
                @Override public final T fromString( final String value ) {
                    // This is where I would like to get the other parameter's value
                    // Is it possible?
                }

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

    @SuppressWarnings( "unchecked" )
    @Override public <T> ParamConverter<T> getConverter(
            final Class<T> rawType,
            final Type genericType,
            final Annotation[] annotations
    ) {
        if( rawType == Instant.class ) {
            return (ParamConverter<T>) INSTANT_CONVERTER;
        }
        return null;
    }
}

1 个答案:

答案 0 :(得分:5)

如上所述here,关键是注入一些带有javax.inject.Provider的上下文对象,这允许我们懒惰地检索对象。由于ParamConverterProvider是Jersey管理的组件,我们应该能够注入其他组件。

问题是我们需要的组件将在请求范围内。为了解决这个问题,我们将javax.inject.Provider<UriInfo>注入提供者。当我们实际调用get()中的Provider来获取UriInfo的实际实例时,它将在请求中。对于需要请求范围的任何其他组件也是如此。

例如

public class InstantParamProvider implements ParamConverterProvider {

    @Inject
    private javax.inject.Provider<UriInfo> uriInfoProvider;

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

        if (rawType != Instant.class) return null; 

        return new ParamConverter<T>() {
            @Override
            public T fromString(String value) {
                UriInfo uriInfo = uriInfoProvider.get();
                String format = uriInfo.getQueryParameters().getFirst("date-format");

                if (format == null) {
                     throw new WebApplicationException(Response.status(400)
                             .entity("data-format query parameter required").build());
                } else {
                    try {
                        // parse and return here
                    } catch (Exception ex) {
                        throw new WebApplicationException(
                            Response.status(400).entity("Bad format " + format).build());
                    }
                }
            }

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

更新

以下是使用Jersey Test Framework

的完整示例
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;

import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;

import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.matchers.JUnitMatchers.*;

public class LocalDateTest extends JerseyTest {

    public static class LocalDateParamProvider implements ParamConverterProvider {

        @Inject
        private javax.inject.Provider<UriInfo> uriInfoProvider;

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

            if (rawType != LocalDate.class) {
                return null;
            }
            return new ParamConverter<T>() {
                @Override
                public T fromString(String value) {
                    UriInfo uriInfo = uriInfoProvider.get();
                    String format = uriInfo.getQueryParameters().getFirst("date-format");

                    if (format == null) {
                        throw new WebApplicationException(Response.status(400)
                                .entity("date-format query parameter required").build());
                    } else {
                        try {
                            return (T) LocalDate.parse(value, DateTimeFormatter.ofPattern(format));
                            // parse and return here
                        } catch (Exception ex) {
                            throw new WebApplicationException(
                                    Response.status(400).entity("Bad format " + format).build());
                        }
                    }
                }

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

    @Path("localdate")
    public static class LocalDateResource {

        @GET
        public String get(@QueryParam("since") LocalDate since) {
            return since.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"));
        }
    }

    @Override
    public ResourceConfig configure() {
        return new ResourceConfig(LocalDateResource.class)
                .register(LocalDateParamProvider.class)
                .register(new LoggingFilter(Logger.getAnonymousLogger(), true));
    }

    @Test
    public void should_return_bad_request_with_bad_format() {
        Response response = target("localdate")
                .queryParam("since", "09/20/2015")
                .queryParam("date-format", "yyyy/MM/dd")
                .request().get();
        assertEquals(400, response.getStatus());
        assertThat(response.readEntity(String.class), containsString("format yyyy/MM/dd"));
        response.close();
    }

    @Test
    public void should_return_bad_request_with_no_date_format() {
        Response response = target("localdate")
                .queryParam("since", "09/20/2015")
                .request().get();
        assertEquals(400, response.getStatus());
        assertThat(response.readEntity(String.class), containsString("query parameter required"));
        response.close();
    }

    @Test
    public void should_succeed_with_correct_format() {
        Response response = target("localdate")
                .queryParam("since", "09/20/2015")
                .queryParam("date-format", "MM/dd/yyyy")
                .request().get();
        assertEquals(200, response.getStatus());
        assertThat(response.readEntity(String.class), containsString("09/20/2015"));
        response.close();
    }
}

这是测试依赖

<dependency>
    <groupId>org.glassfish.jersey.test-framework.providers</groupId>
    <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
    <version>${jersey2.version}</version>
    <scope>test</scope>
</dependency>