下面列出了怎么用javax.ws.rs.core.StreamingOutput的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* <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();
}
}
/**
* 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);
}
}
/**
* {@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);
@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);
}
/**
* {@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);
@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;
}
@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();
}
@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();
}
}
@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;
}
}
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();
}
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();
}
/**
* <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()
)
);
}
}
@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();
}
}
});
}
};
}
@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);
}
};
}
@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;
}
@Override
public Response download(String name) {
StructuredEventContainer events = structuredEventService.getStructuredEventsForStack(name, workspaceService.getForCurrentUser().getId());
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();
}
@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);
}
@GET
@Produces({MediaType.TEXT_PLAIN})
public Response getMetrics() {
Enumeration<Collector.MetricFamilySamples> mfs = prometheusRegistry.metricFamilySamples();
StreamingOutput stream = os -> {
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
TextFormat.write004(writer, mfs);
writer.flush();
};
return Response.ok(stream).build();
}
@Path("v1/owner/{owner}/matchCollection/{matchCollection}/pGroup/{pGroupId}/matches")
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Find matches with the specified pGroup",
notes = "Find all matches where the first tile is in the specified layer.",
response = CanvasMatches.class,
responseContainer="List")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "Match collection not found")
})
public Response getMatchesWithPGroup(@PathParam("owner") final String owner,
@PathParam("matchCollection") final String matchCollection,
@PathParam("pGroupId") final String pGroupId,
@DefaultValue("false") @QueryParam("excludeMatchDetails") final boolean excludeMatchDetails,
@QueryParam("mergeCollection") final List<String> mergeCollectionList) {
LOG.info("getMatchesWithPGroup: entry, owner={}, matchCollection={}, pGroupId={}, mergeCollectionList={}",
owner, matchCollection, pGroupId, mergeCollectionList);
final MatchCollectionId collectionId = getCollectionId(owner, matchCollection);
final List<MatchCollectionId> mergeCollectionIdList = getCollectionIdList(owner, mergeCollectionList);
final StreamingOutput responseOutput =
output -> matchDao.writeMatchesWithPGroup(collectionId, mergeCollectionIdList, pGroupId, excludeMatchDetails, output);
return streamResponse(responseOutput);
}
/**
* Intercepts and returns the entire contents the stream represented by
* this StreamResource.
*
* @return
* A response through which the entire contents of the intercepted
* stream will be sent.
*/
@GET
public Response getStreamContents() {
// Intercept all output
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException {
try {
tunnel.interceptStream(streamIndex, output);
}
catch (GuacamoleException e) {
throw new IOException(e);
}
}
};
// Begin successful response
ResponseBuilder responseBuilder = Response.ok(stream, mediaType);
// Set Content-Disposition header for "application/octet-stream"
if (mediaType.equals(MediaType.APPLICATION_OCTET_STREAM))
responseBuilder.header("Content-Disposition", "attachment");
return responseBuilder.build();
}
@NoOffloadsRouteExecutionStrategy
@Consumes(TEXT_PLAIN)
@Produces(TEXT_PLAIN)
@Path("/no-offloads-oio-streams")
@POST
public StreamingOutput postNoOffloadsOioStreams(final InputStream requestContent) {
return postOioStreams(requestContent);
}
@Consumes(TEXT_PLAIN)
@Produces(TEXT_PLAIN)
@Path("/text-oio-streams")
@POST
public StreamingOutput postTextOioStreams(final InputStream requestContent) {
return output -> {
output.write("GOT: ".getBytes(UTF_8));
int b;
while ((b = requestContent.read()) >= 0) {
output.write(b);
}
output.flush();
};
}
public StreamingOutput getLogsForBuild(String buildRecordLog) {
if (buildRecordLog == null)
return null;
return outputStream -> {
Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream));
writer.write(buildRecordLog);
writer.flush();
};
}
public Response getImageByteResponse(final StreamingOutput imageByteStream,
final String mimeType) {
Response.ResponseBuilder responseBuilder = Response.ok(imageByteStream, mimeType);
if (stackMetaData != null) {
final EntityTag eTag = getStackTag();
responseBuilder = responseBuilder.tag(eTag);
responseBuilder = setDefaultMaxAge(responseBuilder);
}
return responseBuilder.build();
}
private void drainResponse(final NodeResponse response) {
if (response.hasThrowable()) {
return;
}
try {
((StreamingOutput) response.getResponse().getEntity()).write(new NullOutputStream());
} catch (final IOException ioe) {
logger.info("Failed clearing out non-client response buffer from " + response.getNodeId() + " due to: " + ioe, ioe);
}
}
@GET
@Path("{id}")
public StreamingOutput getBook(@PathParam("id") long id) {
final Book book = bookStore.getBook(id);
book.getLinks().put("self", resourceUriBuilder.forBook(book.getId(), uriInfo));
if (bookStore.isAddToCartAllowed(book))
book.getLinks().put("add-to-cart", resourceUriBuilder.forShoppingCart(uriInfo));
return output -> jsonb.toJson(book, output);
}
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@GET
@Path("default")
public Response defaultPublicKey() {
final StreamingOutput streamingOutput = out -> out.write(enclave.defaultPublicKey().getKeyBytes());
return Response.ok(streamingOutput).build();
}
private Response getAuditEventsZipResponse(Collection<AuditEventV4Response> auditEventV4Responses, String resourceType) {
StreamingOutput streamingOutput = output -> {
try (ZipOutputStream zipOutputStream = new ZipOutputStream(output)) {
zipOutputStream.putNextEntry(new ZipEntry("struct-events.json"));
zipOutputStream.write(JsonUtil.writeValueAsString(auditEventV4Responses).getBytes());
zipOutputStream.closeEntry();
}
};
String fileName = String.format("audit-%s.zip", resourceType);
return Response.ok(streamingOutput).header("content-disposition", String.format("attachment; filename = %s", fileName)).build();
}
public static Response streamFile(String location, ServletContext context) {
final File f = new File(location);
if(!f.exists())
return Response.status(Status.NOT_FOUND).build();
if(!f.canRead())
return Response.status(Status.FORBIDDEN).build();
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException {
try {
if(f.isDirectory())
StorageHandler.streamDirectory(f, os);
else
StorageHandler.streamFile(f, os);
} catch (Exception e) {
e.printStackTrace();
}
}
};
String filename = f.getName();
String mime = context.getMimeType(f.getAbsolutePath());
if(f.isDirectory()) {
filename += ".zip";
mime = "application/zip";
}
return Response.ok(stream, mime)
.header("content-disposition", "attachment; filename = "+ filename)
.build();
}
@GET
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
public Response get(@Context Response response, @QueryParam(LumongoConstants.ID) final String uniqueId,
@QueryParam(LumongoConstants.FILE_NAME) final String fileName, @QueryParam(LumongoConstants.INDEX) final String indexName) {
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
if (uniqueId != null && fileName != null && indexName != null) {
InputStream is = indexManager.getAssociatedDocumentStream(indexName, uniqueId, fileName);
if (is != null) {
StreamHelper.copyStream(is, output);
}
else {
throw new WebApplicationException("Cannot find associated document with uniqueId <" + uniqueId + "> with fileName <" + fileName + ">",
LumongoConstants.NOT_FOUND);
}
}
else {
throw new WebApplicationException(LumongoConstants.ID + " and " + LumongoConstants.FILE_NAME + " are required",
LumongoConstants.BAD_REQUEST);
}
}
};
return Response.ok(stream).header("content-disposition", "attachment; filename = " + fileName).build();
}