当前位置: 首页 > 知识库问答 >
问题:

发送响应时未使用MessageBodyWriter

冉伯寅
2023-03-14

我用JacksonAnnotationIntrospector设置了一个自定义注释,以便根据API版本吐出正确的属性名称。根据API版本,有一个助手类可以输出正确的ObjectMapper。

public class ObjectMapperFactory {

  private static final ObjectMapper objectMapper_V1 = new ObjectMapper().setAnnotationIntrospector(new VersioningPropertiesIntrospector(Entity.ApiVersion.V1));
  private static final ObjectMapper objectMapper_V2016 = new ObjectMapper().setAnnotationIntrospector(new VersioningPropertiesIntrospector(Entity.ApiVersion.V2016));

  public static ObjectMapper getObjectMapper(Entity.ApiVersion version) {
    switch (version) {
        case V1:
            return objectMapper_V1;

        case V2016:
            return objectMapper_V2016;

        case INVALID:
            return null;
    }

    return null;
  }
}

还有一个帮助函数用于测试序列化

public static String serializeEntity(Entity.ApiVersion version, Object object) {
    try {
        return getObjectMapper(version).writeValueAsString(object);
    } catch (JsonProcessingException e) {
        log.error(e.toString());
    }

    return "Invalid API version.";
}

在这样的单元测试中:

@Test
public void testSerializeUserWithStateField() {
    User user = new User();
    user.setVersion(Entity.ApiVersion.V2016);
    user.setState(EntityState.CREATED.name());

    String userJson = serializeEntity(user.getVersion(), user);

    assertThat(userJson, equalTo("{\"lifecycleState\":\"CREATED\"}"));
}

现在,假设我有这样的东西:

@GET
@Path("users/{userId}")
public Response getUser(@PrincipalContext Principal principal,
                    @AuthorizationRequestContext AuthorizationRequest authorizationRequest,
                    @PathParam("userId") String userId) {

    final String decodedId = Optional
        .ofNullable(RequestValidationHelper.decodeUrlEncodedOCID(userId))
        .filter(StringUtils::isNotEmpty)
        .orElseThrow(BadArgumentException::new);

    User user = userStore.getUser(decodedId)
        .orElseThrow(OperationNotAllowedException::new);

    log.debug("Successfully retrieved user '{}'", decodedId);
    return Response.status(Response.Status.OK)
            .header(HttpHeaders.ETAG, user.getEtag())
            .entity(user)
            .build();
}

用户扩展实体时:

public abstract class Entity {

  private String id;
  private String userId;

  @JsonIgnore
  private String etag;

  @VersioningProperties({
        @VersioningProperties.Property(version = ApiVersion.V1, value = "state"),
        @VersioningProperties.Property(version = ApiVersion.V2016, value = "lifecycleState")
})
  private String state;

  @JsonIgnore
  private ApiVersion version = ApiVersion.INVALID;

  public enum ApiVersion {
    INVALID,
    V1,
    V2016
  }
}

我知道映射程序单独返回正确的JSON。我可以直接把电话插进去。实体(),但这会导致我们的测试出现问题,测试会检查响应中的实体是否为同一类型(例如,用户)。如果他们找到单个对象的序列化版本或序列化列表的字符串

如果我理解正确,在序列化指定的对象时(我们使用Dropwizard和Jersey),应该选择并使用带有@Provider注释的MessageBodyWriter。

@Provider
public class EntityMessageBodyWriter implements MessageBodyWriter<Entity> {
  @Override
  public long getSize(Entity entity, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
    return 0;
  }

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

  @Override
  public void writeTo(Entity entity, Class<?> aClass, Type type, Annotation[] annotations,
                    MediaType mediaType, MultivaluedMap<String, Object> multivaluedMap, OutputStream outputStream)
        throws IOException, WebApplicationException {
    outputStream.write(serializeEntity(entity.getVersion(), entity).getBytes());
  }
}

然而,事实并非如此。我没有为每个对象创建单独的MessageBodyWriter,因为文档中说可以使用超类,所有子类也会匹配(假设在isWriteable()函数中返回true,我这样做了)。我还尝试过使用JSON媒体类型指定@products,以及只指定一个子类,比如User,而不是Entity,但似乎没有任何效果。

我还尝试注册MessageBodyWriter:

JerseyEnvironment jersey = env.jersey();
jersey.register(new IdentityEntityMessageBodyWriter());

