Search in sources :

Example 51 with JsonGenerator

use of com.fasterxml.jackson.core.JsonGenerator in project pinpoint by naver.

the class FilterDescriptorTest method writeJsonString.

private String writeJsonString() throws IOException {
    StringWriter writer = new StringWriter();
    JsonGenerator json = mapper.getFactory().createGenerator(writer);
    //        json.writeStartArray();
    json.writeStartObject();
    json.writeStringField("fa", "FROM_APPLICATION");
    json.writeStringField("fst", "FROM_SERVICE_TYPE");
    json.writeStringField("fan", "FROM_AGENT_ID");
    // fromResponseTime
    json.writeNumberField("rf", 0);
    json.writeStringField("ta", "TO_APPLICATION");
    json.writeStringField("tst", "TO_SERVICE_TYPE");
    json.writeStringField("tan", "TO_AGENT_ID");
    // toResponseTime
    json.writeNumberField("rt", 1000);
    json.writeNumberField("ie", 1);
    json.writeStringField("url", "/**");
    json.writeEndObject();
    //        json.writeEndArray();
    json.flush();
    json.close();
    String jsonString = writer.toString();
    logger.debug("json:{}", jsonString);
    return jsonString;
}
Also used : StringWriter(java.io.StringWriter) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator)

Example 52 with JsonGenerator

use of com.fasterxml.jackson.core.JsonGenerator in project pinpoint by naver.

the class AgentTimeHistogramTest method testViewModel.

@Test
public void testViewModel() throws IOException {
    Application app = new Application("test", ServiceType.STAND_ALONE);
    AgentTimeHistogramBuilder builder = new AgentTimeHistogramBuilder(app, new Range(0, 1000 * 60));
    List<ResponseTime> responseHistogramList = createResponseTime(app, "test1", "test2");
    AgentTimeHistogram histogram = builder.build(responseHistogramList);
    List<AgentResponseTimeViewModel> viewModel = histogram.createViewModel();
    logger.debug("{}", viewModel);
    JsonFactory jsonFactory = mapper.getFactory();
    StringWriter stringWriter = new StringWriter();
    JsonGenerator jsonGenerator = jsonFactory.createGenerator(stringWriter);
    jsonGenerator.writeStartObject();
    for (AgentResponseTimeViewModel agentResponseTimeViewModel : viewModel) {
        jsonGenerator.writeObject(agentResponseTimeViewModel);
    }
    jsonGenerator.writeEndObject();
    jsonGenerator.flush();
    jsonGenerator.close();
    logger.debug(stringWriter.toString());
}
Also used : AgentTimeHistogramBuilder(com.navercorp.pinpoint.web.applicationmap.histogram.AgentTimeHistogramBuilder) AgentTimeHistogram(com.navercorp.pinpoint.web.applicationmap.histogram.AgentTimeHistogram) AgentResponseTimeViewModel(com.navercorp.pinpoint.web.view.AgentResponseTimeViewModel) StringWriter(java.io.StringWriter) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ResponseTime(com.navercorp.pinpoint.web.vo.ResponseTime) Range(com.navercorp.pinpoint.web.vo.Range) Application(com.navercorp.pinpoint.web.vo.Application) Test(org.junit.Test)

Example 53 with JsonGenerator

use of com.fasterxml.jackson.core.JsonGenerator in project killbill by killbill.

the class AdminResource method triggerInvoiceGenerationForParkedAccounts.

