Example usage for com.fasterxml.jackson.databind JsonMappingException getMessage

List of usage examples for com.fasterxml.jackson.databind JsonMappingException getMessage

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonMappingException getMessage.

Prototype

public String getMessage() 

Source Link

Usage

From source file:com.inferlytics.druidlet.resource.DruidResource.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//from   w  w  w.j  a v a2 s .  c o  m
@Produces(MediaType.APPLICATION_JSON)
public Response query(@Context HttpServletRequest req, String queryJson) {
    try {
        String indexKey = String.valueOf(req.getServerPort());
        return Response.ok(Utils.JSON_MAPPER.writeValueAsString(DruidService.handleQuery(indexKey, queryJson)))
                .build();
    } catch (JsonMappingException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity(new FailureResponse(e.getMessage())).build();
    } catch (Exception e) {
        LOG.error("Exception while handling query", e);
        return Response.serverError().entity(new FailureResponse("Internal Server Error")).build();
    }
}

From source file:com.expedia.seiso.web.controller.ExceptionHandlerAdvice.java

@ExceptionHandler(JsonMappingException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)//from w w  w  . j a va  2s  . c o m
@ResponseBody
public ErrorObject handleJsonMappingException(JsonMappingException e, WebRequest request) {
    return new ErrorObject(C.EC_INVALID_REQUEST_JSON_PAYLOAD, e.getMessage());
}

From source file:org.springframework.web.socket.sockjs.transport.AbstractHttpReceivingTransportHandler.java

protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response,
        AbstractSockJsSession session) throws TransportErrorException {

    String[] messages = null;/*from w ww. jav  a2s .c o  m*/
    try {
        messages = readMessages(request);
    } catch (JsonMappingException ex) {
        logger.error("Failed to read message: " + ex.getMessage());
        sendInternalServerError(response, "Payload expected.", session.getId());
        return;
    } catch (IOException ex) {
        logger.error("Failed to read message: " + ex.getMessage());
        sendInternalServerError(response, "Broken JSON encoding.", session.getId());
        return;
    } catch (Throwable t) {
        logger.error("Failed to read message: " + t.getMessage());
        sendInternalServerError(response, "Failed to process messages", session.getId());
        return;
    }

    if (messages == null) {
        sendInternalServerError(response, "Payload expected.", session.getId());
        return;
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Received message(s): " + Arrays.asList(messages));
    }

    response.setStatusCode(getResponseStatus());
    response.getHeaders().setContentType(new MediaType("text", "plain", Charset.forName("UTF-8")));

    try {
        session.delegateMessages(messages);
    } catch (Throwable t) {
        ExceptionWebSocketHandlerDecorator.tryCloseWithError(session, t, logger);
        throw new TransportErrorException("Unhandled WebSocketHandler error in " + this, t, session.getId());
    }
}

From source file:org.osiam.resources.exception.OsiamExceptionHandler.java

@ExceptionHandler(JsonMappingException.class)
@ResponseStatus(HttpStatus.CONFLICT)//from   ww w . j a va  2 s .co  m
@ResponseBody
public ErrorResponse handleJsonMapping(JsonMappingException e) {
    LOGGER.error("Unable to deserialize", e);
    return produceErrorResponse(e.getMessage(), HttpStatus.CONFLICT, new JsonMappingMessageTransformer());
}

From source file:com.flipkart.poseidon.serviceclients.ServiceResponseDecoder.java

