Search in sources :

Example 16 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project asterixdb by apache.

the class ResultState method toString.

@Override
public String toString() {
    try {
        ObjectMapper om = new ObjectMapper();
        ObjectNode on = om.createObjectNode();
        on.put("rspid", resultSetPartitionId.toString());
        on.put("async", asyncMode);
        on.put("eos", eos.get());
        on.put("failed", failed.get());
        on.put("fileRef", String.valueOf(fileRef));
        return om.writer(new MinimalPrettyPrinter()).writeValueAsString(on);
    } catch (JsonProcessingException e) {
        // NOSONAR
        return e.getMessage();
    }
}
Also used : MinimalPrettyPrinter(com.fasterxml.jackson.core.util.MinimalPrettyPrinter) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 17 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project spring-framework by spring-projects.

the class AbstractJackson2HttpMessageConverter method writeInternal.

@Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    MediaType contentType = outputMessage.getHeaders().getContentType();
    JsonEncoding encoding = getJsonEncoding(contentType);
    JsonGenerator generator = this.objectMapper.getFactory().createGenerator(outputMessage.getBody(), encoding);
    try {
        writePrefix(generator, object);
        Class<?> serializationView = null;
        FilterProvider filters = null;
        Object value = object;
        JavaType javaType = null;
        if (object instanceof MappingJacksonValue) {
            MappingJacksonValue container = (MappingJacksonValue) object;
            value = container.getValue();
            serializationView = container.getSerializationView();
            filters = container.getFilters();
        }
        if (type != null && value != null && TypeUtils.isAssignable(type, value.getClass())) {
            javaType = getJavaType(type, null);
        }
        ObjectWriter objectWriter;
        if (serializationView != null) {
            objectWriter = this.objectMapper.writerWithView(serializationView);
        } else if (filters != null) {
            objectWriter = this.objectMapper.writer(filters);
        } else {
            objectWriter = this.objectMapper.writer();
        }
        if (javaType != null && javaType.isContainerType()) {
            objectWriter = objectWriter.forType(javaType);
        }
        SerializationConfig config = objectWriter.getConfig();
        if (contentType != null && contentType.isCompatibleWith(MediaType.TEXT_EVENT_STREAM) && config.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
            objectWriter = objectWriter.with(this.ssePrettyPrinter);
        }
        objectWriter.writeValue(generator, value);
        writeSuffix(generator, object);
        generator.flush();
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write content: " + ex.getMessage(), ex);
    }
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) JsonEncoding(com.fasterxml.jackson.core.JsonEncoding) SerializationConfig(com.fasterxml.jackson.databind.SerializationConfig) MediaType(org.springframework.http.MediaType) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) FilterProvider(com.fasterxml.jackson.databind.ser.FilterProvider)

Example 18 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project cas by apereo.

the class TicketsResource method createTicketGrantingTicket.

/**
     * Create new ticket granting ticket.
     *
     * @param requestBody username and password application/x-www-form-urlencoded values
     * @param request     raw HttpServletRequest used to call this method
     * @return ResponseEntity representing RESTful response
     * @throws JsonProcessingException in case of JSON parsing failure
     */
