Search in sources :

Example 46 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project onebusaway-application-modules by camsys.

the class AlertsFromRssResource method getAll.

@Path("/service-alerts")
@GET
@Produces("application/x-google-protobuff")
public Response getAll() {
    final FeedMessage serviceAlertFeed = _alertsService.getServlceAlertFeed();
    if (serviceAlertFeed == null) {
        return Response.ok().build();
    }
    StreamingOutput stream = new StreamingOutput() {

        @Override
        public void write(OutputStream os) throws IOException, WebApplicationException {
            // Service Alerts know how to write themselves as protocol buffers
            serviceAlertFeed.writeTo(os);
        }
    };
    Response response = Response.ok(stream).build();
    return response;
}
Also used : Response(javax.ws.rs.core.Response) FeedMessage(com.google.transit.realtime.GtfsRealtime.FeedMessage) OutputStream(java.io.OutputStream) StreamingOutput(javax.ws.rs.core.StreamingOutput) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 47 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project lobcder by skoulouzis.

the class Archive method getZip.

/**
 * Generates a zip archive of folder
 *
 * @param path the folder name
 * @return the stream of the archive
 */
@GET
@Path("/getzip/{name:.+}")
public Response getZip(@PathParam("name") String path) {
    class Folder {

        private String path;

        private LogicalData logicalData;

        private Folder(String path, LogicalData logicalData) {
            this.path = path;
            this.logicalData = logicalData;
        }

        /**
         * @return the path
         */
        public String getPath() {
            return path;
        }

        /**
         * @param path the path to set
         */
        public void setPath(String path) {
            this.path = path;
        }

        /**
         * @return the logicalData
         */
        public LogicalData getLogicalData() {
            return logicalData;
        }

        /**
         * @param logicalData the logicalData to set
         */
        public void setLogicalData(LogicalData logicalData) {
            this.logicalData = logicalData;
        }
    }
    final String rootPath;
    if (path.endsWith("/")) {
        rootPath = path.substring(0, path.length() - 1);
    } else {
        rootPath = path;
    }
    int index = rootPath.lastIndexOf('/');
    final String rootName;
    if (index != -1) {
        rootName = rootPath.substring(index + 1);
    } else {
        rootName = rootPath;
    }
    if (rootName.isEmpty()) {
        throw new WebApplicationException(Response.Status.NOT_ACCEPTABLE);
    }
    final MyPrincipal principal = (MyPrincipal) request.getAttribute("myprincipal");
    final JDBCatalogue catalogue = getCatalogue();
    StreamingOutput result = new StreamingOutput() {

        @Override
        public void write(OutputStream out) throws IOException, WebApplicationException {
            Stack<Folder> folders;
            try (Connection connection = catalogue.getConnection()) {
                LogicalData rootElement = catalogue.getLogicalDataByPath(io.milton.common.Path.path(rootPath), connection);
                if (rootElement == null) {
                    throw new WebApplicationException(Response.Status.NOT_FOUND);
                }
                try (ZipOutputStream zip = new ZipOutputStream(out)) {
                    ZipEntry ze;
                    folders = new Stack<>();
                    Permissions p = catalogue.getPermissions(rootElement.getUid(), rootElement.getOwner(), connection);
                    if (principal.canRead(p)) {
                        if (rootElement.isFolder()) {
                            folders.add(new Folder(rootName, rootElement));
                        } else {
                            ze = new ZipEntry(rootName);
                            zip.putNextEntry(ze);
                            List<PDRIDescr> pdris = catalogue.getPdriDescrByGroupId(rootElement.getPdriGroupId());
                            copyStream(pdris, zip);
                            zip.closeEntry();
                            getCatalogue().addViewForRes(rootElement.getUid());
                        }
                    }
                    while (!folders.isEmpty()) {
                        Folder folder = folders.pop();
                        ze = new ZipEntry(folder.getPath() + "/");
                        ze.setTime(folder.getLogicalData().getModifiedDate());
                        zip.putNextEntry(ze);
                        getCatalogue().addViewForRes(folder.getLogicalData().getUid());
                        for (LogicalData ld : catalogue.getChildrenByParentRef(folder.getLogicalData().getUid(), connection)) {
                            Permissions entry_p = catalogue.getPermissions(ld.getUid(), ld.getOwner(), connection);
                            if (principal.canRead(entry_p)) {
                                if (ld.isFolder()) {
                                    folders.push(new Folder(folder.getPath() + "/" + ld.getName(), ld));
                                } else {
                                    ze = new ZipEntry(folder.getPath() + "/" + ld.getName());
                                    ze.setTime(ld.getModifiedDate());
                                    zip.putNextEntry(ze);
                                    copyStream(catalogue.getPdriDescrByGroupId(ld.getPdriGroupId()), zip);
                                    zip.closeEntry();
                                    getCatalogue().addViewForRes(ld.getUid());
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                if (e instanceof WebApplicationException) {
                    throw (WebApplicationException) e;
                } else {
                    throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
                }
            }
        }
    };
    Response.ResponseBuilder response = Response.ok(result, "application/zip");
    return response.header("Content-Disposition", "attachment; filename=" + rootName + ".zip").build();
}
Also used : JDBCatalogue(nl.uva.cs.lobcder.catalogue.JDBCatalogue) WebApplicationException(javax.ws.rs.WebApplicationException) ZipOutputStream(java.util.zip.ZipOutputStream) OutputStream(java.io.OutputStream) ZipEntry(java.util.zip.ZipEntry) PDRIDescr(nl.uva.cs.lobcder.resources.PDRIDescr) Connection(java.sql.Connection) StreamingOutput(javax.ws.rs.core.StreamingOutput) SQLException(java.sql.SQLException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException) Response(javax.ws.rs.core.Response) LogicalData(nl.uva.cs.lobcder.resources.LogicalData) MyPrincipal(nl.uva.cs.lobcder.auth.MyPrincipal) ZipOutputStream(java.util.zip.ZipOutputStream) Permissions(nl.uva.cs.lobcder.auth.Permissions) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 48 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project plugin-prov by ligoj.

the class TerraformResourceTest method applyTerraformInternal.

@Test
public void applyTerraformInternal() throws IOException, InterruptedException {
    final File log = new File(MOCK_PATH, "main.log");
    final File tf = new File(MOCK_PATH, "main.tf");
    final TerraformResource resource = newResource(Mockito.mock(Terraforming.class), false);
    applyTerraform(resource);
    // Synchronization of sub processes
    Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> tf.exists() && log.exists() && IOUtils.toString(log.toURI(), "UTF-8").contains("show"));
    Thread.yield();
    Assertions.assertTrue(tf.exists());
    Assertions.assertTrue(log.exists());
    final String logString = IOUtils.toString(log.toURI(), "UTF-8");
    Assertions.assertTrue(logString.contains("plan"));
    Assertions.assertTrue(logString.contains("apply"));
    Assertions.assertTrue(logString.contains("show"));
    // Check the log file is well handled
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ((StreamingOutput) resource.getTerraformLog(subscription).getEntity()).write(bos);
    Assertions.assertEquals(logString, bos.toString(StandardCharsets.UTF_8));
    // Check the task status
    final TerraformStatus task = resource.runner.getTask("service:prov:test:account");
    Assertions.assertTrue(task.isFinished());
    Assertions.assertFalse(task.isFailed());
    Assertions.assertNotNull(task.getStart());
    Assertions.assertNotNull(task.getAuthor());
    Assertions.assertEquals(DEFAULT_USER, task.getAuthor());
    Assertions.assertEquals("service:prov:test:account", task.getLocked().getId());
    Assertions.assertNotNull(task.getEnd());
    Assertions.assertEquals(TerraformStep.SHOW, task.getStep());
}
Also used : StreamingOutput(javax.ws.rs.core.StreamingOutput) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) TerraformStatus(org.ligoj.app.plugin.prov.model.TerraformStatus) File(java.io.File) AbstractAppTest(org.ligoj.app.AbstractAppTest) Test(org.junit.jupiter.api.Test)

Example 49 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project plugin-prov by ligoj.

the class TerraformResourceTest method getTerraform.

@Test
public void getTerraform() throws IOException {
    final Terraforming terraforming = Mockito.mock(Terraforming.class);
    ((StreamingOutput) newResource(terraforming).getTerraform(subscription, "any.tf").getEntity()).write(new ByteArrayOutputStream());
    Mockito.verify(terraforming).terraform(ArgumentMatchers.any(OutputStream.class), ArgumentMatchers.eq(subscription), ArgumentMatchers.any(QuoteVo.class));
    // Coverage only
    Assertions.assertEquals(TerraformStep.PLAN, TerraformStep.valueOf(TerraformStep.values()[0].name()));
}
Also used : OutputStream(java.io.OutputStream) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) QuoteVo(org.ligoj.app.plugin.prov.QuoteVo) StreamingOutput(javax.ws.rs.core.StreamingOutput) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) AbstractAppTest(org.ligoj.app.AbstractAppTest) Test(org.junit.jupiter.api.Test)

Example 50 with StreamingOutput

use of javax.ws.rs.core.StreamingOutput in project OpenTripPlanner by opentripplanner.

the class Renderer method generateStreamingImageResponse.

public static Response generateStreamingImageResponse(final BufferedImage image, final MIMEImageFormat format) {
    if (image == null) {
        LOG.warn("response image is null");
    }
    StreamingOutput streamingOutput = new StreamingOutput() {

        public void write(OutputStream outStream) {
            try {
                long t0 = System.currentTimeMillis();
                ImageIO.write(image, format.type, outStream);
                long t1 = System.currentTimeMillis();
                LOG.debug("wrote image in {}msec", (int) (t1 - t0));
            } catch (Exception e) {
                LOG.error("exception while preparing image : {}", e.getMessage());
                throw new WebApplicationException(e);
            }
        }
    };
    CacheControl cc = new CacheControl();
    cc.setMaxAge(3600);
    cc.setNoCache(false);
    return Response.ok(streamingOutput).type(format.toString()).cacheControl(cc).build();
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) OutputStream(java.io.OutputStream) StreamingOutput(javax.ws.rs.core.StreamingOutput) CacheControl(javax.ws.rs.core.CacheControl) WebApplicationException(javax.ws.rs.WebApplicationException)

Aggregations

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