java类javax.ws.rs.core.StreamingOutput的实例源码

TranslationService.java 文件源码 项目:InComb 阅读 29 收藏 0 点赞 0 评论 0
/**
 * 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();
}
ItemResourceImpl.java 文件源码 项目:neoscada 阅读 31 收藏 0 点赞 0 评论 0
@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$
}
TerraformResource.java 文件源码 项目:plugin-prov 阅读 29 收藏 0 点赞 0 评论 0
/**
 * 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();
}
JobResource.java 文件源码 项目:jobson 阅读 34 收藏 0 点赞 0 评论 0
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();
    }
}
VCloudPluginResource.java 文件源码 项目:plugin-vm-vcloud 阅读 32 收藏 0 点赞 0 评论 0
/**
 * 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);
    };
}
JxlsUtils.java 文件源码 项目:simter-jxls-ext 阅读 28 收藏 0 点赞 0 评论 0
/**
 * 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;
}
JpaBenchResource.java 文件源码 项目:bootstrap 阅读 23 收藏 0 点赞 0 评论 0
/**
 * 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);
        }
    };
}
JpaBenchResourceTest.java 文件源码 项目:bootstrap 阅读 27 收藏 0 点赞 0 评论 0
@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);
    }
}
JpaBenchResourceTest.java 文件源码 项目:bootstrap 阅读 24 收藏 0 点赞 0 评论 0
@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);
    }
}
JobResource.java 文件源码 项目:dremio-oss 阅读 33 收藏 0 点赞 0 评论 0
@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()));
  }
}
SupportResource.java 文件源码 项目:dremio-oss 阅读 28 收藏 0 点赞 0 评论 0
@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();
}
JiraExportPluginResourceTest.java 文件源码 项目:plugin-bt-jira 阅读 29 收藏 0 点赞 0 评论 0
@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);
}
MCRJobQueueResource.java 文件源码 项目:mycore 阅读 27 收藏 0 点赞 0 评论 0
@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();
    }
}
MCRJobQueueResource.java 文件源码 项目:mycore 阅读 33 收藏 0 点赞 0 评论 0
@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();
    }
}
LocalStorage.java 文件源码 项目:hangar 阅读 34 收藏 0 点赞 0 评论 0
@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();
    }
}
Types.java 文件源码 项目:aml 阅读 28 收藏 0 点赞 0 评论 0
/**
 * <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);
    }
}
Types.java 文件源码 项目:aml 阅读 28 收藏 0 点赞 0 评论 0
/**
 * <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);
    }
}
DataDownload.java 文件源码 项目:openregister-java 阅读 27 收藏 0 点赞 0 评论 0
@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();
}
DataDownload.java 文件源码 项目:openregister-java 阅读 27 收藏 0 点赞 0 评论 0
@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();
}
DocumentService.java 文件源码 项目:document-management-system 阅读 29 收藏 0 点赞 0 评论 0
@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);
    }
}
BrokerStats.java 文件源码 项目:incubator-pulsar 阅读 23 收藏 0 点赞 0 评论 0
@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);
        }
    });
}
AdminTest.java 文件源码 项目:incubator-pulsar 阅读 26 收藏 0 点赞 0 评论 0
@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
    }
}
CypherExecutor.java 文件源码 项目:WhiteLab2.0-Neo4J-Plugin 阅读 31 收藏 0 点赞 0 评论 0
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();
}
MetadatumSearcher.java 文件源码 项目:WhiteLab2.0-Neo4J-Plugin 阅读 31 收藏 0 点赞 0 评论 0
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();
}
MetadatumSearcher.java 文件源码 项目:WhiteLab2.0-Neo4J-Plugin 阅读 33 收藏 0 点赞 0 评论 0
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();
}
MetadatumSearcher.java 文件源码 项目:WhiteLab2.0-Neo4J-Plugin 阅读 28 收藏 0 点赞 0 评论 0
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();
}
JobResource.java 文件源码 项目:latte-rodeo 阅读 36 收藏 0 点赞 0 评论 0
@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();
}
ApiResource.java 文件源码 项目:jrestless-examples 阅读 27 收藏 0 点赞 0 评论 0
@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);
                }
            }
        }
    };
}
CustomerResource.java 文件源码 项目:resteasy-examples 阅读 30 收藏 0 点赞 0 评论 0
@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>");
      }
   };
}
CustomerResource.java 文件源码 项目:resteasy-examples 阅读 27 收藏 0 点赞 0 评论 0
@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);
}


问题


面经


文章

微信
公众号

扫码关注公众号