@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@Path("/invoices")
@ApiOperation(value = "Trigger an invoice generation for all parked accounts")
@ApiResponses(value = {})
public Response triggerInvoiceGenerationForParkedAccounts(@QueryParam(QUERY_SEARCH_OFFSET) @DefaultValue("0") final Long offset, @QueryParam(QUERY_SEARCH_LIMIT) @DefaultValue("100") final Long limit, @HeaderParam(HDR_CREATED_BY) final String createdBy, @HeaderParam(HDR_REASON) final String reason, @HeaderParam(HDR_COMMENT) final String comment, @javax.ws.rs.core.Context final HttpServletRequest request) {
    final CallContext callContext = context.createContext(createdBy, reason, comment, request);
    // TODO Consider adding a real invoice API post 0.18.x
    final Pagination<Tag> tags = tagUserApi.searchTags(SystemTags.PARK_TAG_DEFINITION_NAME, offset, limit, callContext);
    final Iterator<Tag> iterator = tags.iterator();
    final StreamingOutput json = new StreamingOutput() {

        @Override
        public void write(final OutputStream output) throws IOException, WebApplicationException {
            try {
                final JsonGenerator generator = mapper.getFactory().createGenerator(output);
                generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
                generator.writeStartObject();
                while (iterator.hasNext()) {
                    final Tag tag = iterator.next();
                    final UUID accountId = tag.getObjectId();
                    try {
                        invoiceUserApi.triggerInvoiceGeneration(accountId, clock.getUTCToday(), null, callContext);
                        generator.writeStringField(accountId.toString(), OK);
                    } catch (final InvoiceApiException e) {
                        if (e.getCode() != ErrorCode.INVOICE_NOTHING_TO_DO.getCode()) {
                            log.warn("Unable to trigger invoice generation for accountId='{}'", accountId);
                        }
                        generator.writeStringField(accountId.toString(), ErrorCode.fromCode(e.getCode()).toString());
                    }
                }
                generator.writeEndObject();
                generator.close();
            } finally {
                // In case the client goes away (IOException), make sure to close the underlying DB connection
                while (iterator.hasNext()) {
                    iterator.next();
                }
            }
        }
    };
    final URI nextPageUri = uriBuilder.nextPage(AdminResource.class, "triggerInvoiceGenerationForParkedAccounts", tags.getNextOffset(), limit, ImmutableMap.<String, String>of());
    return Response.status(Status.OK).entity(json).header(HDR_PAGINATION_CURRENT_OFFSET, tags.getCurrentOffset()).header(HDR_PAGINATION_NEXT_OFFSET, tags.getNextOffset()).header(HDR_PAGINATION_TOTAL_NB_RECORDS, tags.getTotalNbRecords()).header(HDR_PAGINATION_MAX_NB_RECORDS, tags.getMaxNbRecords()).header(HDR_PAGINATION_NEXT_PAGE_URI, nextPageUri).build();
}
Also used : InvoiceApiException(org.killbill.billing.invoice.api.InvoiceApiException) OutputStream(java.io.OutputStream) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) StreamingOutput(javax.ws.rs.core.StreamingOutput) Tag(org.killbill.billing.util.tag.Tag) UUID(java.util.UUID) CallContext(org.killbill.billing.util.callcontext.CallContext) URI(java.net.URI) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 54 with JsonGenerator

use of com.fasterxml.jackson.core.JsonGenerator in project killbill by killbill.

the class AdminResource method getQueueEntries.

@GET
@Path("/queues")
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Get queues entries", response = Response.class)
@ApiResponses(value = {})
public Response getQueueEntries(@QueryParam("accountId") final String accountIdStr, @QueryParam("queueName") final String queueName, @QueryParam("serviceName") final String serviceName, @QueryParam("withHistory") @DefaultValue("true") final Boolean withHistory, @QueryParam("minDate") final String minDateOrNull, @QueryParam("maxDate") final String maxDateOrNull, @QueryParam("withInProcessing") @DefaultValue("true") final Boolean withInProcessing, @QueryParam("withBusEvents") @DefaultValue("true") final Boolean withBusEvents, @QueryParam("withNotifications") @DefaultValue("true") final Boolean withNotifications, @javax.ws.rs.core.Context final HttpServletRequest request) {
    final TenantContext tenantContext = context.createContext(request);
    final Long tenantRecordId = recordIdApi.getRecordId(tenantContext.getTenantId(), ObjectType.TENANT, tenantContext);
    final Long accountRecordId = Strings.isNullOrEmpty(accountIdStr) ? null : recordIdApi.getRecordId(UUID.fromString(accountIdStr), ObjectType.ACCOUNT, tenantContext);
    // Limit search results by default
    final DateTime minDate = Strings.isNullOrEmpty(minDateOrNull) ? clock.getUTCNow().minusDays(2) : DATE_TIME_FORMATTER.parseDateTime(minDateOrNull).toDateTime(DateTimeZone.UTC);
    final DateTime maxDate = Strings.isNullOrEmpty(maxDateOrNull) ? clock.getUTCNow().plusDays(2) : DATE_TIME_FORMATTER.parseDateTime(maxDateOrNull).toDateTime(DateTimeZone.UTC);
    final StreamingOutput json = new StreamingOutput() {

        @Override
        public void write(final OutputStream output) throws IOException, WebApplicationException {
            Iterator<BusEventWithMetadata<BusEvent>> busEventsIterator = null;
            Iterator<NotificationEventWithMetadata<NotificationEvent>> notificationsIterator = null;
            try {
                final JsonGenerator generator = mapper.getFactory().createGenerator(output);
                generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
                generator.writeStartObject();
                if (withBusEvents) {
                    generator.writeFieldName("busEvents");
                    generator.writeStartArray();
                    busEventsIterator = getBusEvents(withInProcessing, withHistory, minDate, maxDate, accountRecordId, tenantRecordId).iterator();
                    while (busEventsIterator.hasNext()) {
                        final BusEventWithMetadata<BusEvent> busEvent = busEventsIterator.next();
                        generator.writeObject(new BusEventWithRichMetadata(busEvent));
                    }
                    generator.writeEndArray();
                }
                if (withNotifications) {
                    generator.writeFieldName("notifications");
                    generator.writeStartArray();
                    notificationsIterator = getNotifications(queueName, serviceName, withInProcessing, withHistory, minDate, maxDate, accountRecordId, tenantRecordId).iterator();
                    while (notificationsIterator.hasNext()) {
                        final NotificationEventWithMetadata<NotificationEvent> notification = notificationsIterator.next();
                        generator.writeObject(notification);
                    }
                    generator.writeEndArray();
                }
                generator.writeEndObject();
                generator.close();
            } finally {
                // In case the client goes away (IOException), make sure to close the underlying DB connection
                if (busEventsIterator != null) {
                    while (busEventsIterator.hasNext()) {
                        busEventsIterator.next();
                    }
                }
                if (notificationsIterator != null) {
                    while (notificationsIterator.hasNext()) {
                        notificationsIterator.next();
                    }
                }
            }
        }
    };
    return Response.status(Status.OK).entity(json).build();
}
Also used : BusEventWithMetadata(org.killbill.bus.api.BusEventWithMetadata) OutputStream(java.io.OutputStream) TenantContext(org.killbill.billing.util.callcontext.TenantContext) StreamingOutput(javax.ws.rs.core.StreamingOutput) NotificationEvent(org.killbill.notificationq.api.NotificationEvent) DateTime(org.joda.time.DateTime) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) NotificationEventWithMetadata(org.killbill.notificationq.api.NotificationEventWithMetadata) BusEvent(org.killbill.bus.api.BusEvent) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 55 with JsonGenerator

