Example usage for com.fasterxml.jackson.core JsonProcessingException getMessage

List of usage examples for com.fasterxml.jackson.core JsonProcessingException getMessage

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonProcessingException getMessage.

Prototype

@Override
public String getMessage() 

Source Link

Document

Default method overridden so that we can add location information

Usage

From source file:org.mycontroller.restclient.core.RestHttpClient.java

public String toJsonString(Object object) {
    try {/*www .  j  a  v a 2  s  .c o m*/
        return mapper.writeValueAsString(object);
    } catch (JsonProcessingException ex) {
        _logger.error("Exception,", ex);
        throw new RuntimeException("Exception: " + ex.getMessage());
    }
}

From source file:com.meltmedia.jackson.crypto.EncryptionService.java

private String validationErrorMessage(E encrypted, Set<ConstraintViolation<E>> violations) {
    StringBuilder sb = new StringBuilder();
    try {// w  w  w .  j  a  va2 s .  c o  m
        sb.append("value:").append(mapper.writeValueAsString(encrypted)).append("\n");
    } catch (JsonProcessingException e) {
        sb.append(e.getMessage()).append("\n");
    }
    sb.append("violations:\n");
    for (ConstraintViolation<E> violation : violations) {
        sb.append("- ").append(violation.getPropertyPath().toString() + " " + violation.getMessage())
                .append("\n");
    }
    return sb.toString();
}

From source file:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java

/**
 * //from   w w  w. j  a  v a2 s  . c o m
 * Returns the API documentation of all annotated resources for purposes of Swagger documentation.
 * 
 * @return The resource's documentation
 * 
 */
