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();
}
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();
}
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();
}
}
}
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());
}
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);
}
};
}
Aggregations