但我们所做的只是打破了几乎所有的测试(500、409等)。

我试图根据API版本更改的变量state,在响应V2016 API调用时从未设置为lifecycleState。我怎样才能让它正常工作?

共有1个答案

万俟财
2023-03-14

从你的例子中很难看出哪里出了问题。

我为您写了一个简单的例子,说明如何将其与DW集成。

首先要注意的是:

注释MessageBodyWriter对您没有帮助。当你有一个注入框架来处理你的类时,这是有效的。您可以使用注释将其自动注册到Jersey,这就是此注释的功能。因此,在DW中(除非您使用Guicey或类路径扫描等),这将不起作用,您必须手动执行。

首先,我的注释:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface VersioningProperties {    
    Property[] value();

    @interface Property {
        String version();
        String value();
    }
}

接下来,我的注释版本的东西:)

public class VersioningPropertiesIntrospector extends JacksonAnnotationIntrospector {

    private static final long serialVersionUID = 1L;
    private String version;

    public VersioningPropertiesIntrospector(String version) {
        this.version = version;
    }

    @Override
    public PropertyName findNameForSerialization(Annotated a) {
         PropertyName propertyName = findNameFromVersioningProperties(a);
         if (propertyName != null) {
             return propertyName;
         }
        return super.findNameForSerialization(a);
    }

    @Override
    public PropertyName findNameForDeserialization(Annotated a) {
         PropertyName propertyName = findNameFromVersioningProperties(a);
         if (propertyName != null) {
             return propertyName;
         }
        return super.findNameForDeserialization(a);
    }

    private PropertyName findNameFromVersioningProperties(Annotated a) {
        VersioningProperties annotation = a.getAnnotation(VersioningProperties.class);
        if (annotation == null) {
            return null;
        }
        for (Property property : annotation.value()) {
            if (version.equals(property.version())) {
                return new PropertyName(property.value());
            }
        }
        return null;
    }

}

这两个都是我从这篇文章中借用的:使用Jackson根据API版本指定不同的JSON属性名称

模型:

public class Person {

    @VersioningProperties ( {
        @VersioningProperties.Property(version="A", value="test1")
        ,@VersioningProperties.Property(version="B", value="test2")
    })
    public String name = UUID.randomUUID().toString();

    public String x = "A"; // or B
}

我正在使用属性“x”来确定使用哪个版本。其余的与您的示例相似。

因此,如果“x”是“A”,则属性名为“test1”,否则如果“B”,则属性名为“test2”。

然后,应用程序按如下方式启动:

public class Application extends io.dropwizard.Application<Configuration>{

    @Override
    public void run(Configuration configuration, Environment environment) throws Exception {

        environment.jersey().register(HelloResource.class);

        ObjectMapper aMapper = environment.getObjectMapper().copy().setAnnotationIntrospector(new VersioningPropertiesIntrospector("A"));
        ObjectMapper bMapper = environment.getObjectMapper().copy().setAnnotationIntrospector(new VersioningPropertiesIntrospector("B"));
        environment.jersey().register(new MyMessageBodyWriter(aMapper, bMapper));
    }

    public static void main(String[] args) throws Exception {
        new Application().run("server", "/home/artur/dev/repo/sandbox/src/main/resources/config/test.yaml");
    }
}

注意:我正在jersey环境中注册MessageBodyWriter。我还在使用DW已经提供给我们的ObjectMapper。这个OM有一些已经设置好且有用的配置(例如日期时间处理和类似功能)。

我的资源是:

@Path("test")
public class HelloResource {

    @GET
    @Path("asd")
    @Produces(MediaType.APPLICATION_JSON)
    public Person p(String x) {
        Person p = new Person();
        p.x = x;
        return p;
    }
}

我知道将一个主体传递到GET资源中是不好的做法,但这只是为了我可以切换Person属性来演示正在发生的事情。

这最后是我的MessageBodyWriter:

public class MyMessageBodyWriter implements MessageBodyWriter<Person> {

    private ObjectMapper aMapper;
    private ObjectMapper bMapper;

    MyMessageBodyWriter(ObjectMapper aMapper, ObjectMapper bMapper) {
        this.aMapper = aMapper;
        this.bMapper = bMapper;
    }

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

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

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

