use of jakarta.json.JsonMergePatch in project resteasy by resteasy.
the class JsonpPatchMethodFilter method applyPatch.
@Override
protected byte[] applyPatch(final ContainerRequestContext requestContext, final byte[] targetJsonBytes) throws IOException, ProcessingException {
HttpRequest request = ResteasyContext.getContextData(HttpRequest.class);
// TODO: look at if we need to get reader factory from ContextResolver
Charset charset = AbstractJsonpProvider.getCharset(requestContext.getMediaType());
ByteArrayInputStream is = new ByteArrayInputStream(targetJsonBytes);
if (charset == null) {
charset = Charset.defaultCharset();
}
JsonReader reader = readerFactory.createReader(is, charset);
JsonObject targetJson = reader.readObject();
JsonObject result = null;
try {
if (MediaType.APPLICATION_JSON_PATCH_JSON_TYPE.isCompatible(requestContext.getMediaType())) {
JsonReader arrayReader = readerFactory.createReader(request.getInputStream(), charset);
JsonArray jsonArray = arrayReader.readArray();
JsonPatch patch = Json.createPatch(jsonArray);
result = patch.apply(targetJson);
} else {
JsonReader valueReader = readerFactory.createReader(request.getInputStream(), charset);
JsonValue mergePatchValue = valueReader.readValue();
final JsonMergePatch mergePatch = Json.createMergePatch(mergePatchValue);
result = mergePatch.apply(targetJson).asJsonObject();
}
} catch (JsonException e) {
// TODO: talk with jsonp community fix this
if (e.getMessage().contains("Illegal value") || e.getMessage().contains("JSON Patch must")) {
throw new BadRequestException(e.getMessage());
}
throw new Failure(e, HttpResponseCodes.SC_CONFLICT);
}
ByteArrayOutputStream targetOutputStream = new ByteArrayOutputStream();
JsonWriter jsonWriter = writerFactory.createWriter(targetOutputStream, charset);
jsonWriter.write(result);
return targetOutputStream.toByteArray();
}
Aggregations