@PostMapping(value = "/v1/tickets", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createTicketGrantingTicket(@RequestBody final MultiValueMap<String, String> requestBody, final HttpServletRequest request) throws JsonProcessingException {
    try {
        final Credential credential = this.credentialFactory.fromRequestBody(requestBody);
        final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(null, credential);
        final TicketGrantingTicket tgtId = this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
        final URI ticketReference = new URI(request.getRequestURL().toString() + '/' + tgtId.getId());
        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ticketReference);
        headers.setContentType(MediaType.TEXT_HTML);
        final String tgtUrl = ticketReference.toString();
        final String response = new StringBuilder(SUCCESSFUL_TGT_CREATED_INITIAL_LENGTH + tgtUrl.length()).append(DOCTYPE_AND_OPENING_FORM).append(tgtUrl).append(REST_OF_THE_FORM_AND_CLOSING_TAGS).toString();
        return new ResponseEntity<>(response, headers, HttpStatus.CREATED);
    } catch (final AuthenticationException e) {
        final List<String> authnExceptions = e.getHandlerErrors().values().stream().map(Class::getSimpleName).collect(Collectors.toList());
        final Map<String, List<String>> errorsMap = new HashMap<>();
        errorsMap.put("authentication_exceptions", authnExceptions);
        LOGGER.error("[{}] Caused by: [{}]", e.getMessage(), authnExceptions, e);
        try {
            return new ResponseEntity<>(this.jacksonPrettyWriter.writeValueAsString(errorsMap), HttpStatus.UNAUTHORIZED);
        } catch (final JsonProcessingException exception) {
            LOGGER.error(e.getMessage(), e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    } catch (final BadRequestException e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    } catch (final Throwable e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Credential(org.apereo.cas.authentication.Credential) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) URI(java.net.URI) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) ResponseEntity(org.springframework.http.ResponseEntity) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 19 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project ratpack by ratpack.

the class JsonRenderer method render.

@Override
public void render(Context ctx, JsonRender object) throws Exception {
    ObjectWriter writer = object.getObjectWriter();
    if (writer == null) {
        writer = ctx.maybeGet(ObjectWriter.class).orElseGet(() -> ctx.get(ObjectMapper.class).writer());
    }
    Class<?> viewClass = object.getViewClass();
    if (viewClass != null) {
        writer = writer.withView(viewClass);
    }
    ByteBuf buffer = ctx.get(ByteBufAllocator.class).buffer();
    OutputStream outputStream = new ByteBufOutputStream(buffer);
    try {
        writer.writeValue(outputStream, object.getObject());
    } catch (JsonProcessingException e) {
        buffer.release();
        ctx.error(e);
        return;
    }
    ctx.getResponse().contentTypeIfNotSet(HttpHeaderConstants.JSON).send(buffer);
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) OutputStream(java.io.OutputStream) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ByteBuf(io.netty.buffer.ByteBuf) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 20 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project presto by prestodb.

the class QueryMonitor method queryCompletedEvent.

public void queryCompletedEvent(QueryInfo queryInfo) {
    try {
        Optional<QueryFailureInfo> queryFailureInfo = Optional.empty();
        if (queryInfo.getFailureInfo() != null) {
            FailureInfo failureInfo = queryInfo.getFailureInfo();
            Optional<TaskInfo> failedTask = queryInfo.getOutputStage().flatMap(QueryMonitor::findFailedTask);
            queryFailureInfo = Optional.of(new QueryFailureInfo(queryInfo.getErrorCode(), Optional.ofNullable(failureInfo.getType()), Optional.ofNullable(failureInfo.getMessage()), failedTask.map(task -> task.getTaskStatus().getTaskId().toString()), failedTask.map(task -> task.getTaskStatus().getSelf().getHost()), objectMapper.writeValueAsString(queryInfo.getFailureInfo())));
        }
        ImmutableList.Builder<QueryInputMetadata> inputs = ImmutableList.builder();
        for (Input input : queryInfo.getInputs()) {
            inputs.add(new QueryInputMetadata(input.getConnectorId().getCatalogName(), input.getSchema(), input.getTable(), input.getColumns().stream().map(Column::toString).collect(Collectors.toList()), input.getConnectorInfo()));
        }
        QueryStats queryStats = queryInfo.getQueryStats();
        Optional<QueryOutputMetadata> output = Optional.empty();
        if (queryInfo.getOutput().isPresent()) {
            Optional<TableFinishInfo> tableFinishInfo = queryStats.getOperatorSummaries().stream().map(OperatorStats::getInfo).filter(TableFinishInfo.class::isInstance).map(TableFinishInfo.class::cast).findFirst();
            output = Optional.of(new QueryOutputMetadata(queryInfo.getOutput().get().getConnectorId().getCatalogName(), queryInfo.getOutput().get().getSchema(), queryInfo.getOutput().get().getTable(), tableFinishInfo.map(TableFinishInfo::getConnectorOutputMetadata), tableFinishInfo.map(TableFinishInfo::isJsonLengthLimitExceeded)));
        }
        eventListenerManager.queryCompleted(new QueryCompletedEvent(new QueryMetadata(queryInfo.getQueryId().toString(), queryInfo.getSession().getTransactionId().map(TransactionId::toString), queryInfo.getQuery(), queryInfo.getState().toString(), queryInfo.getSelf(), queryInfo.getOutputStage().flatMap(stage -> stageInfoCodec.toJsonWithLengthLimit(stage, toIntExact(config.getMaxOutputStageJsonSize().toBytes())))), new QueryStatistics(ofMillis(queryStats.getTotalCpuTime().toMillis()), ofMillis(queryStats.getTotalScheduledTime().toMillis()), ofMillis(queryStats.getQueuedTime().toMillis()), Optional.ofNullable(queryStats.getAnalysisTime()).map(duration -> ofMillis(duration.toMillis())), Optional.ofNullable(queryStats.getDistributedPlanningTime()).map(duration -> ofMillis(duration.toMillis())), queryStats.getPeakMemoryReservation().toBytes(), queryStats.getRawInputDataSize().toBytes(), queryStats.getRawInputPositions(), queryStats.getCompletedDrivers(), queryInfo.isCompleteInfo(), objectMapper.writeValueAsString(queryInfo.getQueryStats().getOperatorSummaries())), new QueryContext(queryInfo.getSession().getUser(), queryInfo.getSession().getPrincipal(), queryInfo.getSession().getRemoteUserAddress(), queryInfo.getSession().getUserAgent(), queryInfo.getSession().getClientInfo(), queryInfo.getSession().getSource(), queryInfo.getSession().getCatalog(), queryInfo.getSession().getSchema(), mergeSessionAndCatalogProperties(queryInfo), serverAddress, serverVersion, environment), new QueryIOMetadata(inputs.build(), output), queryFailureInfo, ofEpochMilli(queryStats.getCreateTime().getMillis()), ofEpochMilli(queryStats.getExecutionStartTime().getMillis()), ofEpochMilli(queryStats.getEndTime().getMillis())));
        logQueryTimeline(queryInfo);
    } catch (JsonProcessingException e) {
        throw Throwables.propagate(e);
    }
}
Also used : TaskStats(com.facebook.presto.operator.TaskStats) QueryContext(com.facebook.presto.spi.eventlistener.QueryContext) NodeInfo(io.airlift.node.NodeInfo) TaskState(com.facebook.presto.execution.TaskState) NodeVersion(com.facebook.presto.client.NodeVersion) TableFinishInfo(com.facebook.presto.operator.TableFinishInfo) EventListenerManager(com.facebook.presto.eventlistener.EventListenerManager) QueryStatistics(com.facebook.presto.spi.eventlistener.QueryStatistics) OperatorStats(com.facebook.presto.operator.OperatorStats) StageInfo(com.facebook.presto.execution.StageInfo) Instant.ofEpochMilli(java.time.Instant.ofEpochMilli) Duration(java.time.Duration) Map(java.util.Map) QueryMetadata(com.facebook.presto.spi.eventlistener.QueryMetadata) TransactionId(com.facebook.presto.transaction.TransactionId) SplitStatistics(com.facebook.presto.spi.eventlistener.SplitStatistics) Column(com.facebook.presto.execution.Column) ImmutableMap(com.google.common.collect.ImmutableMap) SplitCompletedEvent(com.facebook.presto.spi.eventlistener.SplitCompletedEvent) Collectors(java.util.stream.Collectors) List(java.util.List) QueryCompletedEvent(com.facebook.presto.spi.eventlistener.QueryCompletedEvent) Input(com.facebook.presto.execution.Input) QueryInfo(com.facebook.presto.execution.QueryInfo) Optional(java.util.Optional) Math.max(java.lang.Math.max) ConnectorId(com.facebook.presto.connector.ConnectorId) Duration.ofMillis(java.time.Duration.ofMillis) QueryFailureInfo(com.facebook.presto.spi.eventlistener.QueryFailureInfo) JsonCodec(io.airlift.json.JsonCodec) DriverStats(com.facebook.presto.operator.DriverStats) QueryIOMetadata(com.facebook.presto.spi.eventlistener.QueryIOMetadata) Logger(io.airlift.log.Logger) Inject(javax.inject.Inject) ImmutableList(com.google.common.collect.ImmutableList) FailureInfo(com.facebook.presto.client.FailureInfo) Objects.requireNonNull(java.util.Objects.requireNonNull) Math.toIntExact(java.lang.Math.toIntExact) Nullable(javax.annotation.Nullable) QueryOutputMetadata(com.facebook.presto.spi.eventlistener.QueryOutputMetadata) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DateTime(org.joda.time.DateTime) Throwables(com.google.common.base.Throwables) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) QueryInputMetadata(com.facebook.presto.spi.eventlistener.QueryInputMetadata) QueryStats(com.facebook.presto.execution.QueryStats) SplitFailureInfo(com.facebook.presto.spi.eventlistener.SplitFailureInfo) TaskId(com.facebook.presto.execution.TaskId) QueryCreatedEvent(com.facebook.presto.spi.eventlistener.QueryCreatedEvent) TaskInfo(com.facebook.presto.execution.TaskInfo) TableFinishInfo(com.facebook.presto.operator.TableFinishInfo) QueryMetadata(com.facebook.presto.spi.eventlistener.QueryMetadata) QueryCompletedEvent(com.facebook.presto.spi.eventlistener.QueryCompletedEvent) ImmutableList(com.google.common.collect.ImmutableList) QueryOutputMetadata(com.facebook.presto.spi.eventlistener.QueryOutputMetadata) QueryContext(com.facebook.presto.spi.eventlistener.QueryContext) QueryInputMetadata(com.facebook.presto.spi.eventlistener.QueryInputMetadata) QueryFailureInfo(com.facebook.presto.spi.eventlistener.QueryFailureInfo) TaskInfo(com.facebook.presto.execution.TaskInfo) Input(com.facebook.presto.execution.Input) QueryStats(com.facebook.presto.execution.QueryStats) QueryStatistics(com.facebook.presto.spi.eventlistener.QueryStatistics) QueryFailureInfo(com.facebook.presto.spi.eventlistener.QueryFailureInfo) FailureInfo(com.facebook.presto.client.FailureInfo) SplitFailureInfo(com.facebook.presto.spi.eventlistener.SplitFailureInfo) QueryIOMetadata(com.facebook.presto.spi.eventlistener.QueryIOMetadata) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)648 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)205 IOException (java.io.IOException)156 HashMap (java.util.HashMap)105 Map (java.util.Map)77 ArrayList (java.util.ArrayList)67 JsonNode (com.fasterxml.jackson.databind.JsonNode)54 List (java.util.List)50 Test (org.junit.Test)44 InputStream (java.io.InputStream)24 Collectors (java.util.stream.Collectors)24 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)23 Json (com.sequenceiq.cloudbreak.domain.json.Json)21 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)20 Function (java.util.function.Function)18 Test (org.testng.annotations.Test)18 File (java.io.File)17 Date (java.util.Date)17 UnsupportedEncodingException (java.io.UnsupportedEncodingException)15 URL (java.net.URL)15