Dav*_*ave 6 java jax-rs jersey jersey-2.0
当给定一个格式化为Instant的原生ISO-8601的字符串时,或者作为自纪元以来的整数毫秒,我ParamConverter提供了一个Instant(Date).这工作正常,但我还需要能够支持其他日期格式(客户很挑剔).
为了避免经典dd/mm/yyyy与mm/dd/yyyy歧义,我希望客户指定他们的首选格式作为请求*的一部分.例如:
GET http://api.example.com/filter?since=01/02/2000&dateformat=dd/mm/yyyy
Run Code Online (Sandbox Code Playgroud)
传递给一个看起来像这样的方法:
@GET
String getFilteredList( final @QueryParam( "since" ) Instant since ) {
...
}
Run Code Online (Sandbox Code Playgroud)
(为清楚起见省略了时间和时区部分)
所以我希望我ParamConverter<Instant>能够读取dateformat参数.
我已经能够使用设置ContainerRequestContext属性的过滤器和AbstractValueFactoryProvider类似的东西的组合,但是需要参数来应用自定义注释,并且不允许它与QueryParam/FormParam /等一起使用.它没那么有用了.
有没有办法从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;
}
}
Run Code Online (Sandbox Code Playgroud)
正如这里提到的,关键是注入一些上下文对象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();
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
这是使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是测试依赖
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>${jersey2.version}</version>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3459 次 |
| 最近记录: |