javax.ws.rs.core.StreamingOutput Java Examples

The following examples show how to use javax.ws.rs.core.StreamingOutput. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PublicFilesResource.java    From hmdm-server with Apache License 2.0 9 votes vote down vote up
/**
 * <p>Sends content of the file to client.</p>
 *
 * @param filePath a relative path to a file.
 * @return a response to client.
 * @throws Exception if an unexpected error occurs.
 */
@GET
@Path("/{filePath}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public javax.ws.rs.core.Response downloadFile(@PathParam("filePath") String filePath) throws Exception {
    // TODO : ISV : Needs to identify the device and do a security check if device is granted access to specified
    //  file
    File file = new File(filePath + "/" + URLDecoder.decode(filePath, "UTF8"));
    if (!file.exists()) {
        return javax.ws.rs.core.Response.status(404).build();
    } else {
        ContentDisposition contentDisposition = ContentDisposition.type("attachment").fileName(file.getName()).creationDate(new Date()).build();
        return javax.ws.rs.core.Response.ok( (StreamingOutput) output -> {
            try {
                InputStream input = new FileInputStream( file );
                IOUtils.copy(input, output);
                output.flush();
            } catch ( Exception e ) { e.printStackTrace(); }
        } ).header( "Content-Disposition", contentDisposition ).build();

    }
}
 
Example #2
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns a JSON object with keys for the list of IRIs of derived skos:Concepts, the list of IRIs of derived
 * skos:ConceptSchemes, an object with the concept hierarchy and index, and an object with the concept scheme
 * hierarchy and index.
 *
 * @param context the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return JSON object with keys "derivedConcepts", "derivedConceptSchemes", "concepts.hierarchy", "concepts.index",
 *      "conceptSchemes.hierarchy", and "conceptSchemes.index".
 */
