Search in sources :

Example 56 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project registry by hortonworks.

the class WSUtils method wrapWithStreamingOutput.

public static StreamingOutput wrapWithStreamingOutput(final InputStream inputStream) {
    return new StreamingOutput() {

        public void write(OutputStream os) throws IOException, WebApplicationException {
            OutputStream wrappedOutputStream = os;
            if (!(os instanceof BufferedOutputStream)) {
                wrappedOutputStream = new BufferedOutputStream(os);
            }
            ByteStreams.copy(inputStream, wrappedOutputStream);
            wrappedOutputStream.flush();
        }
    };
}
Also used : OutputStream(java.io.OutputStream) BufferedOutputStream(java.io.BufferedOutputStream) StreamingOutput(javax.ws.rs.core.StreamingOutput) BufferedOutputStream(java.io.BufferedOutputStream)

Example 57 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project component-runtime by Talend.

the class ProjectResource method createZip.

@POST
@Path("zip/form")
@Produces("application/zip")
public Response createZip(@FormParam("project") final String compressedModel, @Context final Providers providers) {
    final MessageBodyReader<ProjectModel> jsonReader = providers.getMessageBodyReader(ProjectModel.class, ProjectModel.class, NO_ANNOTATION, APPLICATION_JSON_TYPE);
    final ProjectModel model;
    try (final InputStream gzipInputStream = new ByteArrayInputStream(Base64.getUrlDecoder().decode(compressedModel))) {
        model = jsonReader.readFrom(ProjectModel.class, ProjectModel.class, NO_ANNOTATION, APPLICATION_JSON_TYPE, new MultivaluedHashMap<>(), gzipInputStream);
    } catch (final IOException e) {
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorMessage(e.getMessage())).type(APPLICATION_JSON_TYPE).build());
    }
    final String filename = ofNullable(model.getArtifact()).orElse("zip") + ".zip";
    return Response.ok().entity((StreamingOutput) out -> {
        generator.generate(toRequest(model), out);
        out.flush();
    }).header("Content-Disposition", "inline; filename=" + filename).build();
}
Also used : MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) BufferedInputStream(java.io.BufferedInputStream) Produces(javax.ws.rs.Produces) ErrorMessage(org.talend.sdk.component.starter.server.model.ErrorMessage) Path(javax.ws.rs.Path) GithubProject(org.talend.sdk.component.starter.server.model.GithubProject) Collections.singletonList(java.util.Collections.singletonList) MediaType(javax.ws.rs.core.MediaType) Collectors.toMap(java.util.stream.Collectors.toMap) ByteArrayInputStream(java.io.ByteArrayInputStream) Consumes(javax.ws.rs.Consumes) Locale(java.util.Locale) Map(java.util.Map) ENGLISH(java.util.Locale.ENGLISH) ZipEntry(java.util.zip.ZipEntry) ProjectGenerator(org.talend.sdk.component.starter.server.service.ProjectGenerator) Context(javax.ws.rs.core.Context) Providers(javax.ws.rs.ext.Providers) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Collections.emptyList(java.util.Collections.emptyList) StandardOpenOption(java.nio.file.StandardOpenOption) StreamingOutput(javax.ws.rs.core.StreamingOutput) NullProgressMonitor(org.eclipse.jgit.lib.NullProgressMonitor) Collectors.joining(java.util.stream.Collectors.joining) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) FileUtils(org.eclipse.jgit.util.FileUtils) Slf4j(lombok.extern.slf4j.Slf4j) Response(javax.ws.rs.core.Response) Writer(java.io.Writer) Annotation(java.lang.annotation.Annotation) PostConstruct(javax.annotation.PostConstruct) WebApplicationException(javax.ws.rs.WebApplicationException) ProjectModel(org.talend.sdk.component.starter.server.model.ProjectModel) ApplicationScoped(javax.enterprise.context.ApplicationScoped) CreateProjectRequest(org.talend.sdk.component.starter.server.model.github.CreateProjectRequest) ZipInputStream(java.util.zip.ZipInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) GET(javax.ws.rs.GET) Client(javax.ws.rs.client.Client) Entity.entity(javax.ws.rs.client.Entity.entity) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ClientBuilder(javax.ws.rs.client.ClientBuilder) StarterConfiguration(org.talend.sdk.component.starter.server.configuration.StarterConfiguration) FactoryConfiguration(org.talend.sdk.component.starter.server.model.FactoryConfiguration) Collections.emptyMap(java.util.Collections.emptyMap) FormParam(javax.ws.rs.FormParam) POST(javax.ws.rs.POST) Files(java.nio.file.Files) Optional.ofNullable(java.util.Optional.ofNullable) FileWriter(java.io.FileWriter) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) File(java.io.File) CreateProjectResponse(org.talend.sdk.component.starter.server.model.github.CreateProjectResponse) TimeUnit(java.util.concurrent.TimeUnit) Result(org.talend.sdk.component.starter.server.model.Result) Collectors.toList(java.util.stream.Collectors.toList) TreeMap(java.util.TreeMap) APPLICATION_JSON_TYPE(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE) BufferedReader(java.io.BufferedReader) Git(org.eclipse.jgit.api.Git) Comparator(java.util.Comparator) ProjectRequest(org.talend.sdk.component.starter.server.service.domain.ProjectRequest) InputStream(java.io.InputStream) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) WebApplicationException(javax.ws.rs.WebApplicationException) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ProjectModel(org.talend.sdk.component.starter.server.model.ProjectModel) ErrorMessage(org.talend.sdk.component.starter.server.model.ErrorMessage) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 58 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project cloudbreak by hortonworks.

