Search in sources :

Example 11 with JsonParseException

use of com.fasterxml.jackson.core.JsonParseException in project qpid-broker-j by apache.

the class CompressedResponsesTest method doCompressionTest.

private void doCompressionTest(final boolean allowCompression, final boolean acceptCompressed) throws Exception {
    final boolean expectCompression = allowCompression && acceptCompressed;
    getHelper().submitRequest("plugin/httpManagement", "POST", Collections.singletonMap("compressResponses", expectCompression), SC_OK);
    HttpURLConnection conn = getHelper().openManagementConnection("/service/metadata", "GET");
    try {
        if (acceptCompressed) {
            conn.setRequestProperty("Accept-Encoding", "gzip");
        }
        conn.connect();
        String contentEncoding = conn.getHeaderField("Content-Encoding");
        if (expectCompression) {
            assertEquals("gzip", contentEncoding);
        } else {
            if (contentEncoding != null) {
                assertEquals("identity", contentEncoding);
            }
        }
        byte[] bytes;
        try (ByteArrayOutputStream contentBuffer = new ByteArrayOutputStream()) {
            ByteStreams.copy(conn.getInputStream(), contentBuffer);
            bytes = contentBuffer.toByteArray();
        }
        try (InputStream jsonStream = expectCompression ? new GZIPInputStream(new ByteArrayInputStream(bytes)) : new ByteArrayInputStream(bytes)) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                mapper.readValue(jsonStream, LinkedHashMap.class);
            } catch (JsonParseException | JsonMappingException e) {
                fail("Message was not in correct format");
            }
        }
    } finally {
        conn.disconnect();
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) HttpURLConnection(java.net.HttpURLConnection) ByteArrayInputStream(java.io.ByteArrayInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonParseException(com.fasterxml.jackson.core.JsonParseException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 12 with JsonParseException

use of com.fasterxml.jackson.core.JsonParseException in project curiostack by curioswitch.

the class ParseSupport method parseUInt64.

/**
 * Parsers a uint64 value out of the input.
 */
static long parseUInt64(JsonParser parser) throws IOException {
    // cover the vast majority of cases.
    try {
        long result = parseLong(parser);
        if (result >= 0) {
            // Only need to check the uint32 range if the parsed long is negative.
            return result;
        }
    } catch (JsonParseException | NumberFormatException e) {
    // Fall through.
    }
    final BigInteger value;
    try {
        BigDecimal decimal = new BigDecimal(parser.getTextCharacters(), parser.getTextOffset(), parser.getTextLength());
        value = decimal.toBigIntegerExact();
    } catch (ArithmeticException | NumberFormatException e) {
        throw new InvalidProtocolBufferException("Not an uint64 value: " + parser.getText());
    }
    if (value.compareTo(BigInteger.ZERO) < 0 || value.compareTo(MAX_UINT64) > 0) {
        throw new InvalidProtocolBufferException("Out of range uint64 value: " + parser.getText());
    }
    return value.longValue();
}
Also used : InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) BigInteger(java.math.BigInteger) JsonParseException(com.fasterxml.jackson.core.JsonParseException) BigDecimal(java.math.BigDecimal)

Example 13 with JsonParseException

use of com.fasterxml.jackson.core.JsonParseException in project nifi by apache.

the class SiteToSiteRestApiClient method execute.

private <T> T execute(final HttpGet get, final Class<T> entityClass) throws IOException {
    get.setHeader("Accept", "application/json");
    final String responseMessage = execute(get);
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    try {
        return mapper.readValue(responseMessage, entityClass);
    } catch (JsonParseException e) {
        final String msg = "Failed to parse Json. The specified URL " + baseUrl + " is not a proper remote NiFi endpoint for Site-to-Site communication.";
        logger.warn("{} requestedUrl={}, response={}", msg, get.getURI(), responseMessage);
        throw new IOException(msg, e);
    }
}
Also used : IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 14 with JsonParseException

use of com.fasterxml.jackson.core.JsonParseException in project tika by apache.

the class YandexTranslator method translate.

@Override
public String translate(String text, String sourceLanguage, String targetLanguage) throws TikaException, IOException {
    if (!this.isAvailable()) {
        return text;
    }
    WebClient client = WebClient.create(YANDEX_TRANSLATE_URL_BASE);
    String langCode;
    if (sourceLanguage == null) {
        //Translate Service will identify source language
        langCode = targetLanguage;
    } else {
        //Source language is well known
        langCode = sourceLanguage + '-' + targetLanguage;
    }
    //TODO Add support for text over 10k characters
    Response response = client.accept(MediaType.APPLICATION_JSON).query("key", this.apiKey).query("lang", langCode).query("text", text).get();
    BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) response.getEntity(), UTF_8));
    String line = null;
    StringBuffer responseText = new StringBuffer();
    while ((line = reader.readLine()) != null) {
        responseText.append(line);
    }
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonResp = mapper.readTree(responseText.toString());
        if (!jsonResp.findValuesAsText("code").isEmpty()) {
            String code = jsonResp.findValuesAsText("code").get(0);
            if (code.equals("200")) {
                return jsonResp.findValue("text").get(0).asText();
            } else {
                throw new TikaException(jsonResp.findValue("message").get(0).asText());
            }
        } else {
            throw new TikaException("Return message not recognized: " + responseText.toString().substring(0, Math.min(responseText.length(), 100)));
        }
    } catch (JsonParseException e) {
        throw new TikaException("Error requesting translation from '" + sourceLanguage + "' to '" + targetLanguage + "', JSON response from Lingo24 is not well formatted: " + responseText.toString());
    }
}
Also used : Response(javax.ws.rs.core.Response) TikaException(org.apache.tika.exception.TikaException) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonParseException(com.fasterxml.jackson.core.JsonParseException) WebClient(org.apache.cxf.jaxrs.client.WebClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 15 with JsonParseException

use of com.fasterxml.jackson.core.JsonParseException in project tika by apache.

the class JoshuaNetworkTranslator method translate.

/**
   * <p>Initially then check if the source language has been provided.
   * If no source language (or a null value) has been provided then
   * we make an attempt to guess the source using Tika's
   * {@link org.apache.tika.langdetect.OptimaizeLangDetector}. If we
   * are still unable to guess the language then we return the source
   * text.</p>
   * 
   * <p>We then process the input text into a new string consisting of 
   * sentences, one per line e.g. insert \n between the presence of '.'</p>
   * 
   * @see org.apache.tika.language.translate.Translator#translate
   * (java.lang.String, java.lang.String, java.lang.String)
   */
@Override
public String translate(String text, String sourceLanguage, String targetLanguage) throws TikaException, IOException {
    //create networkURI
    if (!networkServer.endsWith("/")) {
        networkURI = networkServer + "/" + targetLanguage;
    } else {
        networkURI = networkServer + targetLanguage;
    }
    if (!this.isAvailable())
        return text;
    //make an attempt to guess language if one is not provided.
    if (sourceLanguage == null)
        sourceLanguage = detectLanguage(text).getLanguage();
    //process input text into sentences, one per line 
    // e.g. insert \n between the presence of '.'
    StringBuilder sb = new StringBuilder(text);
    int i = 0;
    while ((i = sb.indexOf(".", i + 1)) != -1) {
        sb.replace(i, i + 1, "\n");
    }
    String inputText = sb.toString();
    WebClient client;
    final List<Object> providers = new ArrayList<>();
    JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider();
    providers.add(jacksonJsonProvider);
    client = WebClient.create(networkURI, providers);
    ObjectMapper requestMapper = new ObjectMapper();
    ObjectNode jsonNode = requestMapper.createObjectNode();
    jsonNode.put("inputLanguage", sourceLanguage);
    jsonNode.put("inputText", inputText);
    //make the reuest
    Response response = client.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(jsonNode);
    BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) response.getEntity(), UTF_8));
    String line;
    StringBuilder responseText = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        responseText.append(line);
    }
    try {
        ObjectMapper responseMapper = new ObjectMapper();
        JsonNode jsonResp = responseMapper.readTree(responseText.toString());
        if (jsonResp.findValuesAsText("outputText") != null) {
            return jsonResp.findValuesAsText("outputText").get(0);
        } else {
            throw new TikaException(jsonResp.findValue("message").get(0).asText());
        }
    } catch (JsonParseException e) {
        throw new TikaException("Error requesting translation from '" + sourceLanguage + "' to '" + targetLanguage + "', JSON response " + "from Joshua REST Server is not well formatted: " + responseText.toString());
    }
}
Also used : TikaException(org.apache.tika.exception.TikaException) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonParseException(com.fasterxml.jackson.core.JsonParseException) WebClient(org.apache.cxf.jaxrs.client.WebClient) Response(javax.ws.rs.core.Response) BufferedReader(java.io.BufferedReader) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

JsonParseException (com.fasterxml.jackson.core.JsonParseException)120 IOException (java.io.IOException)59 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)53 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)31 JsonParser (com.fasterxml.jackson.core.JsonParser)21 Map (java.util.Map)15 JsonNode (com.fasterxml.jackson.databind.JsonNode)14 Test (org.junit.Test)14 ArrayList (java.util.ArrayList)13 InputStream (java.io.InputStream)12 HashMap (java.util.HashMap)12 JsonToken (com.fasterxml.jackson.core.JsonToken)11 JsonFactory (com.fasterxml.jackson.core.JsonFactory)9 File (java.io.File)9 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)7 JsonLocation (com.fasterxml.jackson.core.JsonLocation)6 Date (java.util.Date)5 GZIPInputStream (java.util.zip.GZIPInputStream)5 TypeReference (com.fasterxml.jackson.core.type.TypeReference)4 Maps.newHashMap (com.google.common.collect.Maps.newHashMap)4