@GET
@Path("{recordId}/vocabulary-stuff")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Gets a JSON representation of all the SKOS vocabulary related information about the ontology")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getVocabularyStuff(@Context ContainerRequestContext context,
                                   @PathParam("recordId") String recordIdStr,
                                   @QueryParam("branchId") String branchIdStr,
                                   @QueryParam("commitId") String commitIdStr) {
    try {
        Optional<Ontology> optionalOntology = getOntology(context, recordIdStr, branchIdStr, commitIdStr, true);
        if (optionalOntology.isPresent()) {
            StreamingOutput output = getVocabularyStuffStream(optionalOntology.get());
            return Response.ok(output).build();
        } else {
            throw ErrorUtils.sendError("Ontology " + recordIdStr + " does not exist.", Response.Status.BAD_REQUEST);
        }
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #3
Source File: BookStoreWebSocket.java    From cxf with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/bookbought")
@Produces("application/*")
public StreamingOutput getBookBought() {
    return new StreamingOutput() {
        public void write(final OutputStream out) throws IOException, WebApplicationException {
            out.write(("Today: " + new java.util.Date()).getBytes());
            // just for testing, using a thread
            executor.execute(new Runnable() {
                public void run() {
                    try {
                        for (int r = 2, i = 1; i <= 5; r *= 2, i++) {
                            Thread.sleep(500);
                            out.write(Integer.toString(r).getBytes());
                            out.flush();
                        }
                        out.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    };
}
 
Example #4
Source File: StreamingWriterInterceptor.java    From ameba with MIT License 6 votes vote down vote up
/**
 * <p>applyStreaming.</p>
 *
 * @param requestContext a {@link javax.ws.rs.container.ContainerRequestContext} object.
 * @param context a {@link javax.ws.rs.ext.WriterInterceptorContext} object.
 * @throws java.io.IOException if any.
 */
protected void applyStreaming(ContainerRequestContext requestContext, WriterInterceptorContext context)
        throws IOException {

    Object entity = context.getEntity();
    StreamingProcess<Object> process = MessageHelper.getStreamingProcess(context.getEntity(), manager);

    if (process != null) {
        ContainerResponseContext responseContext =
                (ContainerResponseContext) requestContext.getProperty(RESP_PROP_N);
        responseContext.setStatusInfo(Response.Status.PARTIAL_CONTENT);
        context.getHeaders().putSingle(ACCEPT_RANGES, BYTES_RANGE);
        context.setType(StreamingOutput.class);
        context.setEntity(new MediaStreaming(
                        entity,
                requestContext.getHeaderString(MediaStreaming.RANGE),
                        process,
                        context.getMediaType(),
                        context.getHeaders()
                )
        );
    }
}
 
Example #5
Source File: BuildEndpoint.java    From pnc with Apache License 2.0 6 votes vote down vote up
/**
 * {@value GET_BUILD_LOGS_DESC}
 *
 * @param id {@value B_ID}
 * @return
 */
@Operation(
        summary = GET_BUILD_LOGS_DESC,
        responses = {
                @ApiResponse(
                        responseCode = SUCCESS_CODE,
                        description = SUCCESS_DESCRIPTION,
                        content = @Content(schema = @Schema(implementation = String.class))),
                @ApiResponse(responseCode = NOT_FOUND_CODE, description = NOT_FOUND_DESCRIPTION),
                @ApiResponse(
                        responseCode = SERVER_ERROR_CODE,
                        description = SERVER_ERROR_DESCRIPTION,
                        content = @Content(schema = @Schema(implementation = ErrorResponse.class))) })
@GET
@Path("/{id}/logs/build")
@Produces(MediaType.TEXT_PLAIN)
StreamingOutput getBuildLogs(@Parameter(description = B_ID) @PathParam("id") String id);
 
Example #6
Source File: AuditService.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@GET
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Generate audit log")
@ApiResponses(
  value = {
    @ApiResponse(code = 200, message = "OK"),
    @ApiResponse(code = 500, message = "Server error")
  }
)
public Response downloadReport() throws ServerException, ConflictException, IOException {
  java.nio.file.Path report = auditManager.generateAuditReport();

  StreamingOutput stream =
      outputStream -> {
        try {
          copy(report, outputStream);
        } finally {
          auditManager.deleteReportDirectory(report);
        }
      };

  return Response.ok(stream, MediaType.TEXT_PLAIN)
      .header("Content-Length", String.valueOf(Files.size(report)))
      .header("Content-Disposition", "attachment; filename=" + report.getFileName().toString())
      .build();
}
 
Example #7
Source File: PlannerResource.java    From wings with Apache License 2.0 6 votes vote down vote up
@POST
@Path("getData")
@Produces(MediaType.APPLICATION_JSON)
public StreamingOutput getData(
    @JsonProperty("template_bindings") final TemplateBindings tbindings) {
  if(this.wp != null) {
    return new StreamingOutput() {
      @Override
      public void write(OutputStream os) throws IOException,
          WebApplicationException {
        PrintWriter out = new PrintWriter(os);
        wp.printSuggestedDataJSON(tbindings, noexplain, out);
        out.flush();
      }
    };
  }
  return null;
}
 
Example #8
Source File: MCRJobQueueResource.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@GET()
@Produces(MediaType.APPLICATION_JSON)
@MCRRestrictedAccess(MCRJobQueuePermission.class)
public Response listJSON() {
    try {
        Queues queuesEntity = new Queues();
        queuesEntity.addAll(
            MCRJobQueue.INSTANCES.keySet().stream().map(Queue::new).collect(Collectors.toList()));

        return Response.ok().status(Response.Status.OK).entity(queuesEntity)
            .build();
    } catch (Exception e) {
        final StreamingOutput so = (OutputStream os) -> e
            .printStackTrace(new PrintStream(os, false, StandardCharsets.UTF_8.name()));
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(so).build();
    }
}
 
Example #9
Source File: TableScanResource.java    From hbase with Apache License 2.0 6 votes vote down vote up
@GET
@Produces({ Constants.MIMETYPE_PROTOBUF, Constants.MIMETYPE_PROTOBUF_IETF })
public Response getProtobuf(
    final @Context UriInfo uriInfo,
    final @HeaderParam("Accept") String contentType) {
  if (LOG.isTraceEnabled()) {
    LOG.trace("GET " + uriInfo.getAbsolutePath() + " as " +
            MIMETYPE_BINARY);
  }
  servlet.getMetrics().incrementRequests(1);
  try {
    int fetchSize = this.servlet.getConfiguration().getInt(Constants.SCAN_FETCH_SIZE, 10);
    StreamingOutput stream = new ProtobufStreamingOutput(this.results, contentType,
        userRequestedLimit, fetchSize);
    servlet.getMetrics().incrementSucessfulScanRequests(1);
    ResponseBuilder response = Response.ok(stream);
    response.header("content-type", contentType);
    return response.build();
  } catch (Exception exp) {
    servlet.getMetrics().incrementFailedScanRequests(1);
    processException(exp);
    LOG.warn(exp.toString(), exp);
    return null;
  }
}
 
Example #10
Source File: CustomerResource.java    From resteasy-examples with Apache License 2.0 6 votes vote down vote up
@GET
@Path("{id}")
@Produces("application/xml")
public StreamingOutput getCustomer(@PathParam("id") int id)
{
   final Customer customer = customerDB.get(id);
   if (customer == null)
   {
      throw new WebApplicationException(Response.Status.NOT_FOUND);
   }
   return new StreamingOutput()
   {
      public void write(OutputStream outputStream) throws IOException, WebApplicationException
      {
         outputCustomer(outputStream, customer);
      }
   };
}
 
Example #11
Source File: BufferedStreamingOutputTest.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void write() throws IOException {

    String testSentence = "robe";
    ByteArrayInputStream inputStream = new ByteArrayInputStream(testSentence.getBytes("UTF-8"));
    File file = Files.writeToTemp(inputStream);
    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
    StreamingOutput stream = new BufferedStreamingOutput(bufferedInputStream, 5);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    stream.write(outputStream);
    Assert.assertTrue(outputStream.size() == 4);


    bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
    stream = new BufferedStreamingOutput(bufferedInputStream, 3);

    outputStream = new ByteArrayOutputStream();
    stream.write(outputStream);
    Assert.assertTrue(outputStream.size() == 4);

}
 
Example #12
Source File: BuildEndpoint.java    From pnc with Apache License 2.0 6 votes vote down vote up
/**
 * {@value GET_ALIGN_LOGS_DESC}
 *
 * @param id {@value B_ID}
 * @return
 */
@Operation(
        summary = GET_ALIGN_LOGS_DESC,
        responses = {
                @ApiResponse(
                        responseCode = SUCCESS_CODE,
                        description = SUCCESS_DESCRIPTION,
                        content = @Content(schema = @Schema(implementation = String.class))),
                @ApiResponse(responseCode = NOT_FOUND_CODE, description = NOT_FOUND_DESCRIPTION),
                @ApiResponse(
                        responseCode = SERVER_ERROR_CODE,
                        description = SERVER_ERROR_DESCRIPTION,
                        content = @Content(schema = @Schema(implementation = ErrorResponse.class))) })
@GET
@Path("/{id}/logs/align")
@Produces(MediaType.TEXT_PLAIN)
StreamingOutput getAlignLogs(@Parameter(description = B_ID) @PathParam("id") String id);
 
Example #13
Source File: StatisticsResource.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
private Response generateAggregatedReport(IStatisticsReportHandler statisticsReportHandler,
                                          AggregateReportParameters parameters) {

    String reportName = statisticsReportHandler.getReportName(parameters);
    StreamingOutput stream = out -> {
        try {
            statisticsReportHandler.writeReport(out);
        } catch(Exception e) {
            logger.error(e.getMessage(), e);
            throw new WebApplicationException(e);
        }
    };
    return Response
            .ok(stream)
            .header("content-disposition",
                    "attachment; filename = "
                            + reportName).build();
}
 
Example #14
Source File: StatisticsResource.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
private Response generateStatsPerTags(List<TagGroupDimension> selectedDimensions) {
    List<TagGroupReportResult> tagGroupReportResults = StatisticsUtils.generateTagGroupReportResults(
            getStatisticsService(), selectedDimensions, new TagGroupReportParameters());
    String reportName = StatisticsUtils.createStatsPerTagsName();
    StreamingOutput stream = out -> {
        try {
            StatisticsUtils.writeTagGroupReportToCsv(out, tagGroupReportResults);
        } catch(Exception e) {
            logger.error(e.getMessage(), e);
            throw new WebApplicationException(e);
        }
    };
    return Response
            .ok(stream)
            .header("content-disposition",
                    "attachment; filename = "
                            + reportName).build();
}
 
Example #15
Source File: PlannerResource.java    From wings with Apache License 2.0 6 votes vote down vote up
@POST
@Path("getParameters")
@Produces(MediaType.APPLICATION_JSON)
public StreamingOutput getParameters(
    @JsonProperty("template_bindings") final TemplateBindings tbindings) {
  if(this.wp != null) {
    return new StreamingOutput() {
      @Override
      public void write(OutputStream os) throws IOException,
          WebApplicationException {
        PrintWriter out = new PrintWriter(os);
        wp.printSuggestedParametersJSON(tbindings, noexplain, out);
        out.flush();
      }
    };
  }
  return null;
}
 
Example #16
Source File: PrintPDF.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/")
public Response viewPDF(@BeanParam final Coordinates coord, @Context final HttpServletRequest request,
		@Context final ServletContext context, @QueryParam("view") final String view) throws URISyntaxException {

	final String urlcontext = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ request.getContextPath();
	final String previousPage = request.getHeader("Referer");

	final String productString = "/" + coord.getProduct() + "/" + coord.getVersionString() + "/" + coord.getBuild();
	final String urlstring = urlcontext + "/print/" + productString;

	// Getting the location of PHANTOMJS_HOME environment variable
	final String phantomjsloc = Objects.toString(context.getInitParameter(XBDD_PHANTOMJS_HOME_INIT_PARAMETER),
			System.getProperty("PHANTOMJS_HOME"));
	if (phantomjsloc == null) {
		final URI location = new URI(previousPage + "&phantom=no");
		return Response.temporaryRedirect(location).build();
	} else {
		final String username = Objects.toString(context.getInitParameter(XBDD_PHANTOMJS_USERNAME_INIT_PARAMETER),
				System.getProperty("PHANTOMJS_USER"));
		final String password = Objects.toString(context.getInitParameter(XBDD_PHANTOMJS_PASSWORD_INIT_PARAMETER),
				System.getProperty("PHANTOMJS_PASSWORD"));
		final StreamingOutput stream = createPDFStream(urlstring, phantomjsloc, context.getRealPath("/WEB-INF/rasterize.js"), username,
				password);

		String viewType = "inline";
		// View in browser or download as attachment
		if (view != null) {
			viewType = view;
		}

		final ResponseBuilder response = Response.ok(stream);
		response.type("application/pdf");
		response.status(200);
		response.header("Content-Disposition", viewType + "; filename=\"" + coord.getProduct() + " Version=" +
				coord.getVersionString() + ", Build=" + coord.getBuild() + ".pdf\"");
		return response.build();
	}
}
 
Example #17
Source File: StandardServiceFacade.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public StreamingOutput getExtensionRepoExtensionDocs(final URI baseUri, final String bucketName, final String groupId,
                                                     final String artifactId, final String version, final String extensionName) {
    final Bucket bucket = registryService.getBucketByName(bucketName);
    authorizeBucketAccess(RequestAction.READ, bucket.getIdentifier());

    final BundleVersion bundleVersion = extensionService.getBundleVersion(bucket.getIdentifier(), groupId, artifactId, version);
    final StreamingOutput streamingOutput = (output) -> extensionService.writeExtensionDocs(bundleVersion, extensionName, output);
    return streamingOutput;
}
 
Example #18
Source File: StandardServiceFacade.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public StreamingOutput getExtensionDocs(final String bundleIdentifier, final String version, final String name) {
    final Bundle bundle = extensionService.getBundle(bundleIdentifier);
    authorizeBucketAccess(RequestAction.READ, bundle);

    final String bucketIdentifier = bundle.getBucketIdentifier();
    final BundleVersion bundleVersion = extensionService.getBundleVersion(bucketIdentifier, bundleIdentifier, version);

    final StreamingOutput streamingOutput = (output) -> extensionService.writeExtensionDocs(bundleVersion, name, output);
    return streamingOutput;
}
 
Example #19
Source File: TomEEJohnzonProvider.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isWriteable(final Class<?> rawType, final Type genericType,
                           final Annotation[] annotations, final MediaType mediaType) {
    return super.isWriteable(rawType, genericType, annotations, mediaType)
            && !OutputStream.class.isAssignableFrom(rawType)
            && !StreamingOutput.class.isAssignableFrom(rawType)
            && !Writer.class.isAssignableFrom(rawType)
            && !Response.class.isAssignableFrom(rawType)
            && !JsonStructure.class.isAssignableFrom(rawType);
}
 
Example #20
Source File: BooksResource.java    From jaxrs-hypermedia with Apache License 2.0 5 votes vote down vote up
@GET
public StreamingOutput getBooks() {
    final List<BookTeaser> books = bookStore.getBookTeasers();
    books.forEach(b -> b.getLinks().put("self", resourceUriBuilder.forBook(b.getId(), uriInfo)));

    return output -> jsonb.toJson(books, output);
}
 
Example #21
Source File: MutatingLdpHandler.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Check the constraints of a graph.
 * @param graph the graph
 * @param type the LDP interaction model
 * @param syntax the output syntax
 */
protected void checkConstraint(final Graph graph, final IRI type, final RDFSyntax syntax) {
    final List<ConstraintViolation> violations = new ArrayList<>();
    getServices().getConstraintServices().forEach(svc -> svc.constrainedBy(getInternalId(), type, graph)
            .forEach(violations::add));
    if (!violations.isEmpty()) {
        final ResponseBuilder err = status(CONFLICT);
        violations.forEach(v -> err.link(v.getConstraint().getIRIString(), LDP.constrainedBy.getIRIString()));
        throw new ClientErrorException(err.entity((StreamingOutput) out ->
                getServices().getIOService().write(violations.stream().flatMap(v2 -> v2.getTriples().stream()),
                        out, syntax, getIdentifier())).type(syntax.mediaType()).build());
    }
}
 
Example #22
Source File: CustomerService.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/monitor")
@Produces("text/*")
public StreamingOutput monitorCustomers(
        @HeaderParam(WebSocketConstants.DEFAULT_REQUEST_ID_KEY) String reqid) {
    final String key = reqid == null ? "*" : reqid;
    return new StreamingOutput() {
        public void write(final OutputStream out) throws IOException, WebApplicationException {
            monitors.put(key, new WriterHolder(out, MAX_ERROR_COUNT));
            out.write(("Subscribed at " + new java.util.Date()).getBytes());
        }

    };
}
 
Example #23
Source File: BinaryDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mt) {
    return byte[].class.isAssignableFrom(type)
           || InputStream.class.isAssignableFrom(type)
           || Reader.class.isAssignableFrom(type)
           || File.class.isAssignableFrom(type)
           || StreamingOutput.class.isAssignableFrom(type);
}
 
Example #24
Source File: StandardServiceFacade.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public StreamingContent getExtensionRepoVersionContent(final String bucketName, final String groupId, final String artifactId,
                                                       final String version) {
    final Bucket bucket = registryService.getBucketByName(bucketName);
    authorizeBucketAccess(RequestAction.READ, bucket.getIdentifier());

    final BundleVersion bundleVersion = extensionService.getBundleVersion(bucket.getIdentifier(), groupId, artifactId, version);
    final StreamingOutput streamingOutput = (output) -> extensionService.writeBundleVersionContent(bundleVersion, output);
    return new StreamingContent(streamingOutput, bundleVersion.getFilename());
}
 
Example #25
Source File: BulkExtract.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a streaming response for the sample data file.
 *
 * @param request - HTTP servlet request for public bulk extract file
 *
 * @return A response with the sample extract file
 *
 * @throws Exception On Error
 */
@GET
@Path("extract")
@RightsAllowed({ Right.BULK_EXTRACT })
public Response get(@Context HttpServletRequest request) throws Exception {
    LOG.info("Received request to stream sample bulk extract...");

    logSecurityEvent("Received request to stream sample bulk extract");

    validateRequestCertificate(request);

    final InputStream is = this.getClass().getResourceAsStream("/bulkExtractSampleData/" + SAMPLED_FILE_NAME);

    StreamingOutput out = new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            int n;
            byte[] buffer = new byte[1024];
            while ((n = is.read(buffer)) > -1) {
                output.write(buffer, 0, n);
            }
        }
    };

    ResponseBuilder builder = Response.ok(out);
    builder.header("content-disposition", "attachment; filename = " + SAMPLED_FILE_NAME);
    builder.header("last-modified", "Not Specified");
    logSecurityEvent("Successful request to stream sample bulk extract");
    return builder.build();
}
 
Example #26
Source File: MatchService.java    From render with GNU General Public License v2.0 5 votes vote down vote up
@Path("v1/owner/{owner}/matchCollection/{matchCollection}/group/{pGroupId}/matchesWith/{qGroupId}")
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Find matches between the specified groups",
        notes = "Find all matches with one tile in the specified p layer and another tile in the specified q layer.",
        response = CanvasMatches.class,
        responseContainer="List")
@ApiResponses(value = {
        @ApiResponse(code = 404, message = "Match collection not found")
})
public Response getMatchesBetweenGroups(@PathParam("owner") final String owner,
                                        @PathParam("matchCollection") final String matchCollection,
                                        @PathParam("pGroupId") final String pGroupId,
                                        @PathParam("qGroupId") final String qGroupId,
                                        @DefaultValue("false") @QueryParam("excludeMatchDetails") final boolean excludeMatchDetails,
                                        @QueryParam("mergeCollection") final List<String> mergeCollectionList) {

    LOG.info("getMatchesBetweenGroups: entry, owner={}, matchCollection={}, pGroupId={}, qGroupId={}, mergeCollectionList={}",
             owner, matchCollection, pGroupId, qGroupId, mergeCollectionList);

    final MatchCollectionId collectionId = getCollectionId(owner, matchCollection);
    final List<MatchCollectionId> mergeCollectionIdList = getCollectionIdList(owner, mergeCollectionList);
    final StreamingOutput responseOutput =
            output -> matchDao.writeMatchesBetweenGroups(collectionId, mergeCollectionIdList, pGroupId, qGroupId, excludeMatchDetails, output);

    return streamResponse(responseOutput);
}
 
Example #27
Source File: StreamOutputEntityProvider.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void writeTo(StreamingOutput streamingOutput,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException {
    streamingOutput.write(entityStream);
}
 
Example #28
Source File: MCRSassResource.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("{fileName:.+}")
@Produces("text/css")
public Response getCSS(@PathParam("fileName") String name, @Context Request request) {
    try {
        MCRServletContextResourceImporter importer = new MCRServletContextResourceImporter(context);
        Optional<String> cssFile = MCRSassCompilerManager.getInstance()
            .getCSSFile(name, Stream.of(importer).collect(Collectors.toList()));

        if (cssFile.isPresent()) {
            CacheControl cc = new CacheControl();
            cc.setMaxAge(SECONDS_OF_ONE_DAY);

            String etagString = MCRSassCompilerManager.getInstance().getLastMD5(name).get();
            EntityTag etag = new EntityTag(etagString);

            Response.ResponseBuilder builder = request.evaluatePreconditions(etag);
            if (builder != null) {
                return builder.cacheControl(cc).tag(etag).build();
            }

            return Response.ok().status(Response.Status.OK)
                .cacheControl(cc)
                .tag(etag)
                .entity(cssFile.get())
                .build();
        } else {
            return Response.status(Response.Status.NOT_FOUND)
                .build();
        }
    } catch (IOException | CompilationException e) {
        StreamingOutput so = (OutputStream os) -> e.printStackTrace(new PrintStream(os, true,
            StandardCharsets.UTF_8));
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(so).build();
    }
}
 
Example #29
Source File: TomEEJsonpProvider.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isWriteable(final Class<?> rawType, final Type genericType,
                           final Annotation[] annotations, final MediaType mediaType) {
    return super.isWriteable(rawType, genericType, annotations, mediaType)
            && !OutputStream.class.isAssignableFrom(rawType)
            && !StreamingOutput.class.isAssignableFrom(rawType)
            && !Writer.class.isAssignableFrom(rawType)
            && !Response.class.isAssignableFrom(rawType);
}
 
Example #30
Source File: MatchService.java    From render with GNU General Public License v2.0 5 votes vote down vote up
@Path("v1/owner/{owner}/matchCollection/{matchCollection}/group/{groupId}/matchesOutsideGroup")
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Find matches outside the specified group",
        notes = "Find all matches with one tile in the specified layer and another tile outside that layer.",
        response = CanvasMatches.class,
        responseContainer="List")
@ApiResponses(value = {
        @ApiResponse(code = 404, message = "Match collection not found")
})
public Response getMatchesOutsideGroup(@PathParam("owner") final String owner,
                                       @PathParam("matchCollection") final String matchCollection,
                                       @PathParam("groupId") final String groupId,
                                       @DefaultValue("false") @QueryParam("excludeMatchDetails") final boolean excludeMatchDetails,
                                       @QueryParam("mergeCollection") final List<String> mergeCollectionList) {

    LOG.info("getMatchesOutsideGroup: entry, owner={}, matchCollection={}, groupId={}, mergeCollectionList={}",
             owner, matchCollection, groupId, mergeCollectionList);

    final MatchCollectionId collectionId = getCollectionId(owner, matchCollection);
    final List<MatchCollectionId> mergeCollectionIdList = getCollectionIdList(owner, mergeCollectionList);
    final StreamingOutput responseOutput =
            output -> matchDao.writeMatchesOutsideGroup(collectionId, mergeCollectionIdList, groupId, excludeMatchDetails, output);

    return streamResponse(responseOutput);
}