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:com.wq.common.web.springmvc.MappingJackson2HttpMessageConverter.java

@SuppressWarnings("deprecation")
@Override//w  w  w . j a  v a2s.  c  o m
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.objectMapper.getJsonFactory()
            .createJsonGenerator(outputMessage.getBody(), encoding);

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    try {
        if (this.prefixJson) {
            jsonGenerator.writeRaw("[] && ");
        }
        // jsonp??
        boolean isJSONP = !ObjectUtil.isEmpty(WebContext.getRequest().getParameter(DEFAULT_CALLBACK));
        if (isJSONP) {
            WebContext.getResponse().setContentType("application/x-javascript");
            jsonGenerator.writeRaw(WebContext.getRequest().getParameter(DEFAULT_CALLBACK) + "(");
        }
        this.objectMapper.writeValue(jsonGenerator, object);
        if (isJSONP) {
            outputMessage.getBody().write(')');
        }
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}

From source file:org.jboss.pnc.buildagent.server.termserver.Term.java

HttpHandler webSocketStatusUpdateHandler() {
    WebSocketConnectionCallback webSocketConnectionCallback = (exchange, webSocketChannel) -> {
        Consumer<TaskStatusUpdateEvent> statusUpdateListener = event -> {
            Map<String, Object> statusUpdate = new HashMap<>();
            statusUpdate.put("action", "status-update");
            statusUpdate.put("event", event);

            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String message = objectMapper.writeValueAsString(statusUpdate);
                WebSockets.sendText(message, webSocketChannel, null);
            } catch (JsonProcessingException e) {
                log.error("Cannot write object to JSON", e);
                String errorMessage = "Cannot write object to JSON: " + e.getMessage();
                WebSockets.sendClose(CloseMessage.UNEXPECTED_ERROR, errorMessage, webSocketChannel, null);
            }//w  ww  .j  a  v  a 2  s .  c  o m
        };
        log.debug("Registering new status update listener {}.", statusUpdateListener);
        addStatusUpdateListener(statusUpdateListener);
        webSocketChannel.addCloseTask((task) -> removeStatusUpdateListener(statusUpdateListener));
    };

    return new WebSocketProtocolHandshakeHandler(webSocketConnectionCallback);
}

From source file:org.commonjava.cartographer.rest.ctl.RenderingController.java

public File tree(final RepositoryContentRequest recipe) throws CartoRESTException {
    configHelper.setRecipeDefaults(recipe);

    final File workBasedir = config.getWorkBasedir();
    String dtoJson;/*from  w w w .jav  a2s.c o  m*/
    try {
        dtoJson = serializer.writeValueAsString(recipe);
    } catch (final JsonProcessingException e) {
        throw new CartoRESTException("Failed to serialize to JSON: %s", e, e.getMessage());
    }

    final File out = new File(workBasedir, DigestUtils.md5Hex(dtoJson));
    workBasedir.mkdirs();

    FileWriter w = null;
    try {
        w = new FileWriter(out);
        ops.depTree(recipe, false, new PrintWriter(w));
    } catch (final CartoDataException e) {
        throw new CartoRESTException("Failed to generate dependency tree. Reason: {}", e, e.getMessage());
    } catch (CartoRequestException e) {
        throw new CartoRESTException(ApplicationStatus.BAD_REQUEST.code(), "Invalid request: %s. Reason: %s", e,
                recipe, e.getMessage());
    } catch (final IOException e) {
        throw new CartoRESTException("Failed to open work file for caching output: {}. Reason: {}", e, out,
                e.getMessage());
    } finally {
        IOUtils.closeQuietly(w);
    }

    return out;
}

From source file:org.commonjava.cartographer.rest.ctl.RenderingController.java

public File list(final RepositoryContentRequest recipe) throws CartoRESTException {
    configHelper.setRecipeDefaults(recipe);

    final File workBasedir = config.getWorkBasedir();
    String dtoJson;/*from www  . j a  v a  2 s  .  c om*/
    try {
        dtoJson = serializer.writeValueAsString(recipe);
    } catch (final JsonProcessingException e) {
        throw new CartoRESTException("Failed to serialize to JSON: %s", e, e.getMessage());
    }

    final File out = new File(workBasedir, DigestUtils.md5Hex(dtoJson));
    workBasedir.mkdirs();

    FileWriter w = null;
    try {
        w = new FileWriter(out);
        ops.depList(recipe, new PrintWriter(w));
    } catch (final CartoDataException e) {
        throw new CartoRESTException("Failed to generate dependency tree. Reason: {}", e, e.getMessage());
    } catch (CartoRequestException e) {
        throw new CartoRESTException(ApplicationStatus.BAD_REQUEST.code(), "Invalid request: %s. Reason: %s", e,
                recipe, e.getMessage());
    } catch (final IOException e) {
        throw new CartoRESTException("Failed to open work file for caching output: {}. Reason: {}", e, out,
                e.getMessage());
    } finally {
        IOUtils.closeQuietly(w);
    }

    return out;
}

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

