RESTEasy无法识别自定义消息正文编写器 [英] RESTEasy doesn't recognize custom message body writer

查看:69
本文介绍了RESTEasy无法识别自定义消息正文编写器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MessageBodyWriter

My MessageBodyWriter

@Provider
@Produces("text/csv")
public class CSVMessageBodyWriter implements MessageBodyWriter<JaxbList>

    public static final String CONTENT_DISPOSITION_HEADER = "Content-Disposition";     
   //$NON-NLS-1$
    private final static HeaderDelegate<ContentDispositionHeader> header = RuntimeDelegate.getInstance().createHeaderDelegate(ContentDispositionHeader.class);

    public long getSize(JaxbList t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return CsvSerializer.class.isAssignableFrom(type);
    }

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

        // set content disposition. This will enable browsers to open excel
        ContentDispositionHeader contentDispositionHeader = ContentDispositionHeader.createContentDispositionHeader(MediaTypeUtils.CSV_TYPE);
        contentDispositionHeader.setFileName("representation"); //$NON-NLS-1$
        httpHeaders.putSingle(CONTENT_DISPOSITION_HEADER, header.toString(contentDispositionHeader));

        Charset charset = Charset.forName(ProviderUtils.getCharset(mediaType));
        OutputStreamWriter writer = new OutputStreamWriter(entityStream, charset);

        PrintWriter printWriter = new PrintWriter(writer);
        Iterator<String[]> rows = ((CsvSerializer) t).getEntities();
        while (rows.hasNext()) {
            printWriter.println(CsvWriter.getCSVRow(rows.next()));
        }
        printWriter.flush();
    }
}

我的REST应用程序

@Path("app/v3")
@GZIP
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "text/csv"})
 public class ApplicationREST

应用扩展

@ApplicationPath("/")
public class JaxRsActivator extends Application {

  private Set<Object> singletons = new HashSet<Object>();
  private Set<Class<?>> classes = new HashSet<Class<?>>();

  public JaxRsActivator() {
    singletons.add(new CSVMessageBodyWriter());
    classes.add(ApplicationREST.class);
  }

  @Override
  public Set<Object> getSingletons() {
    Set<Object> defaults = super.getSingletons();
    singletons.addAll(defaults);
    return singletons;
  }

  public Set<Class<?>> getClasses() {
    return classes;
  }
}

当我在调试模式下运行时,可以打我的JaxRsActivator类,因此我知道正在加载提供程序.但是我收到错误消息无法为类型为net.comp.jaxb.Jaxb的媒体对象类型为text/csv的响应对象找到MessageBodyWriter"

When I run in debug mode I can hit my JaxRsActivator class, so I know that the providers are being loaded. However I get the error "Could not find MessageBodyWriter for response object of type: net.comp.jaxb.JaxbList of media type: text/csv"

推荐答案

根据上面的代码,您的CSVMessageBodyWriter似乎正在被调用,但未通过isWriteable检查.

Based on your code above it would appear that your CSVMessageBodyWriter is being called, but it is failing your isWriteable check.

您的isWriteable检查将始终返回false.您正在检查是否可以从CSVSerializer分配JaxbList.这总是会失败,并且您的CSVMessageBodyWriter将不会被视为能够处理text/csv.

Your isWriteable check is always going to return false. You are checking if JaxbList is assignable from CSVSerializer. This is always going to fail and your CSVMessageBodyWriter will not be deemed able to handle text/csv.

尝试将isWriteable方法更改为以下内容:

Try changing your isWriteable method to the following:

public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) 
{
    return true;
}

这将序列化所有text/csv带注释的方法.如果要将其限制为JaxbList,则可以执行以下操作:

This will serialize all text/csv annotated methods. If you want to constrain it to JaxbList then you can do something like this:

public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) 
{
    ParameterizedType paramType = (ParameterizedType) genericType;

    if(paramType.getRawType().equals(JaxbList.class))
    {
        return true;
    }

    return false;
}


这是配置自定义MessageBodyWriter的简单工作示例:


Here is a simple working example of configuring a custom MessageBodyWriter:

应用

public class ProductGuideApplication extends Application
{
    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> classes = new HashSet<Class<?>>();

    public ProductGuideApplication() 
    { 
        singletons.add(new CSVMessageBodyWriter());
        classes.add(FooResource.class);
    }

    @Override
    public Set<Object> getSingletons()
    { 
        return singletons;
    }

    @Override
    public Set<Class<?>> getClasses() 
    {
        return classes;
    }
}

资源

@Path("/foo")
public class FooResource
{
    @GET
    @Produces("text/csv")
    public List<Consumer> getConsumers()
    {
        Consumer consumer1 = new Consumer();
        consumer1.setId("1234");
        consumer1.setGender("Male");

        Consumer consumer2 = new Consumer();
        consumer2.setId("2345");
        consumer2.setGender("Male");

        List<Consumer> consumers = new ArrayList<Consumer>();
        consumers.add(consumer1);
        consumers.add(consumer2);

        return consumers;
    }
}

MessageBodyWriter

@Provider
@Produces("text/csv")
public class CSVMessageBodyWriter implements MessageBodyWriter<List<Consumer>>
{
    @Override
    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) 
    {
        ParameterizedType paramType = (ParameterizedType) genericType;

        if(paramType.getRawType().equals(List.class))
        {
            if(paramType.getActualTypeArguments()[0].equals(Consumer.class))
            {
                return true;
            }
        }

        return false;
    }

    @Override
    public long getSize(List<Consumer> t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) 
    {
        return 0;
    }

    @Override
    public void writeTo(List<Consumer> t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, Object> httpHeaders,
            OutputStream entityStream) throws IOException,
            WebApplicationException 
    {
        //Write your CSV to entityStream here.
    }
}

这篇关于RESTEasy无法识别自定义消息正文编写器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