Search in sources :

Example 6 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput 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 7 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput 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)

Example 8 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project pulsar by yahoo.

the class PersistentTopics method peekNthMessage.

@GET
@Path("/{property}/{cluster}/{namespace}/{destination}/subscription/{subName}/position/{messagePosition}")
@ApiOperation(value = "Peek nth message on a topic subscription.")
@ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"), @ApiResponse(code = 404, message = "Topic, subscription or the message position does not exist") })
public Response peekNthMessage(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @PathParam("destination") @Encoded String destination, @PathParam("subName") String subName, @PathParam("messagePosition") int messagePosition, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    destination = decode(destination);
    DestinationName dn = DestinationName.get(domain(), property, cluster, namespace, destination);
    PartitionedTopicMetadata partitionMetadata = getPartitionedTopicMetadata(property, cluster, namespace, destination, authoritative);
    if (partitionMetadata.partitions > 0) {
        throw new RestException(Status.METHOD_NOT_ALLOWED, "Peek messages on a partitioned topic is not allowed");
    }
    validateAdminOperationOnDestination(dn, authoritative);
    PersistentTopic topic = getTopicReference(dn);
    PersistentReplicator repl = null;
    PersistentSubscription sub = null;
    Entry entry = null;
    if (subName.startsWith(topic.replicatorPrefix)) {
        repl = getReplicatorReference(subName, topic);
    } else {
        sub = getSubscriptionReference(subName, topic);
    }
    try {
        if (subName.startsWith(topic.replicatorPrefix)) {
            entry = repl.peekNthMessage(messagePosition).get();
        } else {
            entry = sub.peekNthMessage(messagePosition).get();
        }
        checkNotNull(entry);
        PositionImpl pos = (PositionImpl) entry.getPosition();
        ByteBuf metadataAndPayload = entry.getDataBuffer();
        // moves the readerIndex to the payload
        MessageMetadata metadata = Commands.parseMessageMetadata(metadataAndPayload);
        ResponseBuilder responseBuilder = Response.ok();
        responseBuilder.header("X-Pulsar-Message-ID", pos.toString());
        for (KeyValue keyValue : metadata.getPropertiesList()) {
            responseBuilder.header("X-Pulsar-PROPERTY-" + keyValue.getKey(), keyValue.getValue());
        }
        if (metadata.hasPublishTime()) {
            responseBuilder.header("X-Pulsar-publish-time", DATE_FORMAT.format(Instant.ofEpochMilli(metadata.getPublishTime())));
        }
        // Decode if needed
        CompressionCodec codec = CompressionCodecProvider.getCompressionCodec(metadata.getCompression());
        ByteBuf uncompressedPayload = codec.decode(metadataAndPayload, metadata.getUncompressedSize());
        // Copy into a heap buffer for output stream compatibility
        ByteBuf data = PooledByteBufAllocator.DEFAULT.heapBuffer(uncompressedPayload.readableBytes(), uncompressedPayload.readableBytes());
        data.writeBytes(uncompressedPayload);
        uncompressedPayload.release();
        StreamingOutput stream = new StreamingOutput() {

            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                output.write(data.array(), data.arrayOffset(), data.readableBytes());
                data.release();
            }
        };
        return responseBuilder.entity(stream).build();
    } catch (NullPointerException npe) {
        throw new RestException(Status.NOT_FOUND, "Message not found");
    } catch (Exception exception) {
        log.error("[{}] Failed to get message at position {} from {} {}", clientAppId(), messagePosition, dn, subName, exception);
        throw new RestException(exception);
    } finally {
        if (entry != null) {
            entry.release();
        }
    }
}
Also used : PersistentReplicator(com.yahoo.pulsar.broker.service.persistent.PersistentReplicator) KeyValue(com.yahoo.pulsar.common.api.proto.PulsarApi.KeyValue) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) OutputStream(java.io.OutputStream) RestException(com.yahoo.pulsar.broker.web.RestException) StreamingOutput(javax.ws.rs.core.StreamingOutput) ByteBuf(io.netty.buffer.ByteBuf) PersistentSubscription(com.yahoo.pulsar.broker.service.persistent.PersistentSubscription) RestException(com.yahoo.pulsar.broker.web.RestException) TopicBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicBusyException) WebApplicationException(javax.ws.rs.WebApplicationException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PreconditionFailedException(com.yahoo.pulsar.client.admin.PulsarAdminException.PreconditionFailedException) SubscriptionBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) NotFoundException(com.yahoo.pulsar.client.admin.PulsarAdminException.NotFoundException) NotAllowedException(com.yahoo.pulsar.broker.service.BrokerServiceException.NotAllowedException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) Entry(org.apache.bookkeeper.mledger.Entry) MessageMetadata(com.yahoo.pulsar.common.api.proto.PulsarApi.MessageMetadata) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) CompressionCodec(com.yahoo.pulsar.common.compression.CompressionCodec) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) PartitionedTopicMetadata(com.yahoo.pulsar.common.partition.PartitionedTopicMetadata) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 9 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project ice by JBEI.