@Override
public ServiceResponse<T> decode(HttpResponse httpResponse) throws Exception {
    Map<String, String> headers = getHeaders(httpResponse);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    String statusCodeString = String.valueOf(statusCode);
    if (statusCode >= 200 && statusCode <= 299) {
        if (statusCode == 204) {
            return new ServiceResponse<T>((T) null, headers);
        } else {/*w  w  w .j  ava2  s . c  o m*/
            try {
                // Don't deserialize a plain string response using jackson
                if (String.class.isAssignableFrom(javaType.getRawClass())) {
                    return new ServiceResponse<T>((T) IOUtils.toString(httpResponse.getEntity().getContent()),
                            headers);
                }
                return new ServiceResponse<T>(
                        objectMapper.<T>readValue(httpResponse.getEntity().getContent(), javaType), headers);
            } catch (JsonMappingException e) {
                if (e.getMessage().contains("No content to map due to end-of-input")) {
                    return new ServiceResponse<T>((T) null, headers);
                } else {
                    logger.error("Error de-serializing response object exception: {}", e.getMessage());
                    throw new IOException("Response object de-serialization error", e);
                }
            } catch (Exception e) {
                logger.error("Error de-serializing response object exception: {}", e.getMessage());
                throw new IOException("Response object de-serialization error", e);
            }
        }
    } else {
        String serviceResponse = StringUtils.convertStreamToString(httpResponse.getEntity().getContent());
        Object errorResponse = null;
        if (errorType != null) {
            try {
                errorResponse = objectMapper.readValue(serviceResponse, errorType);
            } catch (Exception e) {
                logger.warn(
                        "Error while de-serializing non 200 response to given errorType statusCode:{} exception: {}",
                        statusCodeString, e.getMessage());
            }
        }
        Class<? extends ServiceClientException> exceptionClass;
        if (exceptions.containsKey(statusCodeString)) {
            exceptionClass = exceptions.get(statusCodeString);
        } else {
            exceptionClass = exceptions.get("default");
        }

        String exceptionMessage = statusCodeString + " " + serviceResponse;
        ServiceClientException serviceClientException = exceptionClass
                .getConstructor(String.class, Object.class).newInstance(exceptionMessage, errorResponse);
        if (statusCode >= 500 && statusCode <= 599) {
            // 5xx errors have to be treated as hystrix command failures. Hence throw service client exception.
            logger.error("Non 200 response statusCode: {} response: {}", statusCodeString, serviceResponse);
            throw serviceClientException;
        } else {
            // Rest of non 2xx don't have to be treated as hystrix command failures (ex: validation failure resulting in 400)
            logger.debug("Non 200 response statusCode: {} response: {}", statusCodeString, serviceResponse);
            return new ServiceResponse<T>(serviceClientException, headers);
        }
    }
}

From source file:se.bitcraze.crazyflie.lib.toc.TocCache.java

/**
 * Save a new cache to file//from w w  w .j  a va  2s . com
 */
public void insert(int crc, CrtpPort port, Toc toc) {
    String fileName = String.format("%08X.json", crc);
    String subDir = (port == CrtpPort.PARAMETERS) ? PARAM_CACHE_DIR : LOG_CACHE_DIR;
    File cacheDir = (mCacheDir != null) ? new File(mCacheDir, subDir) : new File(subDir);
    File cacheFile = new File(cacheDir, fileName);
    try {
        if (!cacheFile.exists()) {
            cacheFile.getParentFile().mkdirs();
            cacheFile.createNewFile();
        }
        this.mMapper.enable(SerializationFeature.INDENT_OUTPUT);
        this.mMapper.writeValue(cacheFile, toc.getTocElementMap());
        //TODO: add "__class__" : "LogTocElement",
        this.mLogger.info("Saved cache to " + fileName);
        this.mCacheFiles.add(cacheFile);
        //TODO: file leak?
    } catch (JsonGenerationException jge) {
        mLogger.error("Could not save cache to file " + fileName + ".\n" + jge.getMessage());
    } catch (JsonMappingException jme) {
        mLogger.error("Could not save cache to file " + fileName + ".\n" + jme.getMessage());
    } catch (IOException ioe) {
        mLogger.error("Could not save cache to file " + fileName + ".\n" + ioe.getMessage());
    }
}

From source file:se.bitcraze.crazyflielib.toc.TocCache.java

/**
 * Try to get a hit in the cache, return None otherwise
 *
 * @param crc CRC code of the TOC//from  w ww  .  j  a v  a2s  . c o  m
 * @param port CrtpPort of the TOC
 */
public Toc fetch(int crc, CrtpPort port) {
    Toc fetchedToc = null;
    String pattern = String.format("%08X.json", crc);
    File hit = null;

    mLogger.debug("Trying to find existing TOC cache file: " + pattern);

    for (File file : mCacheFiles) {
        if (file.getName().endsWith(pattern)) {
            hit = file;
        }
    }
    if (hit != null) {
        mLogger.debug("Found TOC cache file: " + pattern);
        try {
            fetchedToc = new Toc();
            Map<String, TocElement> readValue;
            //                if (port == CrtpPort.PARAMETERS) {
            readValue = mMapper.readValue(hit, new TypeReference<Map<String, ParamTocElement>>() {
            });
            //                } else {
            //                    readValue = mMapper.readValue(hit, new TypeReference<Map<String, LogTocElement>>() { });
            //                }
            fetchedToc.setTocElementMap(readValue);
            mLogger.debug("Number of cached elements: " + fetchedToc.getElements().size());
            //TODO: file leak?
        } catch (JsonParseException jpe) {
            mLogger.error("Error while parsing cache file " + hit.getName() + ": " + jpe.getMessage());
            return null;
        } catch (JsonMappingException jme) {
            mLogger.error("Error while parsing cache file " + hit.getName() + ": " + jme.getMessage());
            return null;
        } catch (IOException ioe) {
            mLogger.error("Error while parsing cache file " + hit.getName() + ": " + ioe.getMessage());
            return null;
        }
    }
    return fetchedToc;
}