the class CloudbreakEventController method getStructuredEventsZip.

@Override
public Response getStructuredEventsZip(Long stackId) {
    List<StructuredEvent> events = getStructuredEventsForStack(stackId);
    StreamingOutput streamingOutput = output -> {
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(output)) {
            zipOutputStream.putNextEntry(new ZipEntry("struct-events.json"));
            zipOutputStream.write(JsonUtil.writeValueAsString(events).getBytes());
            zipOutputStream.closeEntry();
        }
    };
    return Response.ok(streamingOutput).header("content-disposition", "attachment; filename = struct-events.zip").build();
}
Also used : ZipOutputStream(java.util.zip.ZipOutputStream) Arrays(java.util.Arrays) IdentityUser(com.sequenceiq.cloudbreak.common.model.user.IdentityUser) StreamingOutput(javax.ws.rs.core.StreamingOutput) StructuredEventService(com.sequenceiq.cloudbreak.structuredevent.StructuredEventService) Maps(com.google.common.collect.Maps) Inject(javax.inject.Inject) List(java.util.List) Component(org.springframework.stereotype.Component) Response(javax.ws.rs.core.Response) CloudbreakEventsFacade(com.sequenceiq.cloudbreak.facade.CloudbreakEventsFacade) Map(java.util.Map) CloudbreakEventsJson(com.sequenceiq.cloudbreak.api.model.CloudbreakEventsJson) EventEndpoint(com.sequenceiq.cloudbreak.api.endpoint.v1.EventEndpoint) StructuredEvent(com.sequenceiq.cloudbreak.structuredevent.event.StructuredEvent) ZipEntry(java.util.zip.ZipEntry) JsonUtil(com.sequenceiq.cloudbreak.util.JsonUtil) ZipOutputStream(java.util.zip.ZipOutputStream) StructuredEvent(com.sequenceiq.cloudbreak.structuredevent.event.StructuredEvent) ZipEntry(java.util.zip.ZipEntry) StreamingOutput(javax.ws.rs.core.StreamingOutput)

Example 59 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
                entities.close();
            }
        }
    };
    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 60 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput 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 = { @ApiResponse(code = 200, message = "Successful operation") })
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.createCallContextNoAccountId(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(), 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
                tags.close();
            }
        }
    };
    final URI nextPageUri = uriBuilder.nextPage(AdminResource.class, "triggerInvoiceGenerationForParkedAccounts", tags.getNextOffset(), limit, ImmutableMap.<String, String>of(), 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)

Aggregations

StreamingOutput (javax.ws.rs.core.StreamingOutput)190 OutputStream (java.io.OutputStream)84 Response (javax.ws.rs.core.Response)76 Path (javax.ws.rs.Path)53 Produces (javax.ws.rs.Produces)52 IOException (java.io.IOException)50 GET (javax.ws.rs.GET)50 File (java.io.File)45 InputStream (java.io.InputStream)45 Test (org.junit.Test)44 WebApplicationException (javax.ws.rs.WebApplicationException)33 ByteArrayOutputStream (java.io.ByteArrayOutputStream)32 List (java.util.List)26 MediaType (javax.ws.rs.core.MediaType)24 ByteArrayInputStream (java.io.ByteArrayInputStream)20 ArrayList (java.util.ArrayList)20 Consumes (javax.ws.rs.Consumes)20 HashMap (java.util.HashMap)19 POST (javax.ws.rs.POST)19 FileOutputStream (java.io.FileOutputStream)17