the class FileResource method downloadSequence.

@GET
@Path("{partId}/sequence/{type}")
public Response downloadSequence(@PathParam("partId") final long partId, @PathParam("type") final String downloadType, @DefaultValue("-1") @QueryParam("remoteId") long remoteId, @QueryParam("sid") String sid) {
    if (StringUtils.isEmpty(sessionId))
        sessionId = sid;
    final String userId = getUserId(sessionId);
    final ByteArrayWrapper wrapper;
    if (remoteId != -1) {
        RemoteSequence sequence = new RemoteSequence(remoteId, partId);
        wrapper = sequence.get(downloadType);
    } else {
        wrapper = sequenceController.getSequenceFile(userId, partId, downloadType);
    }
    StreamingOutput stream = output -> {
        final ByteArrayInputStream input = new ByteArrayInputStream(wrapper.getBytes());
        ByteStreams.copy(input, output);
    };
    return addHeaders(Response.ok(stream), wrapper.getName());
}
Also used : RemoteSequence(org.jbei.ice.lib.net.RemoteSequence) AttachmentInfo(org.jbei.ice.lib.dto.entry.AttachmentInfo) FormDataContentDisposition(org.glassfish.jersey.media.multipart.FormDataContentDisposition) PartSequence(org.jbei.ice.lib.entry.sequence.PartSequence) Setting(org.jbei.ice.lib.dto.Setting) SequenceAnalysisController(org.jbei.ice.lib.entry.sequence.SequenceAnalysisController) ConfigurationKey(org.jbei.ice.lib.dto.ConfigurationKey) EntryField(org.jbei.ice.lib.dto.entry.EntryField) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) Entries(org.jbei.ice.lib.entry.Entries) Sequence(org.jbei.ice.storage.model.Sequence) MediaType(javax.ws.rs.core.MediaType) ConfigurationController(org.jbei.ice.lib.config.ConfigurationController) DAOFactory(org.jbei.ice.storage.DAOFactory) Logger(org.jbei.ice.lib.common.logging.Logger) FileBulkUpload(org.jbei.ice.lib.bulkupload.FileBulkUpload) SequenceInfo(org.jbei.ice.lib.dto.entry.SequenceInfo) PigeonSBOLv(org.jbei.ice.lib.entry.sequence.composers.pigeon.PigeonSBOLv) Entry(org.jbei.ice.storage.model.Entry) EntryType(org.jbei.ice.lib.dto.entry.EntryType) URI(java.net.URI) Utils(org.jbei.ice.lib.utils.Utils) AttachmentController(org.jbei.ice.lib.entry.attachment.AttachmentController) EntrySelection(org.jbei.ice.lib.entry.EntrySelection) FileUtils(org.apache.commons.io.FileUtils) StreamingOutput(javax.ws.rs.core.StreamingOutput) SequenceController(org.jbei.ice.lib.entry.sequence.SequenceController) Collectors(java.util.stream.Collectors) RemoteEntries(org.jbei.ice.lib.net.RemoteEntries) FormDataParam(org.glassfish.jersey.media.multipart.FormDataParam) List(java.util.List) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) java.io(java.io) Paths(java.nio.file.Paths) ByteStreams(com.google.common.io.ByteStreams) ByteArrayWrapper(org.jbei.ice.lib.entry.sequence.ByteArrayWrapper) ShotgunSequenceDAO(org.jbei.ice.storage.hibernate.dao.ShotgunSequenceDAO) TraceSequence(org.jbei.ice.storage.model.TraceSequence) EntriesAsCSV(org.jbei.ice.lib.entry.EntriesAsCSV) ShotgunSequence(org.jbei.ice.storage.model.ShotgunSequence) ByteArrayWrapper(org.jbei.ice.lib.entry.sequence.ByteArrayWrapper) StreamingOutput(javax.ws.rs.core.StreamingOutput) RemoteSequence(org.jbei.ice.lib.net.RemoteSequence)

