2012-09-14 69 views
0

我正在试验api verioning,并有一个非常特殊的要求。我们将使用内容协商,即@Produces注解为此,我想要一个像@Produces({“th/v1-v10 + xml”})格式的自定义媒体类型,其中v1-v10告诉我这个api将以“th/v1 + xml”,“th/v2 + xml”的Accept标头一直到“th/v10 + xml”的方式提供任何请求。@ Produces /提供者媒体类型匹配

我知道这有点奇怪,但是我们的想法是,我们在生产中制作的每一滴水都将成为客户端的新版本,但并不是每一项服务都会被修改。所以我想用范围来注释服务,这样即使没有更改,我也不必为每一滴都复制它。

所以我想知道的是有什么办法可以拦截在泽西登录,而它匹配的@Path和@Produces注释?我知道我不能使用正则表达式来匹配媒体类型。

.......

了些研究告诉我,泽西调用MediaType.isCompatible(其他的MediaType)方法来确定兼容性的要求接受头部和服务提供商的媒体类型。

如果我可以创建自定义MediaType并覆盖isCompatible方法,可能可以利用这一点。泽西是否允许这种扩展?

任何帮助,非常感谢。

回答

0

您可能应该使用自定义响应映射器。

1.-创建负责编写响应

@Provider 
public class MyResponseTypeMapper 
    implements MessageBodyWriter<MyResponseObjectType> { 
    @Override 
    public boolean isWriteable(final Class<?> type,final Type genericType, 
       final Annotation[] annotations, 
       final MediaType mediaType) { 
     ... use one of the arguments (either the type, an annotation or the MediaType) 
      to guess if the object shoud be written with this class 
    } 
    @Override 
    public long getSize(final MyResponseObjectType myObjectTypeInstance, 
        final Class<?> type,final Type genericType, 
         final Annotation[] annotations, 
        final MediaType mediaType) { 
     // return the exact response length if you know it... -1 otherwise 
     return -1; 
    } 
    @Override 
    public void writeTo(final MyResponseObjectType myObjectTypeInstance, 
        final Class<?> type,final Type genericType, 
        final Annotation[] annotations, 
        final MediaType mediaType, 
        final MultivaluedMap<String,Object> httpHeaders, 
        final OutputStream entityStream) throws IOException,                 WebApplicationException { 
     ... serialize/marshall the MyResponseObjectType instance using 
      whatever you like (jaxb, etC) 
     entityStream.write(serializedObj.getBytes()); 
    } 
} 

2:注册映射器在您的应用程序的执行MessageBodyWriter类

public class MyRESTApp 
    extends Application { 
    @Override 
public Set<Class<?>> getClasses() { 
     Set<Class<?>> s = new HashSet<Class<?>>(); 
     s.add(MyResponseTypeMapper.class); 
     return s; 
    } 
} 

泽西会扫描所有已注册的映射器调用它们isWriteable ()方法,直到一个返回true ...如果是,则使用此MessageBodyWriter实例将内容序列化到客户端