@GET
@Path("/swagger.json")
@Produces(MediaType.APPLICATION_JSON)
public HttpResponse getSwaggerJSON() {
    Swagger swagger = new Reader(new Swagger()).read(this.getClass());
    if (swagger == null) {
        return new HttpResponse("Swagger API declaration not available!", HttpURLConnection.HTTP_NOT_FOUND);
    }
    try {
        return new HttpResponse(Json.mapper().writeValueAsString(swagger), HttpURLConnection.HTTP_OK);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:org.venice.piazza.servicecontroller.taskmanaged.ServiceTaskManager.java

/**
 * Processes the external Worker requesting a Status Update for a running job.
 * /* w ww. j a  va 2  s.  c  o m*/
 * @param serviceId
 *            The ID of the Service
 * @param jobId
 *            The ID of the Job
 * @param statusUpdate
 *            The Status of the Job
 */
public void processStatusUpdate(String serviceId, String jobId, StatusUpdate statusUpdate)
        throws MongoException, InvalidInputException {
    // Validate the Service ID exists, and contains the Job ID
    ServiceJob serviceJob = mongoAccessor.getServiceJob(serviceId, jobId);
    if (serviceJob == null) {
        throw new InvalidInputException(
                String.format("Cannot find the specified Job %s for this Service %s", jobId, serviceId));
    }
    // Send the Update to Kafka
    ProducerRecord<String, String> statusUpdateRecord;
    try {
        statusUpdateRecord = new ProducerRecord<String, String>(
                String.format("%s-%s", JobMessageFactory.UPDATE_JOB_TOPIC_NAME, SPACE), jobId,
                objectMapper.writeValueAsString(statusUpdate));
        producer.send(statusUpdateRecord);
    } catch (JsonProcessingException exception) {
        String error = "Error Sending Job Status from External Service to Job Manager: "
                + exception.getMessage();
        LOGGER.error(error, exception);
        piazzaLogger.log(error, Severity.ERROR);
    }
    // If done, remove the Job from the Service Queue
    String status = statusUpdate.getStatus();
    if ((StatusUpdate.STATUS_CANCELLED.equals(status)) || (StatusUpdate.STATUS_ERROR.equals(status))
            || (StatusUpdate.STATUS_FAIL.equals(status)) || (StatusUpdate.STATUS_SUCCESS.equals(status))) {
        piazzaLogger.log(String.format(
                "Job %s For Service %s has reached final state %s. Removing from Service Jobs Queue.", jobId,
                serviceId, status), Severity.INFORMATIONAL);
        mongoAccessor.removeJobFromServiceQueue(serviceId, jobId);
    }
}

From source file:eu.freme.common.rest.OwnedResourceManagingController.java

@RequestMapping(method = RequestMethod.GET)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> getAllEntities() {
    try {//w  ww.  j  av a2  s.c o  m
        List<Entity> entities = entityDAO.findAllReadAccessible();
        String serialization = entities.stream().map(p -> {
            try {
                return p.toJson();
            } catch (JsonProcessingException e) {
                throw new FREMEHttpException("Could not serialize entity with identifier=\"" + p.getIdentifier()
                        + "\" to JSON. " + e.getMessage());
            }
        }).collect(Collectors.joining(",\n"));

        HttpHeaders responseHeaders = new HttpHeaders();
        //ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        //String serialization = ow.writeValueAsString(entities);
        responseHeaders.add("Content-Type", SerializationFormatMapper.JSON);
        return new ResponseEntity<>("[" + serialization + "]", responseHeaders, HttpStatus.OK);
    } catch (FREMEHttpException ex) {
        logger.error(ex.getMessage());
        throw ex;
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        throw new FREMEHttpException(ex.getMessage());
    }
}

From source file:org.inaetics.pubsub.impl.discovery.etcd.EtcdDiscoveryManager.java

private String mapToJSON(Map<String, String> map) {
    try {/*w w  w.j a  v  a 2s  .c o  m*/
        return new ObjectMapper().writeValueAsString(map);
    } catch (JsonProcessingException e) {
        m_LogService.log(LogService.LOG_ERROR, e.getMessage(), e);
    }
    return "";
}

From source file:com.servioticy.api.commons.data.Group.java

/** Create a Group from a JsonNode document.
 *
 * @param root The JsonNode Root/*  w  w  w.  j ava  2s .c o  m*/
 */
public Group(final JsonNode root) {
    try {
        // Check if exist stream
        if (root.path("stream").isMissingNode())
            throw new ServIoTWebApplicationException(Response.Status.NOT_FOUND,
                    "The stream field was not found");
        // Check if exist soIds
        if (root.path("soIds").isMissingNode())
            throw new ServIoTWebApplicationException(Response.Status.NOT_FOUND,
                    "The soIds field was not found");

        streamId = ((ObjectNode) root).get("stream").asText();
        try {
            soIds = mapper.readValue(mapper.writeValueAsString(root.get("soIds")),
                    new TypeReference<ArrayList<String>>() {
                    });
        } catch (JsonProcessingException e) {
            throw new ServIoTWebApplicationException(Response.Status.BAD_REQUEST,
                    "soIds has to be an array of Strings");
        }

    } catch (JsonProcessingException e) {
        LOG.error(e);
        throw new ServIoTWebApplicationException(Response.Status.BAD_REQUEST, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new ServIoTWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
    }

}

From source file:com.yahoo.bard.webservice.web.endpoints.JobsServlet.java

/**
 * Process a request to get job payload.
 *
 * @param ticket  The ticket that can uniquely identify a Job
 * @param apiRequest  JobsApiRequest object with all the associated info in it
 * @param asyncResponse  An async response that we can use to respond asynchronously
 *//*  w w  w.jav  a2s .  co m*/
protected void handleJobResponse(String ticket, JobsApiRequest apiRequest, AsyncResponse asyncResponse) {
    apiRequest.getJobViewObservable(ticket)
            //map the job to Json String
            .map(job -> {
                try {
                    return objectMappers.getMapper().writeValueAsString(job);
                } catch (JsonProcessingException e) {
                    LOG.error(e.getMessage(), e);
                    throw Exceptions.propagate(e);
                }
            })
            //map the jsonResponse String to a Response
            .map(this::getResponse).onErrorReturn(this::getErrorResponse).subscribe(asyncResponse::resume);
}

From source file:com.hpcloud.mon.resource.exception.JsonProcessingExceptionMapper.java

@Override
public Response toResponse(JsonProcessingException exception) {
    /*/*from  ww  w  . ja v a2s  . c om*/
     * If the error is in the JSON generation, it's a server error.
     */
    if (exception instanceof JsonGenerationException)
        return Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON).entity(Exceptions
                .buildLoggedErrorMessage(FaultType.SERVER_ERROR, "Error generating JSON", null, exception))
                .build();

    final String message = exception.getMessage();

    /*
     * If we can't deserialize the JSON because someone forgot a no-arg constructor, it's a server
     * error and we should inform the developer.
     */
    if (message.startsWith("No suitable constructor found"))
        return Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON)
                .entity(Exceptions.buildLoggedErrorMessage(FaultType.SERVER_ERROR,
                        "Unable to deserialize the provided JSON", null, exception))
                .build();

    /*
     * Otherwise, it's those pesky users.
     */
    return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON)
            .entity(Exceptions.buildLoggedErrorMessage(FaultType.BAD_REQUEST,
                    "Unable to process the provided JSON", Exceptions.stripLocationFromStacktrace(message),
                    exception))
            .build();
}