Example 10 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project tika by apache.

the class TikaResource method produceOutput.

private StreamingOutput produceOutput(final InputStream is, final MultivaluedMap<String, String> httpHeaders, final UriInfo info, final String format) {
    final Parser parser = createParser();
    final Metadata metadata = new Metadata();
    final ParseContext context = new ParseContext();
    fillMetadata(parser, metadata, context, httpHeaders);
    fillParseContext(context, httpHeaders, parser);
    logRequest(LOG, info, metadata);
    return new StreamingOutput() {

        public void write(OutputStream outputStream) throws IOException, WebApplicationException {
            Writer writer = new OutputStreamWriter(outputStream, UTF_8);
            ContentHandler content;
            try {
                SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
                TransformerHandler handler = factory.newTransformerHandler();
                handler.getTransformer().setOutputProperty(OutputKeys.METHOD, format);
                handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
                handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, UTF_8.name());
                handler.setResult(new StreamResult(writer));
                content = new ExpandedTitleContentHandler(handler);
            } catch (TransformerConfigurationException e) {
                throw new WebApplicationException(e);
            }
            parse(parser, LOG, info.getPath(), is, content, metadata, context);
        }
    };
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) WebApplicationException(javax.ws.rs.WebApplicationException) OutputStream(java.io.OutputStream) Metadata(org.apache.tika.metadata.Metadata) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) StreamingOutput(javax.ws.rs.core.StreamingOutput) BoilerpipeContentHandler(org.apache.tika.parser.html.BoilerpipeContentHandler) ExpandedTitleContentHandler(org.apache.tika.sax.ExpandedTitleContentHandler) BodyContentHandler(org.apache.tika.sax.BodyContentHandler) ContentHandler(org.xml.sax.ContentHandler) RichTextContentHandler(org.apache.tika.sax.RichTextContentHandler) ExpandedTitleContentHandler(org.apache.tika.sax.ExpandedTitleContentHandler) Parser(org.apache.tika.parser.Parser) HtmlParser(org.apache.tika.parser.html.HtmlParser) AutoDetectParser(org.apache.tika.parser.AutoDetectParser) DigestingParser(org.apache.tika.parser.DigestingParser) ParseContext(org.apache.tika.parser.ParseContext) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Aggregations

StreamingOutput (javax.ws.rs.core.StreamingOutput)23 OutputStream (java.io.OutputStream)13 IOException (java.io.IOException)8 Path (javax.ws.rs.Path)7 Produces (javax.ws.rs.Produces)7 WebApplicationException (javax.ws.rs.WebApplicationException)7 Response (javax.ws.rs.core.Response)6 GET (javax.ws.rs.GET)5 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)4 Consumes (javax.ws.rs.Consumes)4 POST (javax.ws.rs.POST)4 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)4 QueryInterruptedException (io.druid.query.QueryInterruptedException)3 ApiOperation (io.swagger.annotations.ApiOperation)3 ApiResponses (io.swagger.annotations.ApiResponses)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 OutputStreamWriter (java.io.OutputStreamWriter)3 ByteStreams (com.google.common.io.ByteStreams)2 ISE (io.druid.java.util.common.ISE)2 Writer (java.io.Writer)2