Search in sources :

Example 1 with JsonPatchException

use of com.github.fge.jsonpatch.JsonPatchException in project syndesis by syndesisio.

the class Updater method patch.

@PATCH
@Path(value = "/{id}")
@Consumes(MediaType.APPLICATION_JSON)
default void patch(@NotNull @PathParam("id") @ApiParam(required = true) String id, @NotNull JsonNode patchJson) throws IOException {
    Class<T> modelClass = resourceKind().getModelClass();
    final T existing = getDataManager().fetch(modelClass, id);
    if (existing == null) {
        throw new EntityNotFoundException();
    }
    JsonNode document = Json.reader().readTree(Json.writer().writeValueAsString(existing));
    // Attempt to apply the patch...
    final JsonMergePatch patch;
    try {
        patch = JsonMergePatch.fromJson(patchJson);
        document = patch.apply(document);
    } catch (JsonPatchException e) {
        throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
    }
    // Convert the Json back to an entity.
    T obj = Json.reader().forType(modelClass).readValue(Json.writer().writeValueAsBytes(document));
    if (this instanceof Validating) {
        final Validator validator = ((Validating<?>) this).getValidator();
        final Set<ConstraintViolation<T>> violations = validator.validate(obj, AllValidations.class);
        if (!violations.isEmpty()) {
            throw new ConstraintViolationException(violations);
        }
    }
    getDataManager().update(obj);
}
Also used : JsonPatchException(com.github.fge.jsonpatch.JsonPatchException) PUT(javax.ws.rs.PUT) WebApplicationException(javax.ws.rs.WebApplicationException) ConstraintViolation(javax.validation.ConstraintViolation) JsonMergePatch(com.github.fge.jsonpatch.mergepatch.JsonMergePatch) ConstraintViolationException(javax.validation.ConstraintViolationException) JsonNode(com.fasterxml.jackson.databind.JsonNode) EntityNotFoundException(javax.persistence.EntityNotFoundException) Validator(javax.validation.Validator) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) PATCH(io.swagger.jaxrs.PATCH)

Example 2 with JsonPatchException

use of com.github.fge.jsonpatch.JsonPatchException in project oc-explorer by devgateway.

the class OcdsSchemaValidatorService method init.

/**
 * Intializes the JSON schema validator plus the provided patches
 */