From source file:se.bitcraze.crazyflie.lib.toc.TocCache.java

/**
 * Try to get a hit in the cache, return None otherwise
 *
 * @param crc CRC code of the TOC//from   w ww. ja  v  a  2 s.c om
 * @param port CrtpPort of the TOC
 */
public Toc fetch(int crc, CrtpPort port) {
    Toc fetchedToc = null;
    String pattern = String.format("%08X.json", crc);
    File hit = null;

    mLogger.debug("Trying to find existing TOC cache file: " + pattern);

    for (File file : mCacheFiles) {
        if (file.getName().endsWith(pattern)) {
            hit = file;
        }
    }
    if (hit != null) {
        mLogger.debug("Found TOC cache file: " + pattern);
        try {
            fetchedToc = new Toc();
            Map<String, TocElement> readValue;
            if (port == CrtpPort.PARAMETERS) {
                readValue = mMapper.readValue(hit, new TypeReference<Map<String, ParamTocElement>>() {
                });
            } else {
                readValue = mMapper.readValue(hit, new TypeReference<Map<String, LogTocElement>>() {
                });
            }
            fetchedToc.setTocElementMap(readValue);
            mLogger.debug("Number of cached elements: " + fetchedToc.getElements().size());
            //TODO: file leak?
        } catch (JsonParseException jpe) {
            mLogger.error("Error while parsing cache file " + hit.getName() + ": " + jpe.getMessage());
            return null;
        } catch (JsonMappingException jme) {
            mLogger.error("Error while parsing cache file " + hit.getName() + ": " + jme.getMessage());
            return null;
        } catch (IOException ioe) {
            mLogger.error("Error while parsing cache file " + hit.getName() + ": " + ioe.getMessage());
            return null;
        }
    }
    return fetchedToc;
}

From source file:fi.hsl.parkandride.front.ExceptionHandlers.java

@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<Map<String, Object>> jsonException(HttpServletRequest request,
        HttpMessageNotReadableException ex) {
    if (ex.getCause() instanceof JsonMappingException) {
        JsonMappingException jsonEx = (JsonMappingException) ex.getCause();
        String path = getPath(jsonEx);
        Violation violation = new Violation("TypeMismatch", path, jsonEx.getMessage());
        return handleError(request, BAD_REQUEST, ex, "Invalid input", ImmutableList.of(violation));
    }/*  w  w w.j a  v a 2  s.  co m*/
    return handleError(request, BAD_REQUEST, ex);
}

From source file:ws.doerr.cssinliner.server.InlinerApp.java

private void processHandlebars(SourceInstance instance) throws IOException {
    try (FileWriter writer = new FileWriter(instance.getMerged().toFile())) {
        Template template = handlebars.compile(instance.getInlined().getFileName().toString());
        JsonNode data = Server.getMapper().readTree(instance.getData().toFile());
        Context handlebarsContext = Context.newBuilder(data).resolver(JsonNodeValueResolver.INSTANCE).build();

        template.apply(handlebarsContext, writer);
    } catch (JsonMappingException ex) {
        instance.logError("JSON", ex.getMessage());
        Files.copy(instance.getInlined().toFile(), instance.getMerged().toFile());
    } catch (HandlebarsException ex) {
        instance.logError("Handlebars", ex.getError().reason);
        Files.copy(instance.getInlined().toFile(), instance.getMerged().toFile());
        LOG.log(Level.WARNING, "", ex);
    } catch (FileNotFoundException ex) {
        instance.logError("JSON", "No JSON data file found");
        Files.copy(instance.getInlined().toFile(), instance.getMerged().toFile());
    } catch (Exception ex) {
        instance.logError(ex.getClass().getSimpleName(), ex.getMessage());
        Files.copy(instance.getInlined().toFile(), instance.getMerged().toFile());
        LOG.log(Level.WARNING, "", ex);
    }// ww  w.  j  a v a  2 s.  c o m
}