JsonPatchInterceptor.java 文件源码

java
阅读 27 收藏 0 点赞 0 评论 0

项目:omakase 作者:
@Override
public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException {
    Optional<Object> optionalBean = getCurrentObject();

    if (optionalBean.isPresent()) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // Currently assume the bean is of type BuiltResponse, this may need to change in the future
        Object bean = ((BuiltResponse) optionalBean.get()).getEntity();

        MessageBodyWriter<? super Object> bodyWriter = providers.getMessageBodyWriter(Object.class, bean.getClass(), new Annotation[0], MediaType.APPLICATION_JSON_TYPE);
        bodyWriter.writeTo(bean, bean.getClass(), bean.getClass(), new Annotation[0], MediaType.APPLICATION_JSON_TYPE, new MultivaluedHashMap<>(), outputStream);

        // Use the Jackson 2.x classes to convert both the incoming patch and the current state of the object into a JsonNode / JsonPatch
        ObjectMapper mapper = new ObjectMapper();
        JsonNode serverState = mapper.readValue(outputStream.toByteArray(), JsonNode.class);
        JsonNode patchAsNode = mapper.readValue(context.getInputStream(), JsonNode.class);
        JsonPatch patch = JsonPatch.fromJson(patchAsNode);

        try {
            JsonNode result = patch.apply(serverState);
            // Stream the result & modify the stream on the readerInterceptor
            ByteArrayOutputStream resultAsByteArray = new ByteArrayOutputStream();
            mapper.writeValue(resultAsByteArray, result);
            context.setInputStream(new ByteArrayInputStream(resultAsByteArray.toByteArray()));

            return context.proceed();

        } catch (JsonPatchException | JsonMappingException e) {
            throw new WebApplicationException(e.getMessage(), e, Response.status(Response.Status.BAD_REQUEST).build());
        }

    } else {
        throw new IllegalArgumentException("No matching GET method on resource");
    }
}
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号