use of com.fasterxml.jackson.core.JsonGenerator in project killbill by killbill.

the class JaxRsResourceBase method buildStreamingPaginationResponse.

protected <E extends Entity, J extends JsonBase> Response buildStreamingPaginationResponse(final Pagination<E> entities, final Function<E, J> toJson, final URI nextPageUri) {
    final StreamingOutput json = new StreamingOutput() {

        @Override
        public void write(final OutputStream output) throws IOException, WebApplicationException {
            final Iterator<E> iterator = entities.iterator();
            try {
                final JsonGenerator generator = mapper.getFactory().createGenerator(output);
                generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
                generator.writeStartArray();
                while (iterator.hasNext()) {
                    final E entity = iterator.next();
                    final J asJson = toJson.apply(entity);
                    if (asJson != null) {
                        generator.writeObject(asJson);
                    }
                }
                generator.writeEndArray();
                generator.close();
            } finally {
                // In case the client goes away (IOException), make sure to close the underlying DB connection
                while (iterator.hasNext()) {
                    iterator.next();
                }
            }
        }
    };
    return Response.status(Status.OK).entity(json).header(HDR_PAGINATION_CURRENT_OFFSET, entities.getCurrentOffset()).header(HDR_PAGINATION_NEXT_OFFSET, entities.getNextOffset()).header(HDR_PAGINATION_TOTAL_NB_RECORDS, entities.getTotalNbRecords()).header(HDR_PAGINATION_MAX_NB_RECORDS, entities.getMaxNbRecords()).header(HDR_PAGINATION_NEXT_PAGE_URI, nextPageUri).build();
}
Also used : OutputStream(java.io.OutputStream) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) StreamingOutput(javax.ws.rs.core.StreamingOutput)

Aggregations

JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)187 StringWriter (java.io.StringWriter)81 IOException (java.io.IOException)52 JsonFactory (com.fasterxml.jackson.core.JsonFactory)44 ByteArrayOutputStream (java.io.ByteArrayOutputStream)25 Map (java.util.Map)17 OutputStream (java.io.OutputStream)14 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)13 JsonParser (com.fasterxml.jackson.core.JsonParser)11 ArrayList (java.util.ArrayList)11 HashMap (java.util.HashMap)10 Test (org.junit.Test)10 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)8 File (java.io.File)7 OutputStreamWriter (java.io.OutputStreamWriter)6 ServletOutputStream (javax.servlet.ServletOutputStream)6 HeapDataOutputStream (org.apache.geode.internal.HeapDataOutputStream)6 List (java.util.List)5 AccessExecutionVertex (org.apache.flink.runtime.executiongraph.AccessExecutionVertex)5 JsonEncoding (com.fasterxml.jackson.core.JsonEncoding)4