        switch(t.x) {
        case "A": aMapper.writeValue(entityStream, t);
        break;
        case "B" : bMapper.writeValue(entityStream, t);
        break;
        }
    }
}

现在,调用我的API,我得到:

artur@pandaadb:~/tmp/test$ curl -v -XGET "localhost:9085/api/test/asd"  -d "A"
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9085 (#0)
> GET /api/test/asd HTTP/1.1
> Host: localhost:9085
> User-Agent: curl/7.47.0
> Accept: */*
> Content-Length: 1
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 1 out of 1 bytes
< HTTP/1.1 200 OK
< Date: Tue, 09 Aug 2016 09:59:13 GMT
< Content-Type: application/html" target="_blank">json
< Vary: Accept-Encoding
< Content-Length: 56
< 
* Connection #0 to host localhost left intact
{"x":"A","test1":"adec4590-47af-4eeb-a15a-67a532c22b72"}artur@pandaadb:~/tmp/test$ 
artur@pandaadb:~/tmp/test$ 
artur@pandaadb:~/tmp/test$ curl -v -XGET "localhost:9085/api/test/asd"  -d "B"
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9085 (#0)
> GET /api/test/asd HTTP/1.1
> Host: localhost:9085
> User-Agent: curl/7.47.0
> Accept: */*
> Content-Length: 1
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 1 out of 1 bytes
< HTTP/1.1 200 OK
< Date: Tue, 09 Aug 2016 09:59:17 GMT
< Content-Type: application/json
< Vary: Accept-Encoding
< Content-Length: 56
< 
* Connection #0 to host localhost left intact
{"x":"B","test2":"6c56650c-6c87-418f-8b1a-0750a8091c46"}artur@pandaadb:~/tmp/test$ 

请注意,根据传递给curl命令的主体,属性名称已正确切换。

所以,我不能100%确定你的测试为什么会失败。

我相信OM有某种缓存,你不能来回切换注释内参探查器(这只是一个假设,因为我不能重置我的OM)。无论如何,只有两个不同的可能是更好的选择。

我希望这能帮助你解决问题。

如果您使用的是测试,那么还需要确保在单元测试中正确注册了所有内容。

设置一些断点,sysout和其他有帮助的小朋友,他们会为你指出正确的方向。

干杯

阿图尔

 类似资料:
  • 我有问题让我的Angular2客户端与我的Spring服务器通信,因为我添加了Spring Security性,即当我尝试向服务器登录url发送包含鉴别信息的JSON时,我得到一个403“无效的CSRF令牌'null'是在请求参数'_csrf'或标头'X-CSRF-TOKEN'上找到的。” 我知道我应该在我的响应头上传递一个令牌,供客户端使用,但没有传递这个令牌。我尝试了这个答案,但令牌仍然没有被

  • 我正在尝试使用Netty编写RTSP服务器。 现在,客户端发送请求 我想发回以下回复 我应该使用什么来构造http响应。我应该使用HttpResponse还是只使用普通字节数组并将其转换为ByteBuf? 我使用的Netty版本是4.1.5 提前谢谢。

  • 我在这里遵循 JWT 夸克指南。我想在不允许用户组访问 API 时发送自定义响应。 这是指南中显示的示例。 我如何知道请求是否未经授权,以便我可以发送自定义响应。

  • 我有一个场景,其中各种JSP击中同一个servlet。对于该servlet有一个过滤器,用于检查托运。基于这种情况,必须将响应从请求发出的地方发送回jsp。不管发送请求的源是什么,servlet都必须执行相同的功能。如何编写通用代码将响应重定向回源JSP。

  • 但是,当我试图模拟一个异常(例如反序列化异常)时,异常消息不会作为响应发送回Tcp客户端。我可以看到我的应用程序侦听器正在获取TcpDeserializationExceptionEvent,并将消息发送到ExceptionEventChannel。@ServiceActivator方法句柄(Message msg)也打印我的异常消息。但它从未到达MessageHandler方法out(Abstr

  • 我正在尝试使用ETags和nginx (1.2.1)服务器理解本地缓存,该服务器将php的请求重定向到php-cgi守护进程。 这里是我的简单索引。电话: 在第二个请求之后,我的浏览器会发送一个 If-None-匹配 标头: 但是我的网络服务器没有返回304: 除非我误解了,否则我的服务器应该将 Etag 与发送的 If-None-Match 进行比较,并返回 304 响应,因为它们是相同的。 我