Search in sources :

Example 11 with JacksonException

use of com.fasterxml.jackson.core.JacksonException in project briar by briar.

the class MailboxApiImpl method setup.

@Override
public MailboxAuthToken setup(MailboxProperties properties) throws IOException, ApiException {
    if (!properties.isOwner())
        throw new IllegalArgumentException();
    Request request = getRequestBuilder(properties.getAuthToken()).url(properties.getBaseUrl() + "/setup").put(EMPTY_REQUEST).build();
    OkHttpClient client = httpClientProvider.get();
    Response response = client.newCall(request).execute();
    if (response.code() == 401)
        throw new MailboxAlreadyPairedException();
    if (!response.isSuccessful())
        throw new ApiException();
    ResponseBody body = response.body();
    if (body == null)
        throw new ApiException();
    try {
        JsonNode node = mapper.readTree(body.string());
        JsonNode tokenNode = node.get("token");
        if (tokenNode == null) {
            throw new ApiException();
        }
        String ownerToken = tokenNode.textValue();
        return MailboxAuthToken.fromString(ownerToken);
    } catch (JacksonException | InvalidMailboxIdException e) {
        throw new ApiException();
    }
}
Also used : Response(okhttp3.Response) JacksonException(com.fasterxml.jackson.core.JacksonException) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) JsonNode(com.fasterxml.jackson.databind.JsonNode) ResponseBody(okhttp3.ResponseBody) InvalidMailboxIdException(org.briarproject.bramble.api.mailbox.InvalidMailboxIdException)

Example 12 with JacksonException

use of com.fasterxml.jackson.core.JacksonException in project elide by yahoo.

the class Elide method handleRequest.

/**
 * Handle JSON API requests.
 *
 * @param isReadOnly if the transaction is read only
 * @param user the user object from the container
 * @param transaction a transaction supplier
 * @param requestId the Request ID
 * @param handler a function that creates the request scope and request handler
 * @return the response
 */
protected ElideResponse handleRequest(boolean isReadOnly, User user, Supplier<DataStoreTransaction> transaction, UUID requestId, Handler<DataStoreTransaction, User, HandlerResult> handler) {
    boolean isVerbose = false;
    try (DataStoreTransaction tx = transaction.get()) {
        transactionRegistry.addRunningTransaction(requestId, tx);
        HandlerResult result = handler.handle(tx, user);
        RequestScope requestScope = result.getRequestScope();
        isVerbose = requestScope.getPermissionExecutor().isVerbose();
        Supplier<Pair<Integer, JsonNode>> responder = result.getResponder();
        tx.preCommit(requestScope);
        requestScope.runQueuedPreSecurityTriggers();
        requestScope.getPermissionExecutor().executeCommitChecks();
        requestScope.runQueuedPreFlushTriggers();
        if (!isReadOnly) {
            requestScope.saveOrCreateObjects();
        }
        tx.flush(requestScope);
        requestScope.runQueuedPreCommitTriggers();
        ElideResponse response = buildResponse(responder.get());
        auditLogger.commit();
        tx.commit(requestScope);
        requestScope.runQueuedPostCommitTriggers();
        if (log.isTraceEnabled()) {
            requestScope.getPermissionExecutor().logCheckStats();
        }
        return response;
    } catch (JacksonException e) {
        String message = (e.getLocation() != null && e.getLocation().getSourceRef() != null) ? // This will leak Java class info if the location isn't known.
        e.getMessage() : e.getOriginalMessage();
        return buildErrorResponse(new BadRequestException(message), isVerbose);
    } catch (IOException e) {
        log.error("IO Exception uncaught by Elide", e);
        return buildErrorResponse(new TransactionException(e), isVerbose);
    } catch (RuntimeException e) {
        return handleRuntimeException(e, isVerbose);
    } finally {
        transactionRegistry.removeRunningTransaction(requestId);
        auditLogger.clear();
    }
}
Also used : JacksonException(com.fasterxml.jackson.core.JacksonException) IOException(java.io.IOException) PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) RequestScope(com.yahoo.elide.core.RequestScope) TransactionException(com.yahoo.elide.core.exceptions.TransactionException) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) Pair(org.apache.commons.lang3.tuple.Pair)

Example 13 with JacksonException

use of com.fasterxml.jackson.core.JacksonException in project jackson-jr by FasterXML.

the class BeanReader method readNext.

@Override
public Object readNext(JSONReader r, JsonParser p) throws JacksonException {
    JsonToken t = p.nextToken();
    if (t == JsonToken.START_OBJECT) {
        final Object bean;
        try {
            bean = create();
        } catch (Exception e) {
            return _reportFailureToCreate(p, e);
        }
        p.assignCurrentValue(bean);
        return _readBean(r, p, bean);
    }
    if (t != null) {
        try {
            switch(t) {
                case VALUE_NULL:
                    return null;
                case VALUE_STRING:
                    return create(p.getText());
                case VALUE_NUMBER_INT:
                    return create(p.getLongValue());
                default:
            }
        } catch (Exception e) {
            return _reportFailureToCreate(p, e);
        }
    }
    throw JSONObjectException.from(p, "Can not create a %s instance out of %s", _valueType.getName(), _tokenDesc(p));
}
Also used : JsonToken(com.fasterxml.jackson.core.JsonToken) JSONObjectException(com.fasterxml.jackson.jr.ob.JSONObjectException) JacksonException(com.fasterxml.jackson.core.JacksonException)

Example 14 with JacksonException

use of com.fasterxml.jackson.core.JacksonException in project buessionframework by buession.

the class MimeTypeStringDeserializer method deserialize.

