/** * Returns Translations of a given {@link Locale} * @param locale to get the Translation of * @param request The HTTP-Request - is injected automatically * @return the translation */ @GET public Response getTranslations(@PathParam("locale") final String locale, @Context final Request request) { final Translator translator = TranslatorManager.getTranslator(LocaleUtil.toLocale(locale)); if(translator == null) { throw new NotFoundException(); } final File file = translator.getFile(); final Date lastModified = new Date(file.lastModified()); ResponseBuilder respBuilder = request.evaluatePreconditions(lastModified); if(respBuilder == null) { respBuilder = Response.ok(); } return respBuilder.lastModified(lastModified).entity(new StreamingOutput() { @Override public void write(final OutputStream output) throws IOException, WebApplicationException { IOUtils.copy(new FileInputStream(file), output); } }).build(); }
@Override public Response readAllCsv ( final String contextId ) { final DataContext context = this.provider.getContext ( contextId ); if ( context == null ) { logger.trace ( "Context '{}' not found", contextId ); //$NON-NLS-1$ throw new WebApplicationException ( Status.NOT_FOUND ); } final SortedMap<String, DataItemValue> values = context.getAllValues (); final StreamingOutput out = new StreamingOutput () { @Override public void write ( final OutputStream output ) throws IOException, WebApplicationException { streamAsCSV ( new PrintWriter ( new OutputStreamWriter ( output, StandardCharsets.UTF_8 ) ), values, ",", "\r\n" ); //$NON-NLS-1$ //$NON-NLS-2$ } }; return Response.ok ( out ).header ( "Content-Disposition", "attachment; filename=\"data.csv\"" ).build (); //$NON-NLS-1$ }
/** * Get the log of the current or last Terraform execution of a given * subscription. * * @param subscription * The related subscription. * @return the streaming {@link Response} with output. * @throws IOException * When Terraform content cannot be written. */ @GET @Produces(MediaType.TEXT_HTML) @Path("{subscription:\\d+}/terraform.log") public Response getTerraformLog(@PathParam("subscription") final int subscription) throws IOException { final Subscription entity = subscriptionResource.checkVisibleSubscription(subscription); final File log = toFile(entity, MAIN_LOG); // Check there is a log file if (log.exists()) { final StreamingOutput so = o -> FileUtils.copyFile(toFile(entity, MAIN_LOG), o); return Response.ok().entity(so).build(); } // No log file for now return Response.status(Status.NOT_FOUND).build(); }
private Response generateBinaryDataResponse(JobId jobId, Optional<BinaryData> maybeBinaryData) { if (maybeBinaryData.isPresent()) { final BinaryData binaryData = maybeBinaryData.get(); final StreamingOutput body = outputStream -> { IOUtils.copyLarge(binaryData.getData(), outputStream); binaryData.getData().close(); }; final Response.ResponseBuilder b = Response.ok(body, binaryData.getMimeType()) .header("Content-Length", binaryData.getSizeOf()); if (binaryData.getSizeOf() > Constants.MAX_JOB_OUTPUT_SIZE_IN_BYTES_BEFORE_DISABLING_COMPRESSION) b.header("Content-Encoding", "identity"); return b.build(); } else { return Response.status(404).build(); } }
/** * Return a snapshot of the console. * * @param subscription * the valid screenshot of the console. * @return the valid screenshot of the console. */ @GET @Path("{subscription:\\d+}/console.png") @Produces("image/png") public StreamingOutput getConsole(@PathParam("subscription") final int subscription) { final Map<String, String> parameters = subscriptionResource.getParameters(subscription); final VCloudCurlProcessor processor = new VCloudCurlProcessor(); authenticate(parameters, processor); // Get the screen thumbnail return output -> { final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_API), "/") + "vApp/vm-" + parameters.get(PARAMETER_VM) + "/screen"; final CurlRequest curlRequest = new CurlRequest("GET", url, null, (request, response) -> { if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) { // Copy the stream IOUtils.copy(response.getEntity().getContent(), output); output.flush(); } return false; }); processor.process(curlRequest); }; }
/** * Generate a {@link Response.ResponseBuilder} instance * and render the excel template with the specified data to its output stream. * * @param template the excel template, can be xlsx or xls format * @param data the data * @param filename the download filename of the response * @return the instance of {@link Response.ResponseBuilder} with the excel data * @throws RuntimeException if has IOException or UnsupportedEncodingException inner */ public static Response.ResponseBuilder renderTemplate2Response(InputStream template, Map<String, Object> data, String filename) { StreamingOutput stream = (OutputStream output) -> { // Convert to jxls Context Context context = convert2Context(data); // Add default functions addDefault(context); // render renderByJxls(template, output, context); }; // create response Response.ResponseBuilder builder = Response.ok(stream); if (filename != null) { try { builder.header("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\""); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } return builder; }
/** * Bench the get picture file. * * @return the JAX-RS stream. */ @GET @Path("picture.png") @Produces(MediaType.APPLICATION_OCTET_STREAM) @OnNullReturn404 public StreamingOutput downloadLobFile() { log.info("Picture download is requested"); final byte[] firstAvailableLob = jpaDao.getLastAvailableLob(); if (firstAvailableLob.length == 0) { return null; } return output -> { try { IOUtils.write(firstAvailableLob, output); } catch (final IOException e) { throw new IllegalStateException("Unable to write the LOB data", e); } }; }
@Test(expected = IllegalStateException.class) public void testDownloadDataBlobError() throws Exception { final URL jarLocation = getBlobFile(); InputStream openStream = null; try { // Get the JAR input openStream = jarLocation.openStream(); // Proceed to the test resource.prepareData(openStream, 1); final StreamingOutput downloadLobFile = resource.downloadLobFile(); final OutputStream output = Mockito.mock(OutputStream.class); Mockito.doThrow(new IOException()).when(output).write(ArgumentMatchers.any(byte[].class)); downloadLobFile.write(output); } finally { IOUtils.closeQuietly(openStream); } }
@Test public void testDownloadDataBlob() throws Exception { final URL jarLocation = getBlobFile(); InputStream openStream = null; try { // Get the JAR input openStream = jarLocation.openStream(); // Proceed to the test resource.prepareData(openStream, 1); final StreamingOutput downloadLobFile = resource.downloadLobFile(); final ByteArrayOutputStream output = new ByteArrayOutputStream(); downloadLobFile.write(output); org.junit.Assert.assertTrue(output.toByteArray().length > 3000000); } finally { IOUtils.closeQuietly(openStream); } }
@GET @Path("download") @Consumes(MediaType.APPLICATION_JSON) public Response downloadData(@PathParam("jobId") JobId jobId) throws IOException, JobResourceNotFoundException, JobNotFoundException { final Job job = jobsService.getJob(jobId); final JobInfo jobInfo = job.getJobAttempt().getInfo(); if (jobInfo.getQueryType() == QueryType.UI_EXPORT) { final DownloadDataResponse downloadDataResponse = datasetService.downloadData(jobInfo.getDownloadInfo(), securityContext.getUserPrincipal().getName()); final StreamingOutput streamingOutput = new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { IOUtils.copyBytes(downloadDataResponse.getInput(), output, 4096, true); } }; return Response.ok(streamingOutput, MediaType.APPLICATION_OCTET_STREAM) .header("Content-Disposition", "attachment; filename=\"" + downloadDataResponse.getFileName() + "\"").build(); } else { throw new JobResourceNotFoundException(jobId, format("Job %s has no data that can not be downloaded, invalid type %s", jobId, jobInfo.getQueryType())); } }
@POST @Path("download") @Consumes(MediaType.APPLICATION_JSON) public Response downloadData(@PathParam("jobId") JobId jobId) throws IOException, UserNotFoundException, JobResourceNotFoundException { final DownloadDataResponse response; try { response = supportService.downloadSupportRequest(context.getUserPrincipal().getName(), jobId); } catch (JobNotFoundException e) { throw JobResourceNotFoundException.fromJobNotFoundException(e); } final StreamingOutput streamingOutput = new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { IOUtils.copyBytes(response.getInput(), output, 4096, true); } }; return Response.ok(streamingOutput, MediaType.APPLICATION_OCTET_STREAM) .header("Content-Disposition", "attachment; filename=\"" + response.getFileName() + "\"").build(); }
@Test public void getStatusHistory() throws Exception { final int subscription = getSubscription("MDA"); final StreamingOutput csv = (StreamingOutput) resource.getStatusHistory(subscription, "file1").getEntity(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); csv.write(out); final BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()), "cp1252")); final String header = inputStreamReader.readLine(); Assert.assertEquals("issueid;key;author;from;to;fromText;toText;date;dateTimestamp", header); String lastLine = inputStreamReader.readLine(); Assert.assertEquals("11432;MDA-1;fdaugan;;1;;OPEN;2009/03/23 15:26:43;1237818403000", lastLine); lastLine = inputStreamReader.readLine(); Assert.assertEquals("11437;MDA-4;xsintive;;1;;OPEN;2009/03/23 16:23:31;1237821811000", lastLine); lastLine = inputStreamReader.readLine(); lastLine = inputStreamReader.readLine(); lastLine = inputStreamReader.readLine(); lastLine = inputStreamReader.readLine(); Assert.assertEquals("11535;MDA-8;challer;;1;;OPEN;2009/04/01 14:20:29;1238588429000", lastLine); lastLine = inputStreamReader.readLine(); lastLine = inputStreamReader.readLine(); lastLine = inputStreamReader.readLine(); Assert.assertEquals("11535;MDA-8;fdaugan;1;10024;OPEN;ASSIGNED;2009/04/09 09:45:16;1239263116000", lastLine); lastLine = inputStreamReader.readLine(); Assert.assertEquals("11535;MDA-8;fdaugan;10024;3;ASSIGNED;IN PROGRESS;2009/04/09 09:45:30;1239263130000", lastLine); }
@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(MediaType.APPLICATION_XML) @MCRRestrictedAccess(MCRJobQueuePermission.class) public Response listXML() { 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(toJSON(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(); } }
@Override public StreamingOutput getArtifactStream(final IndexArtifact artifact, final String filename) { Path streamPath = fs.getPath(getPath() + artifact.getLocation() + "/" + filename); if (Files.isReadable(streamPath)) { return new StreamingOutput() { public void write(OutputStream os) throws IOException, WebApplicationException { FileInputStream fis = new FileInputStream(streamPath.toString()); ByteStreams.copy(fis, os); fis.close(); } }; } else { throw new NotFoundException(); } }
/** * <p>getResponseEntityClass.</p> * * @param mimeType a {@link org.aml.apimodel.MimeType} object. * @return a {@link com.sun.codemodel.JType} object. * @throws java.io.IOException if any. */ public JType getResponseEntityClass(final MimeType mimeType) throws IOException { final JClass schemaClass = getSchemaClass(mimeType); if (schemaClass != null) { return schemaClass; } else if (startsWith(mimeType.getType(), "text/")) { return getGeneratorType(String.class); } else { // fallback to a streaming output return getGeneratorType(StreamingOutput.class); } }
@GET @Path("/download-rsf/{start-entry-number}") @Produces({ExtraMediaType.APPLICATION_RSF, ExtraMediaType.TEXT_HTML}) @DownloadNotAvailable @Timed public Response downloadPartialRSF(@PathParam("start-entry-number") int startEntryNumber) { if (startEntryNumber < 0) { throw new BadRequestException("start-entry-number must be 0 or greater"); } int totalEntriesInRegister = register.getTotalEntries(EntryType.user); if (startEntryNumber > totalEntriesInRegister) { throw new BadRequestException("start-entry-number must not exceed number of total entries in the register"); } String rsfFileName = String.format("attachment; filename=rsf-%d.%s", System.currentTimeMillis(), rsfFormatter.getFileExtension()); return Response .ok((StreamingOutput) output -> rsfService.writeTo(output, rsfFormatter, startEntryNumber, totalEntriesInRegister)) .header("Content-Disposition", rsfFileName).build(); }
@GET @Path("/download-rsf/{total-entries-1}/{total-entries-2}") @Produces({ExtraMediaType.APPLICATION_RSF, ExtraMediaType.TEXT_HTML}) @DownloadNotAvailable @Timed public Response downloadPartialRSF(@PathParam("total-entries-1") int totalEntries1, @PathParam("total-entries-2") int totalEntries2) { if (totalEntries1 < 0) { throw new BadRequestException("total-entries-1 must be 0 or greater"); } if (totalEntries2 < totalEntries1) { throw new BadRequestException("total-entries-2 must be greater than or equal to total-entries-1"); } int totalEntriesInRegister = register.getTotalEntries(); if (totalEntries2 > totalEntriesInRegister) { throw new BadRequestException("total-entries-2 must not exceed number of total entries in the register"); } String rsfFileName = String.format("attachment; filename=rsf-%d.%s", System.currentTimeMillis(), rsfFormatter.getFileExtension()); return Response .ok((StreamingOutput) output -> rsfService.writeTo(output, rsfFormatter, totalEntries1, totalEntries2)) .header("Content-Disposition", rsfFileName).build(); }
@GET @Path("/getContent") @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response getContent(@QueryParam("docId") String docId) throws GenericException { try { log.debug("getContent({})", new Object[]{docId}); DocumentModule dm = ModuleManager.getDocumentModule(); final InputStream is = dm.getContent(null, docId, false); StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream os) throws IOException, WebApplicationException { IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }; log.debug("getContent: [BINARY]"); return Response.ok(stream).build(); } catch (Exception e) { throw new GenericException(e); } }
@GET @Path("/destinations") @ApiOperation(value = "Get all the destination stats by namesapce", response = OutputStream.class, responseContainer = "OutputStream") // https://github.com/swagger-api/swagger-ui/issues/558 // map // support // missing @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission") }) public StreamingOutput getDestinations2() throws Exception { // Ensure super user access only validateSuperUserAccess(); return output -> pulsar().getBrokerService().getDimensionMetrics(statsBuf -> { try { output.write(statsBuf.array(), statsBuf.arrayOffset(), statsBuf.readableBytes()); } catch (Exception e) { throw new WebApplicationException(e); } }); }
@Test void brokerStats() throws Exception { doReturn("client-id").when(brokerStats).clientAppId(); Collection<Metrics> metrics = brokerStats.getMetrics(); assertNotNull(metrics); LocalBrokerData loadReport = (LocalBrokerData) brokerStats.getLoadReport(); assertNotNull(loadReport); assertNotNull(loadReport.getCpu()); Collection<Metrics> mBeans = brokerStats.getMBeans(); assertTrue(!mBeans.isEmpty()); AllocatorStats allocatorStats = brokerStats.getAllocatorStats("default"); assertNotNull(allocatorStats); Map<String, Map<String, PendingBookieOpsStats>> bookieOpsStats = brokerStats.getPendingBookieOpsStats(); assertTrue(bookieOpsStats.isEmpty()); StreamingOutput destination = brokerStats.getDestinations2(); assertNotNull(destination); try { Map<Long, Collection<ResourceUnit>> resource = brokerStats.getBrokerResourceAvailability("prop", "use", "ns2"); fail("should have failed as ModularLoadManager doesn't support it"); } catch (RestException re) { // Ok } }
public Response getQueryResult(final Query query) { StreamingOutput stream = new StreamingOutput() { @Override public void write( OutputStream os ) throws IOException, WebApplicationException { JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8); jg.setPrettyPrinter(new DefaultPrettyPrinter()); jg.writeStartObject(); if (query != null && query.toCypher().length() > 0) { writeQueryDetails(jg, query); System.out.println(query.toCypher()); executeQuery(jg, query); } else { jg.writeStringField("error", "No query supplied."); } jg.writeEndObject(); jg.flush(); jg.close(); } }; return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build(); }
protected Response getMetadataLabel(final String label) { StreamingOutput stream = new StreamingOutput() { @Override public void write( OutputStream os ) throws IOException, WebApplicationException { try ( Transaction tx = database.beginTx() ) { JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8); IndexManager index = database.index(); Index<Node> metadata = index.forNodes("Metadatum"); jg.writeStartArray(); for ( Node metadatum : metadata.query( "label:"+label ) ) { executor.writeField(metadatum, jg); } jg.writeEndArray(); jg.flush(); tx.success(); } } }; return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build(); }
protected Response updateMetadataLabel(final String label, final String property, final String value) { StreamingOutput stream = new StreamingOutput() { @Override public void write( OutputStream os ) throws IOException, WebApplicationException { try ( Transaction tx = database.beginTx() ) { JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8); IndexManager index = database.index(); Index<Node> metadata = index.forNodes("Metadatum"); for ( Node metadatum : metadata.query( "label:"+label ) ) { if (property.equals("explorable") || property.equals("searchable")) metadatum.setProperty(property, Boolean.valueOf(value)); else metadatum.setProperty(property, value); } jg.writeString("Updated "+label); jg.flush(); tx.success(); } } }; return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build(); }
protected Response getMetadataGroupKey(final String group, final String key) { StreamingOutput stream = new StreamingOutput() { @Override public void write( OutputStream os ) throws IOException, WebApplicationException { try ( Transaction tx = database.beginTx() ) { JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8); IndexManager index = database.index(); Index<Node> metadata = index.forNodes("Metadatum"); jg.writeStartArray(); for ( Node metadatum : metadata.query( "group:"+group+" AND key:"+key ) ) { executor.writeField(metadatum, jg); } jg.writeEndArray(); jg.flush(); tx.success(); } } }; return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build(); }
@Path("{identifier}/log.txt") @GET @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response getJobLog(@PathParam("identifier") JobIdentifier identifier) { final List<Job> list = model.query(new JobsByIdentifierOrStatus(identifier, null)); if (list.isEmpty()) { return respondFileNotFound(identifier); } String dir = list.get(0).getWorkDirectory(); if (dir == null) { return respondFileNotFound(identifier); } File workDirectory = new File(dir); final File file = new File(workDirectory, "log.txt"); if (!file.exists()) { return respondFileNotFound(identifier); } StreamingOutput output = new StreamingOutput() { @Override public void write(OutputStream out) throws IOException { Files.copy(file.toPath(), out); } }; return Response.ok(output, MediaType.TEXT_PLAIN).build(); }
@GET @Path("/cat-streaming-output") @Produces("image/gif") public StreamingOutput getRandomCatAsStreamingOutput() { return new StreamingOutput() { @Override public void write(OutputStream os) throws IOException, WebApplicationException { try (InputStream is = loadRandomCatGif()) { byte[] buffer = new byte[BUFFER_LENGTH]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } } } }; }
@GET @Produces("application/xml") public StreamingOutput getCustomers(final @QueryParam("start") int start, final @QueryParam("size") @DefaultValue("2") int size) { return new StreamingOutput() { public void write(OutputStream outputStream) throws IOException, WebApplicationException { PrintStream writer = new PrintStream(outputStream); writer.println("<customers>"); synchronized (customerDB) { int i = 0; for (Customer customer : customerDB.values()) { if (i >= start && i < start + size) outputCustomer(" ", writer, customer); i++; } } writer.println("</customers>"); } }; }
@GET @Produces("application/xml") @Path("uriinfo") public StreamingOutput getCustomers(@Context UriInfo info) { int start = 0; int size = 2; if (info.getQueryParameters().containsKey("start")) { start = Integer.valueOf(info.getQueryParameters().getFirst("start")); } if (info.getQueryParameters().containsKey("size")) { size = Integer.valueOf(info.getQueryParameters().getFirst("size")); } return getCustomers(start, size); }
@GET @Path("{id : \\d+}") @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); } }; }
@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); } }; }
@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 @Path("{first}-{last}") @Produces("application/xml") public StreamingOutput getCustomer(@PathParam("first") String firstName, @PathParam("last") String lastName) { final Customer customer = customerDB.get(firstName + "-" + lastName); if (customer == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return new StreamingOutput() { public void write(OutputStream outputStream) throws IOException, WebApplicationException { outputCustomer(outputStream, customer); } }; }
@GET @Secured @Path("/{id}") public Response downloadFile(@PathParam("id") String id) { File file = attachmentManager.getFileById(id); StreamingOutput fileStream = new StreamingOutput() { @Override public void write(java.io.OutputStream output) throws IOException { java.nio.file.Path path = file.toPath(); byte[] data = Files.readAllBytes(path); output.write(data); output.flush(); } }; return Response.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename = "+file.getName()).build(); }
/** * An endpoint at /fail. * * @param uriInfo The URI info of the request * @param asyncResponse The response to respond to */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("/fail") public void getFail(@Context UriInfo uriInfo, @Suspended AsyncResponse asyncResponse) { // Process stream StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream os) throws IOException { try { Thread.sleep(100); } catch (InterruptedException ignore) { // Ignore } throw new IOException(); } }; // pass stream handler as response javax.ws.rs.core.Response rsp = javax.ws.rs.core.Response.ok(stream).build(); asyncResponse.resume(rsp); }
/** * This version is different as we need to re-write the filename with the * timestamp for the latest version. * * @param key * IndexKey to find the Artifact in the Index * @param filename * Filename from the request * @return StreamingOutput from the Storage Layer */ protected StreamingOutput getSnapshotArtifact(JavaIndexKey key, String filename) { logger.info("[Downloading Snapshot] " + key); try { if (getIndex().isArtifact(key)) { JavaIndexArtifact ia = (JavaIndexArtifact) getIndex().getArtifact(key); String snapshotFilename = filename.replace(key.getVersion(), ia.getSnapshotVersion()); return getStorage().getArtifactStream(ia, snapshotFilename); } else { throw new NotFoundException(); } } catch (IndexException ie) { throw new InternalServerErrorException(); } }
@Override public void writeTo( Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { // Special case of unsupported type, where surrounding framework // may have, mistakengly, chosen this provider based on media type, but when // response will be streamed using StreamingOutput or is already prepared using // in the form of CharSequence if (t instanceof StreamingOutput) { ((StreamingOutput) t).write(entityStream); return; } if (t instanceof CharSequence) { // UTF-8 used because it should be considered default encoding for the JSON-family // of media types OutputStreamWriter writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8); writer.append((CharSequence) t); writer.flush(); return; } // Standard way of handling writing using gson try { streamer.write(gson, genericType, t, entityStream); } catch (IOException ex) { exceptionHandler.onWrite(gson, ex); throw ex; } }