From source file:org.venice.piazza.servicecontroller.taskmanaged.ServiceTaskManager.java

/**
 * Attempts to cancel a Job. This will use a Job lookup in order to find the Service that was executed. If this
 * Service was task managed, then that Job will be removed from the queue.
 * /*from  w ww. j  a  v a  2s . c o m*/
 * @param jobId
 *            The ID of the Job to attempt to cancel.
 */
public void cancelJob(String jobId) {
    try {
        // Attempt to get the Service that executed this Job
        Job job = mongoAccessor.getJobById(jobId);
        if (job != null) {
            // If this was an Execute Service Job
            if (job.getJobType() instanceof ExecuteServiceJob) {
                ExecuteServiceJob executeJob = (ExecuteServiceJob) job.getJobType();
                String serviceId = executeJob.getData().getServiceId();

                // Log the cancellation
                piazzaLogger.log(
                        String.format("Removing Service Job %s from Service Queue for %s", jobId, serviceId),
                        Severity.INFORMATIONAL);

                // Determine if the Service ID is Task-Managed
                Service service = mongoAccessor.getServiceById(serviceId);
                if ((service.getIsTaskManaged() != null) && (service.getIsTaskManaged() == true)) {
                    // If this is a Task Managed Service, then remove the Job from the Queue.
                    mongoAccessor.removeJobFromServiceQueue(serviceId, jobId);
                    // Send the Kafka Message that this Job has been cancelled
                    StatusUpdate statusUpdate = new StatusUpdate();
                    statusUpdate.setStatus(StatusUpdate.STATUS_CANCELLED);
                    ProducerRecord<String, String> statusUpdateRecord;
                    try {
                        statusUpdateRecord = new ProducerRecord<String, String>(
                                String.format("%s-%s", JobMessageFactory.UPDATE_JOB_TOPIC_NAME, SPACE), jobId,
                                objectMapper.writeValueAsString(statusUpdate));
                        producer.send(statusUpdateRecord);
                    } catch (JsonProcessingException exception) {
                        String error = String.format("Error Sending Cancelled Job %s Status to Job Manager: %s",
                                jobId, exception.getMessage());
                        LOGGER.error(error, exception);
                        piazzaLogger.log(error, Severity.ERROR);
                    }

                    // Log the success
                    piazzaLogger
                            .log(String.format("Successfully removed Service Job %s from Service Queue for %s",
                                    jobId, serviceId), Severity.INFORMATIONAL);
                }
            }
        }
    } catch (Exception exception) {
        String error = String.format("Error Removing Job %s from a Task-Managed Service Queue : %s", jobId,
                exception.getMessage());
        LOGGER.error(error, exception);
        piazzaLogger.log(error, Severity.ERROR);
    }
}