public void init() {
    try {
        ocdsSchemaNode = JsonLoader.fromResource(schemaLocation == null ? OCDS_SCHEMA_LOCATION : schemaLocation);
        if (patchResourceNames != null && patchResourceNames.length > 0) {
            for (int i = 0; i < patchResourceNames.length; i++) {
                JsonNode node = JsonLoader.fromResource(patchResourceNames[i]);
                if (patchResourceNames[i].contains("mergepatch")) {
                    JsonMergePatch patch = JsonMergePatch.fromJson(node);
                    ocdsSchemaNode = patch.apply(ocdsSchemaNode);
                } else {
                    JsonPatch patch = JsonPatch.fromJson(node);
                    ocdsSchemaNode = patch.apply(ocdsSchemaNode);
                }
            }
        }
        logger.debug(jacksonObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(ocdsSchemaNode));
        schema = JsonSchemaFactory.newBuilder().setReportProvider(new ListReportProvider(LogLevel.ERROR, LogLevel.FATAL)).freeze().getJsonSchema(ocdsSchemaNode);
    } catch (ProcessingException | IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (JsonPatchException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
}
Also used : ListReportProvider(com.github.fge.jsonschema.core.report.ListReportProvider) JsonPatchException(com.github.fge.jsonpatch.JsonPatchException) JsonMergePatch(com.github.fge.jsonpatch.mergepatch.JsonMergePatch) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) JsonPatch(com.github.fge.jsonpatch.JsonPatch) ProcessingException(com.github.fge.jsonschema.core.exceptions.ProcessingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 3 with JsonPatchException

use of com.github.fge.jsonpatch.JsonPatchException in project jersey by jersey.

the class PatchingInterceptor method aroundReadFrom.

@SuppressWarnings("unchecked")
@Override
public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException {
    // Get the resource we are being called on, and find the GET method
    Object resource = uriInfo.getMatchedResources().get(0);
    Method found = null;
    for (Method next : resource.getClass().getMethods()) {
        if (next.getAnnotation(GET.class) != null) {
            found = next;
            break;
        }
    }
    if (found == null) {
        throw new InternalServerErrorException("No matching GET method on resource");
    }
    // Invoke the get method to get the state we are trying to patch
    Object bean;
    try {
        bean = found.invoke(resource);
    } catch (Exception e) {
        throw new WebApplicationException(e);
    }
    // Convert this object to a an array of bytes
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    MessageBodyWriter bodyWriter = workers.getMessageBodyWriter(bean.getClass(), 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<String, Object>(), baos);
    // 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(baos.toByteArray(), JsonNode.class);
    JsonNode patchAsNode = mapper.readValue(readerInterceptorContext.getInputStream(), JsonNode.class);
    JsonPatch patch = JsonPatch.fromJson(patchAsNode);
    try {
        // Apply the patch
        JsonNode result = patch.apply(serverState);
        // Stream the result & modify the stream on the readerInterceptor
        ByteArrayOutputStream resultAsByteArray = new ByteArrayOutputStream();
        mapper.writeValue(resultAsByteArray, result);
        readerInterceptorContext.setInputStream(new ByteArrayInputStream(resultAsByteArray.toByteArray()));
        // Pass control back to the Jersey code
        return readerInterceptorContext.proceed();
    } catch (JsonPatchException ex) {
        throw new InternalServerErrorException("Error applying patch.", ex);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) JsonNode(com.fasterxml.jackson.databind.JsonNode) Method(java.lang.reflect.Method) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonPatch(com.github.fge.jsonpatch.JsonPatch) JsonPatchException(com.github.fge.jsonpatch.JsonPatchException) IOException(java.io.IOException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) WebApplicationException(javax.ws.rs.WebApplicationException) JsonPatchException(com.github.fge.jsonpatch.JsonPatchException) ByteArrayInputStream(java.io.ByteArrayInputStream) GET(javax.ws.rs.GET) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 4 with JsonPatchException

use of com.github.fge.jsonpatch.JsonPatchException in project ocvn by devgateway.

the class OcdsSchemaValidatorService method init.

/**
 * Intializes the JSON schema validator plus the provided patches
 */
public void init() {
    try {
        ocdsSchemaNode = JsonLoader.fromResource(schemaLocation == null ? OCDS_SCHEMA_LOCATION : schemaLocation);
        if (patchResourceNames != null && patchResourceNames.length > 0) {
            for (int i = 0; i < patchResourceNames.length; i++) {
                JsonNode node = JsonLoader.fromResource(patchResourceNames[i]);
                if (patchResourceNames[i].contains("mergepatch")) {
                    JsonMergePatch patch = JsonMergePatch.fromJson(node);
                    ocdsSchemaNode = patch.apply(ocdsSchemaNode);
                } else {
                    JsonPatch patch = JsonPatch.fromJson(node);
                    ocdsSchemaNode = patch.apply(ocdsSchemaNode);
                }
            }
        }
        logger.debug(jacksonObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(ocdsSchemaNode));
        schema = JsonSchemaFactory.newBuilder().setReportProvider(new ListReportProvider(LogLevel.ERROR, LogLevel.FATAL)).freeze().getJsonSchema(ocdsSchemaNode);
    } catch (ProcessingException | IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (JsonPatchException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
}
Also used : ListReportProvider(com.github.fge.jsonschema.core.report.ListReportProvider) JsonPatchException(com.github.fge.jsonpatch.JsonPatchException) JsonMergePatch(com.github.fge.jsonpatch.mergepatch.JsonMergePatch) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) JsonPatch(com.github.fge.jsonpatch.JsonPatch) ProcessingException(com.github.fge.jsonschema.core.exceptions.ProcessingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

JsonNode (com.fasterxml.jackson.databind.JsonNode)4 JsonPatchException (com.github.fge.jsonpatch.JsonPatchException)4 JsonPatch (com.github.fge.jsonpatch.JsonPatch)3 JsonMergePatch (com.github.fge.jsonpatch.mergepatch.JsonMergePatch)3 IOException (java.io.IOException)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ProcessingException (com.github.fge.jsonschema.core.exceptions.ProcessingException)2 ListReportProvider (com.github.fge.jsonschema.core.report.ListReportProvider)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 PATCH (io.swagger.jaxrs.PATCH)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 Method (java.lang.reflect.Method)1 EntityNotFoundException (javax.persistence.EntityNotFoundException)1 ConstraintViolation (javax.validation.ConstraintViolation)1 ConstraintViolationException (javax.validation.ConstraintViolationException)1 Validator (javax.validation.Validator)1 Consumes (javax.ws.rs.Consumes)1 GET (javax.ws.rs.GET)1