/** Create a Subscription
 *
 * @param soId/*from ww w  .ja v a  2  s  .  c  o m*/
 * @param streamId
 * @param body
 */
public Subscription(SO so, String userId, String streamId, String body) {
    JsonNode root;

    soParent = so;
    JsonNode stream = soParent.getStream(streamId);
    this.userId = userId;

    // Check if exists this streamId in the Service Object
    if (stream == null)
        throw new ServIoTWebApplicationException(Response.Status.NOT_FOUND,
                "This Service Object does not have this stream.");

    try {
        root = mapper.readTree(body);
    } 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());
    }

    // Check if exists callback field in body request
    if (root.path("callback").isMissingNode())
        throw new ServIoTWebApplicationException(Response.Status.BAD_REQUEST, "No callback in the request");

    // Check if exists destination field in body request
    if (root.path("destination").isMissingNode())
        throw new ServIoTWebApplicationException(Response.Status.BAD_REQUEST, "No destination in the request");

    // Check repeated subscriptions for pubsub subscriptions
    if (root.get("callback").asText().equals("pubsub"))
        if (SearchEngine.getRepeatedSubscriptions(root.get("destination").asText(), soParent.getId(), "pubsub",
                streamId) > 0)
            throw new ServIoTWebApplicationException(Response.Status.BAD_REQUEST,
                    "Duplicated pubsub subscription");

    // OK, create the subscription

    // servioticy key = subsId
    // TODO improve key and subsId generation
    UUID uuid = UUID.randomUUID(); //UUID java library

    subsId = uuid.toString().replaceAll("-", "");
    subsKey = soParent.getId() + "-" + streamId + "-" + subsId;

    ((ObjectNode) subsRoot).put("id", subsId);
    ((ObjectNode) subsRoot).put("userId", userId);
    long time = System.currentTimeMillis();
    ((ObjectNode) subsRoot).put("createdAt", time);
    ((ObjectNode) subsRoot).put("updatedAt", time);
    ((ObjectNode) subsRoot).put("callback", root.get("callback").asText());
    ((ObjectNode) subsRoot).put("source", soParent.getId());
    ((ObjectNode) subsRoot).put("destination", root.get("destination").asText());
    ((ObjectNode) subsRoot).put("stream", streamId);
    if (!root.path("customFields").isMissingNode())
        ((ObjectNode) subsRoot).put("customFields", root.get("customFields"));
    if (!root.path("delay").isMissingNode())
        ((ObjectNode) subsRoot).put("delay", root.get("delay").asInt());
    if (!root.path("expire").isMissingNode()) {
        ((ObjectNode) subsRoot).put("expire", root.get("expire").asInt());
    }

    //    // Put the subscription id in the so stream subscription array
    //    soParent.setSubscription(stream, subsId);

}

From source file:org.venice.piazza.servicecontroller.messaging.handlers.ExecuteServiceHandler.java

/**
 * Handles requests to execute a service. 
 * TODO this needs to change to leverage pz-jbcommon ExecuteServiceMessage after it builds.
 * //w  w  w  .  j  a va 2 s.  c  o m
 * @param message
 * @return the Response as a String
 */
