从Jersey ExceptionMapper生成JSONP

时间:2014-04-26 17:25:36

标签: java jersey jax-rs jersey-2.0

我有一个返回JAXB映射对象的Jersey资源,当我使用Accept标头请求时,Jersey使用Moxy插件将此对象序列化为XML,JSON或JSONP。

@GET
@JSONP( queryParam = "callback" )
@Produces( { "application/javascript", "application/json", "application/xml" } )
public Settings get()
{
   if( someCondition )
        throw new NotFoundExcpetion();
    Settings settings = new Settings();
    settings.setSomeKey( "some value" );
    return settings;
}

如果该方法产生异常,我有一个类似下面的ExceptionHandler,它将产生一个包含错误细节的响应。

@Provider
public class NotFoundExceptionMapper implements
      ExceptionMapper<NotFoundException>
{

    @Override
    public Response toResponse( NotFoundException ex )
    {
        return Response.status( 404 )
              .entity( ex.getMessage() )
              .entity( new ErrorStatus( 404 ) )
              .build();
    }
}

但是,当客户端请求生成异常的资源并请求Accept标头为application/javascript的JSONP时,我会收到以下异常。

org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/javascript, type=class com.myproject.api.dom.ErrorStatus, genericType=class com.myproject.api.dom.ErrorStatus.
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:247)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:103)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:88)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1154)
    at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:571)
    at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:378)
    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:418)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:265)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:320)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1028)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:219)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.myproject.api.servlet.TransactionFilter.doFilter(TransactionFilter.java:43)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

所以问题是,如何在请求时获取ExceptionHandler来生成JSONP响应?

2 个答案:

答案 0 :(得分:1)

问题是com.myproject.api.dom.ErrorStatus类型的实体。如果这是@XmlRootElement注释类,则Jersey知道如何将其转换为application/jsonapplication/xml,而不是application/javascript

您需要为此实体提供MessageBodyWriter

@Provider
@Produces("application/javascript")
public class ErrorStatusMessageBodyWriter implements MessageBodyWriter<ErrorStatus> {
  ...
}

我没有测试是否可以使用@JSONP注释此提供程序。否则你必须手动填充。

答案 1 :(得分:0)

我有一个来自@lefloh建议的解决方案,我只是扩展了MOXyJsonProvider并在writeTo方法中添加了我自己的填充。缺点是它与泽西岛的@JSONP注释不兼容,因此资源上的注释现在是多余的。欢迎任何更好的解决方案。

@Provider
@Produces( { "application/javascript", "application/x-javascript" } )
public class JsonMessageBodyWriter extends MOXyJsonProvider
{

    private static final MediaType APPLICATION_JAVASCRIPT = new MediaType( "application", "javascript" );
    private static final MediaType APPLICATION_XJAVASCRIPT = new MediaType( "application", "x-javascript" );

    @Context
    private HttpServletRequest httpRequest;


    @Override
    protected boolean supportsMediaType( MediaType mediaType )
    {
        if( mediaType.equals( APPLICATION_JAVASCRIPT ) ||
              mediaType.equals( APPLICATION_XJAVASCRIPT ) )
            return true;
        return false;
    }


    @Override
    public void writeTo( Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
          MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream ) throws IOException, WebApplicationException
    {

        String callback = httpRequest.getParameter( "callback" );
        if( callback == null )
            callback = "callback";

        entityStream.write( callback.getBytes() );
        entityStream.write( "(".getBytes() );
        super.writeTo( object, type, genericType, annotations, mediaType, httpHeaders, entityStream );
        entityStream.write( ")".getBytes() );
    }

}