@Override
public MimeType deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JacksonException {
    Object currentValue = jsonParser.getCurrentValue();
    Class<?> clazz = currentValue.getClass();
    if (clazz.isAssignableFrom(String.class)) {
        try {
            return MimeType.parse(currentValue.toString());
        } catch (Exception e) {
            throw new JsonParseException(jsonParser, e.getMessage(), jsonParser.getCurrentLocation(), e);
        }
    }
    throw new JsonParseException(jsonParser, clazz.getName() + " cloud not deserialize to: " + MimeType.class.getName(), jsonParser.getCurrentLocation());
}
Also used : JsonParseException(com.fasterxml.jackson.core.JsonParseException) IOException(java.io.IOException) JacksonException(com.fasterxml.jackson.core.JacksonException) JsonParseException(com.fasterxml.jackson.core.JsonParseException)

Example 15 with JacksonException

use of com.fasterxml.jackson.core.JacksonException in project tracdap by finos.

the class CsvDecoder method decodeChunk.

@Override
protected void decodeChunk(ByteBuf chunk) {
    var csvFactory = new CsvFactory().enable(CsvParser.Feature.TRIM_SPACES).enable(CsvParser.Feature.FAIL_ON_MISSING_COLUMNS);
    try (var stream = new ByteBufInputStream(chunk);
        var parser = (CsvParser) csvFactory.createParser((InputStream) stream)) {
        var csvSchema = CsvSchemaMapping.arrowToCsv(this.arrowSchema).build();
        csvSchema = DEFAULT_HEADER_FLAG ? csvSchema.withHeader() : csvSchema.withoutHeader();
        parser.setSchema(csvSchema);
        var row = 0;
        var col = 0;
        JsonToken token;
        while ((token = parser.nextToken()) != null) {
            switch(token) {
                // For CSV files, a null field name is produced for every field
                case FIELD_NAME:
                    continue;
                case VALUE_NULL:
                case VALUE_TRUE:
                case VALUE_FALSE:
                case VALUE_STRING:
                case VALUE_NUMBER_INT:
                case VALUE_NUMBER_FLOAT:
                    var vector = root.getVector(col);
                    JacksonValues.parseAndSet(vector, row, parser, token);
                    col++;
                    break;
                case START_OBJECT:
                    if (row == 0)
                        for (var vector_ : root.getFieldVectors()) vector_.allocateNew();
                    break;
                case END_OBJECT:
                    row++;
                    col = 0;
                    if (row == BATCH_SIZE) {
                        root.setRowCount(row);
                        dispatchBatch(root);
                        row = 0;
                    }
                    break;
                default:
                    var msg = String.format("Unexpected token %s", token.name());
                    throw new CsvReadException(parser, msg, csvSchema);
            }
        }
        if (row > 0 || col > 0) {
            root.setRowCount(row);
            dispatchBatch(root);
        }
    } catch (JacksonException e) {
        // This exception is a "well-behaved" parse failure, parse location and message should be meaningful
        var errorMessage = String.format("CSV decoding failed on line %d: %s", e.getLocation().getLineNr(), e.getOriginalMessage());
        log.error(errorMessage, e);
        throw new EDataCorruption(errorMessage, e);
    } catch (IOException e) {
        // Decoders work on a stream of buffers, "real" IO exceptions should not occur
        // IO exceptions here indicate parse failures, not file/socket communication errors
        // This is likely to be a more "badly-behaved" failure, or at least one that was not anticipated
        var errorMessage = "CSV decoding failed, content is garbled: " + e.getMessage();
        log.error(errorMessage, e);
        throw new EDataCorruption(errorMessage, e);
    } catch (Throwable e) {
        // Ensure unexpected errors are still reported to the Flow API
        log.error("Unexpected error in CSV decoding", e);
        throw new EUnexpected(e);
    } finally {
        chunk.release();
    }
}
Also used : CsvFactory(com.fasterxml.jackson.dataformat.csv.CsvFactory) JacksonException(com.fasterxml.jackson.core.JacksonException) CsvReadException(com.fasterxml.jackson.dataformat.csv.CsvReadException) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) InputStream(java.io.InputStream) EDataCorruption(com.accenture.trac.common.exception.EDataCorruption) CsvParser(com.fasterxml.jackson.dataformat.csv.CsvParser) JsonToken(com.fasterxml.jackson.core.JsonToken) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) IOException(java.io.IOException) EUnexpected(com.accenture.trac.common.exception.EUnexpected)

Aggregations

JacksonException (com.fasterxml.jackson.core.JacksonException)17 IOException (java.io.IOException)9 JsonToken (com.fasterxml.jackson.core.JsonToken)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 ArrayList (java.util.ArrayList)4 Response (okhttp3.Response)4 ResponseBody (okhttp3.ResponseBody)4 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)3 InvalidMailboxIdException (org.briarproject.bramble.api.mailbox.InvalidMailboxIdException)3 EDataCorruption (com.accenture.trac.common.exception.EDataCorruption)2 EUnexpected (com.accenture.trac.common.exception.EUnexpected)2 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)2 JsonParseException (com.fasterxml.jackson.core.JsonParseException)2 JsonParser (com.fasterxml.jackson.core.JsonParser)2 TreeNode (com.fasterxml.jackson.core.TreeNode)2 DeserializationContext (com.fasterxml.jackson.databind.DeserializationContext)2 SerializerProvider (com.fasterxml.jackson.databind.SerializerProvider)2 SimpleModule (com.fasterxml.jackson.databind.module.SimpleModule)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 CsvFactory (com.fasterxml.jackson.dataformat.csv.CsvFactory)2