我想在泽西岛使用Joda的DateTime
作为查询参数,但泽西开箱即用不支持。我假设实现InjectableProvider
是添加DateTime
支持的正确方法。
有人能指出我对InjectableProvider
DateTime
的良好实施吗?或者是否有值得推荐的替代方法? (我知道我可以在代码中转换Date
或String
,但这似乎是一个较小的解决方案。)
感谢。
解决方案:
我在下面修改了Gili的答案,在JAX-RS而不是Guice中使用@Context
注入机制。
更新:如果未在服务方法参数中注入UriInfo,则可能无法正常工作。
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;
import java.util.List;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import org.joda.time.DateTime;
/**
* Enables DateTime to be used as a QueryParam.
* <p/>
* @author Gili Tzabari
*/
@Provider
public class DateTimeInjector extends PerRequestTypeInjectableProvider<QueryParam, DateTime>
{
private final UriInfo uriInfo;
/**
* Creates a new DateTimeInjector.
* <p/>
* @param uriInfo an instance of {@link UriInfo}
*/
public DateTimeInjector( @Context UriInfo uriInfo)
{
super(DateTime.class);
this.uriInfo = uriInfo;
}
@Override
public Injectable<DateTime> getInjectable(final ComponentContext cc, final QueryParam a)
{
return new Injectable<DateTime>()
{
@Override
public DateTime getValue()
{
final List<String> values = uriInfo.getQueryParameters().get(a.value());
if( values == null || values.isEmpty())
return null;
if (values.size() > 1)
{
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).
entity(a.value() + " may only contain a single value").build());
}
return new DateTime(values.get(0));
}
};
}
}
答案 0 :(得分:5)
这是一个依赖于Guice的实现。您可以使用不同的进样器进行微小修改:
import com.google.inject.Inject;
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;
import java.util.List;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import org.joda.time.DateTime;
/**
* Enables DateTime to be used as a QueryParam.
* <p/>
* @author Gili Tzabari
*/
@Provider
public class DateTimeInjector extends PerRequestTypeInjectableProvider<QueryParam, DateTime>
{
private final com.google.inject.Provider<UriInfo> uriInfo;
/**
* Creates a new DateTimeInjector.
* <p/>
* @param uriInfo an instance of {@link UriInfo}
*/
@Inject
public DateTimeInjector(com.google.inject.Provider<UriInfo> uriInfo)
{
super(DateTime.class);
this.uriInfo = uriInfo;
}
@Override
public Injectable<DateTime> getInjectable(final ComponentContext cc, final QueryParam a)
{
return new Injectable<DateTime>()
{
@Override
public DateTime getValue()
{
final List<String> values = uriInfo.get().getQueryParameters().get(a.value());
if (values.size() > 1)
{
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).
entity(a.value() + " may only contain a single value").build());
}
if (values.isEmpty())
return null;
return new DateTime(values.get(0));
}
};
}
}
没有Guice绑定。 @Provider是一个JAX-RS注释。 Guice只需要能够注入UriInfo,Jersey-Guice提供绑定。
答案 1 :(得分:2)
处理客户端 - 服务器之间发送Joda DateTime对象的另一个选择是使用适配器和相应的注释显式地编组/解组它们。 原理是将其编组为Long对象,而解组则使用Long对象为构造函数调用实例化新的DateTime对象。 Long对象是通过getMillis方法获得的。 要使其工作,请指定要在具有DateTime对象的类中使用的适配器:
@XmlElement(name="capture_date")
@XmlJavaTypeAdapter(XmlDateTimeAdapter.class)
public DateTime getCaptureDate() { return this.capture_date; }
public void setCaptureDate(DateTime capture_date) { this.capture_date = capture_date; }
然后编写适配器和XML类来封装Long对象:
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
/**
* Convert between joda datetime and XML-serialisable millis represented as long
*/
public class XmlDateTimeAdapter extends XmlAdapter<XmlDateTime, DateTime> {
@Override
public XmlDateTime marshal(DateTime v) throws Exception {
if(v != null)
return new XmlDateTime(v.getMillis());
else
return new XmlDateTime(0);
}
@Override
public DateTime unmarshal(XmlDateTime v) throws Exception {
return new DateTime(v.millis, DateTimeZone.UTC);
}
}
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* XML-serialisable wrapper for joda datetime values.
*/
@XmlRootElement(name="joda_datetime")
public class XmlDateTime {
@XmlElement(name="millis") public long millis;
public XmlDateTime() {};
public XmlDateTime(long millis) { this.millis = millis; }
}
如果全部按计划进行,则应使用适配器对DateTime对象进行编组/解组;通过在适配器中设置断点来检查这一点。
答案 2 :(得分:1)
从阅读the documentation开始,您似乎需要让您的方法返回一个String,然后转换为DateTime,我想使用DateTime(long) constructor,有一个(相对)易于关注example at codehale,如果您希望我参与其中,请与我联系。
答案 3 :(得分:1)
@ Gili,抱歉,我没有直接评论你的帖子所需的声誉,但是你可以请:
非常感谢你。
微米。
<强>问题强>:
我有兴趣和HolySamosa一样,我也使用Guice,但我面对以下问题。
如果我添加:
bind(DateTimeInjector.class);
在我的GuiceServletContextListener
中,我得到了:
java.lang.RuntimeException:
The scope of the component class com.foo.mapping.DateTimeInjector must be a singleton
如果我在@Singleton
课程上添加DateTimeInjector
,我会得到:
GRAVE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for method public java.util.List com.foo.ThingService.getThingByIdAndDate(java.lang.String,org.joda.time.DateTime) at parameter at index 1
SEVERE: Method, public java.util.List com.foo.ThingService.getThingByIdAndDate(java.lang.String,org.joda.time.DateTime), annotated with GET of resource, class com.foo.ThingService, is not recognized as valid resource method.
建议/解决方案:
@PathParam
而不是@QueryParam
。UriInfo uriInfo
。只是功能参数应该足够,无论是否存在UriInfo
,它都应该有效。示例:
// Configure Jersey with Guice:
Map<String, String> settings = new HashMap<String, String>();
settings.put(PackagesResourceConfig.PROPERTY_PACKAGES, "com.foo.mapping");
serve("/*").with(GuiceContainer.class, settings);
完整解决方案:
import java.util.List;
import javax.ws.rs.PathParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import org.joda.time.DateTime;
import com.google.inject.Inject;
import com.foo.utils.DateTimeAdapter;
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;
/**
* Enables DateTime to be used as a PathParam.
*/
@Provider
public class DateTimeInjector extends PerRequestTypeInjectableProvider<PathParam, DateTime> {
private final com.google.inject.Provider<UriInfo> uriInfo;
/**
* Creates a new DateTimeInjector.
*
* @param uriInfo
* an instance of {@link UriInfo}
*/
@Inject
public DateTimeInjector(com.google.inject.Provider<UriInfo> uriInfo) {
super(DateTime.class);
this.uriInfo = uriInfo;
}
@Override
public Injectable<DateTime> getInjectable(final ComponentContext context, final PathParam annotation) {
return new Injectable<DateTime>() {
@Override
public DateTime getValue() {
final List<String> values = uriInfo.get().getPathParameters().get(annotation.value());
if (values == null) {
throwInternalServerError(annotation);
}
if (values.size() > 1) {
throwBadRequestTooManyValues(annotation);
}
if (values.isEmpty()) {
throwBadRequestMissingValue(annotation);
}
return parseDate(annotation, values);
}
private void throwInternalServerError(final PathParam annotation) {
String errorMessage = String.format("Failed to extract parameter [%s] using [%s]. This is likely to be an implementation error.",
annotation.value(), annotation.annotationType().getName());
throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build());
}
private void throwBadRequestTooManyValues(final PathParam annotation) {
String errorMessage = String.format("Parameter [%s] must only contain one single value.", annotation.value());
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(errorMessage).build());
}
private void throwBadRequestMissingValue(final PathParam annotation) {
String errorMessage = String.format("Parameter [%s] must be provided.", annotation.value());
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(errorMessage).build());
}
private DateTime parseDate(final PathParam annotation, final List<String> values) {
try {
return DateTimeAdapter.parse(values.get(0));
} catch (Exception e) {
String errorMessage = String.format("Parameter [%s] is formatted incorrectly: %s", annotation.value(), e.getMessage());
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(errorMessage).build());
}
}
};
}
}