public ResponseEntity<String> handle(ExecuteServiceData data) {
    coreLogger.log("executeService serviceId=" + data.getServiceId(), PiazzaLogger.INFO);
    ResponseEntity<String> responseEntity = null;
    String serviceId = data.getServiceId();
    Service sMetadata = null;
    // Default request mimeType application/json
    String requestMimeType = "application/json";
    try {
        // Accessor throws exception if can't find service
        sMetadata = accessor.getServiceById(serviceId);

        ObjectMapper om = new ObjectMapper();
        String result = om.writeValueAsString(sMetadata);
        coreLogger.log(result, PiazzaLogger.INFO);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    if (sMetadata != null) {
        String rawURL = sMetadata.getUrl();
        coreLogger.log("URL to use = " + rawURL, PiazzaLogger.INFO);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(rawURL);

        Map<String, DataType> postObjects = new HashMap<>();
        Iterator<Entry<String, DataType>> it = data.getDataInputs().entrySet().iterator();
        String postString = "";
        while (it.hasNext()) {
            Entry<String, DataType> entry = it.next();
            String inputName = entry.getKey();
            coreLogger.log("The parameter is " + inputName, PiazzaLogger.DEBUG);

            if (entry.getValue() instanceof URLParameterDataType) {
                String paramValue = ((URLParameterDataType) entry.getValue()).getContent();
                if (inputName.length() == 0) {
                    coreLogger.log("sMetadata.getResourceMeta=" + sMetadata.getResourceMetadata(),
                            PiazzaLogger.DEBUG);

                    builder = UriComponentsBuilder.fromHttpUrl(sMetadata.getUrl() + "?" + paramValue);
                    coreLogger.log("Builder URL is " + builder.toUriString(), PiazzaLogger.DEBUG);

                } else {
                    builder.queryParam(inputName, paramValue);
                    coreLogger.log("Input Name=" + inputName + " paramValue=" + paramValue, PiazzaLogger.DEBUG);
                }
            } else if (entry.getValue() instanceof BodyDataType) {
                BodyDataType bdt = (BodyDataType) entry.getValue();
                postString = bdt.getContent();
                requestMimeType = bdt.getMimeType();
                if ((requestMimeType == null) || (requestMimeType.length() == 0)) {
                    coreLogger.log("Body mime type not specified", PiazzaLogger.ERROR);
                    return new ResponseEntity<>("Body mime type not specified", HttpStatus.BAD_REQUEST);
                }
            } else {
                // Default behavior for other inputs, put them in list of objects
                // which are transformed into JSON consistent with default requestMimeType
                coreLogger.log("inputName =" + inputName + "entry Value=" + entry.getValue(),
                        PiazzaLogger.INFO);
                postObjects.put(inputName, entry.getValue());
            }
        }

        coreLogger.log("Final Builder URL" + builder.toUriString(), PiazzaLogger.INFO);
        if (postString.length() > 0 && postObjects.size() > 0) {
            coreLogger.log("String Input not consistent with other Inputs", PiazzaLogger.ERROR);
            return new ResponseEntity<>("String Input not consistent with other Inputs",
                    HttpStatus.BAD_REQUEST);
        } else if (postObjects.size() > 0) {
            ObjectMapper mapper = makeObjectMapper();
            try {
                postString = mapper.writeValueAsString(postObjects);
            } catch (JsonProcessingException e) {
                coreLogger.log(e.getMessage(), PiazzaLogger.ERROR);
                return new ResponseEntity<>("Could not marshal post requests", HttpStatus.BAD_REQUEST);
            }
        }

        URI url = URI.create(builder.toUriString());
        if (sMetadata.getMethod().equals("GET")) {
            coreLogger.log("GetForEntity URL=" + url, PiazzaLogger.INFO);
            responseEntity = template.getForEntity(url, String.class);

        } else {
            HttpHeaders headers = new HttpHeaders();

            // Set the mimeType of the request
            MediaType mediaType = createMediaType(requestMimeType);
            headers.setContentType(mediaType);
            HttpEntity<String> requestEntity = makeHttpEntity(headers, postString);

            coreLogger.log("PostForEntity URL=" + url, PiazzaLogger.INFO);
            responseEntity = template.postForEntity(url, requestEntity, String.class);
        }

    } else {
        return new ResponseEntity<>("Service Id" + data.getServiceId() + "not found", HttpStatus.NOT_FOUND);

    }
    return responseEntity;
}

From source file:eu.modaclouds.sla.mediator.generation.TierTemplateGenerator.java

private GuaranteeTerm generateGuaranteeTerm(Constraint constraint, MonitoringRule rule, Model model) {

    logger.debug("Generate guaranteeTerm({}, {}, {}", rule.getId(),
            model.getRepository().getJAXBNode().getId());

    GuaranteeTerm gt;//from   w  w  w  .  ja va  2 s.c  o  m
    String outputMetric = QosModels.getOutputMetric(rule);

    if ("".equals(outputMetric)) {
        logger.warn("OutputMetric is not defined. GuaranteeTerm cannot be added to agreement");
        gt = NULL_GUARANTEE_TERM;
        /*
         * fall to return
         */
    } else {

        gt = new GuaranteeTerm();

        gt.setName(rule.getId());

        ServiceScope serviceScope = ServiceScoper.fromConstraint(constraint, model.getRepository());
        gt.setServiceScope(serviceScope);

        ServiceLevelObjective slo = new ServiceLevelObjective();
        KPITarget kpi = new KPITarget();
        kpi.setKpiName(rule.getCollectedMetric().getMetricName());
        try {
            kpi.setCustomServiceLevel(
                    String.format("{\"constraint\": \"%s NOT_EXISTS\", \"qos\": %s, \"aggregation\": %s}",
                            outputMetric, toJson(constraint.getRange()), toJson(rule.getMetricAggregation())));
        } catch (JsonProcessingException e) {
            throw new GeneratorException(e.getMessage(), e);
        }
        slo.setKpitarget(kpi);
        gt.setServiceLevelObjetive(slo);
    }

    return gt;
}

From source file:eu.modaclouds.sla.mediator.generation.TierTemplateGenerator.java

/**
 * Generate a GuaranteeTerm from a s4c-generated rule.
 * /*from  w  ww  .  j  a  v  a 2s .com*/
 * Assumes there is only one rule per seff, that change threshold every hour.
 */
private GuaranteeTerm generateS4cGuaranteeTerm(MonitoringRule rule, Model model) {

    logger.debug("Generate S4C guaranteeTerm({}, {}", rule.getId(),
            model.getRepository().getJAXBNode().getId());

    GuaranteeTerm gt;
    String outputMetric = QosModels.getOutputMetric(rule);

    if ("".equals(outputMetric)) {
        logger.warn("OutputMetric is not defined. GuaranteeTerm cannot be added to agreement");
        gt = NULL_GUARANTEE_TERM;
        /*
         * fall to return
         */
    } else {
        gt = new GuaranteeTerm();

        gt.setName(rule.getId());
        /*
         * TODO: I need an actual example
         */
        ServiceScope serviceScope = ServiceScoper.fromRule(rule, model.getRepository());
        gt.setServiceScope(serviceScope);

        ServiceLevelObjective slo = new ServiceLevelObjective();
        KPITarget kpi = new KPITarget();
        kpi.setKpiName(rule.getCollectedMetric().getMetricName());
        try {
            kpi.setCustomServiceLevel(String.format("{\"constraint\": \"%s NOT_EXISTS\", \"aggregation\": %s}",
                    outputMetric, toJson(rule.getMetricAggregation())));
        } catch (JsonProcessingException e) {
            throw new GeneratorException(e.getMessage(), e);
        }
        slo.setKpitarget(kpi);
        gt.setServiceLevelObjetive(slo);
    }
    return gt;
}

From source file:com.flipkart.foxtrot.core.datastore.impl.hbase.HBaseDataStore.java

@Override
@Timed//from w  ww. jav a 2  s .  c  om
public Document save(final Table table, Document document) throws DataStoreException {
    if (document == null || document.getData() == null || document.getId() == null) {
        throw new DataStoreException(DataStoreException.ErrorCode.STORE_INVALID_REQUEST, "Invalid Document");
    }
    HTableInterface hTable = null;
    Document translatedDocument = null;
    try {
        translatedDocument = translator.translate(table, document);
        hTable = tableWrapper.getTable(table);
        hTable.put(getPutForDocument(table, translatedDocument));
    } catch (JsonProcessingException e) {
        throw new DataStoreException(DataStoreException.ErrorCode.STORE_INVALID_REQUEST, e.getMessage(), e);
    } catch (IOException e) {
        throw new DataStoreException(DataStoreException.ErrorCode.STORE_SINGLE_SAVE, e.getMessage(), e);
    } catch (Exception e) {
        throw new DataStoreException(DataStoreException.ErrorCode.STORE_SINGLE_SAVE, e.getMessage(), e);
    } finally {
        if (null != hTable) {
            try {
                hTable.close();
            } catch (IOException e) {
                logger.error("Error closing table: ", e);
            }
        }
    }
    return translatedDocument;
}

From source file:org.commonjava.aprox.depgraph.rest.RenderingController.java

private File tree(final WebOperationConfigDTO dto) throws AproxWorkflowException {
    final File workBasedir = config.getWorkBasedir();
    String dtoJson;//  w  w  w .j av  a 2s .co  m
    try {
        dtoJson = serializer.writeValueAsString(dto);
    } catch (final JsonProcessingException e) {
        throw new AproxWorkflowException("Failed to serialize to JSON: %s", e, e.getMessage());
    }

    final File out = new File(workBasedir, DigestUtils.md5Hex(dtoJson));
    workBasedir.mkdirs();

    final GraphComposition comp = resolve(dto);
    FileWriter w = null;
    try {
        w = new FileWriter(out);
        ops.depTree(dto.getWorkspaceId(), comp, false, new PrintWriter(w));
    } catch (final CartoDataException e) {
        throw new AproxWorkflowException("Failed to generate dependency tree. Reason: {}", e, e.getMessage());
    } catch (final IOException e) {
        throw new AproxWorkflowException("Failed to open work file for caching output: {}. Reason: {}", e, out,
                e.getMessage());
    } finally {
        IOUtils.closeQuietly(w);
    }

    return out;
}