Example usage for javax.servlet.http HttpServletResponse getOutputStream

List of usage examples for javax.servlet.http HttpServletResponse getOutputStream

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse getOutputStream.

Prototype

public ServletOutputStream getOutputStream() throws IOException;

Source Link

Document

Returns a ServletOutputStream suitable for writing binary data in the response.

Usage

From source file:org.zalando.logbook.servlet.example.ExampleController.java

@RequestMapping(value = "/read-byte", produces = MediaType.TEXT_PLAIN_VALUE)
public void readByte(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    final ServletInputStream input = request.getInputStream();
    final ServletOutputStream output = response.getOutputStream();

    while (true) {
        final int read = input.read();
        if (read == -1) {
            break;
        }//from w ww .  j  a v a2s  .c  om
        output.write(read);
    }
}

From source file:com.healthcit.cacure.web.controller.ModuleImportExportController.java

@RequestMapping(method = RequestMethod.GET)
public void exportModule(@RequestParam(value = "moduleId", required = true) long id,
        @RequestParam(value = "format", required = true) String format, HttpServletResponse response) {

    try {/* ww  w .  j a v  a2s .  c o m*/
        response.setContentType("text/xml");

        OutputStream oStream = response.getOutputStream();
        Cure cureXml = dataExporter.constructModuleXML(id);
        JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model");
        if (ExportFormat.XML.name().equals(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xml;", id);

            response.setHeader("Content-Disposition", fileNameHeader);
            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(cureXml, oStream);
        } else if (ExportFormat.EXCEL.name().equals(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xlxml;", id);

            response.setHeader("Content-Disposition", fileNameHeader);
            response.setContentType("application/xml");
            StreamSource xslSource = new StreamSource(this.getClass().getClassLoader()
                    .getResourceAsStream(AppConfig.getString(Constants.EXPORT_EXCEL_XSLT_FILE)));
            JAXBSource xmlSource = new JAXBSource(jc, cureXml);
            Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource);
            transformer.transform(xmlSource, new StreamResult(oStream));
        }
        oStream.flush();
    } catch (IOException e) {
        log.error("Unable to obtain output stream from the response");
        log.error(e.getMessage(), e);
    } catch (JAXBException e) {
        log.error("Unable to marshal the object");
        log.error(e.getMessage(), e);
    } catch (TransformerException e) {
        log.error("XSLT transformation failed");
        log.error(e.getMessage(), e);
    }
}

From source file:org.openmrs.module.clinicalsummary.web.controller.watcher.CohortEvaluationWatcherController.java

@RequestMapping(method = RequestMethod.GET)
public void watch(final HttpServletResponse response) throws IOException {
    response.setContentType(MimeType.APPLICATION_JSON);
    JsonFactory factory = new JsonFactory();
    JsonGenerator generator = factory.createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
    generator.useDefaultPrettyPrinter();

    generator.writeStartObject();/*from  w ww  .j  av  a  2 s .  c o  m*/

    SummaryCohortEvaluatorInstance instanceSummary = SummaryCohortEvaluatorInstance.getInstance();
    generator.writeBooleanField("running", instanceSummary.isRunning());
    generator.writeStringField("filename", instanceSummary.getCurrentPatient());
    generator.writeStringField("status", instanceSummary.getCurrentStatus());
    generator.writeStringField("counter", instanceSummary.getProcessed());
    generator.writeStringField("size", instanceSummary.getSize());

    generator.writeEndObject();

    generator.close();
}

From source file:org.openmrs.module.clinicalsummary.web.controller.watcher.ReminderEvaluationWatcherController.java

@RequestMapping(method = RequestMethod.GET)
public void watch(final HttpServletResponse response) throws IOException {
    response.setContentType(MimeType.APPLICATION_JSON);
    JsonFactory factory = new JsonFactory();
    JsonGenerator generator = factory.createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
    generator.useDefaultPrettyPrinter();

    generator.writeStartObject();//from w ww .j  a va  2s .  c  om

    ReminderCohortEvaluatorInstance instanceSummary = ReminderCohortEvaluatorInstance.getInstance();
    generator.writeBooleanField("running", instanceSummary.isRunning());
    generator.writeStringField("filename", instanceSummary.getCurrentPatient());
    generator.writeStringField("status", instanceSummary.getCurrentStatus());
    generator.writeStringField("counter", instanceSummary.getProcessed());
    generator.writeStringField("size", instanceSummary.getSize());

    generator.writeEndObject();

    generator.close();
}

From source file:org.openmrs.module.clinicalsummary.web.controller.watcher.RuleEvaluationWatcherController.java

@RequestMapping(method = RequestMethod.GET)
public void watch(final HttpServletResponse response) throws IOException {
    response.setContentType(MimeType.APPLICATION_JSON);
    JsonFactory factory = new JsonFactory();
    JsonGenerator generator = factory.createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
    generator.useDefaultPrettyPrinter();

    generator.writeStartObject();//from   w w  w.ja v a 2s.  co  m

    RuleCohortEvaluatorInstance instanceCohort = RuleCohortEvaluatorInstance.getInstance();
    generator.writeBooleanField("running", instanceCohort.isRunning());
    generator.writeStringField("filename", instanceCohort.getCurrentPatient());
    generator.writeStringField("status", instanceCohort.getCurrentStatus());
    generator.writeStringField("counter", instanceCohort.getProcessed());
    generator.writeStringField("size", instanceCohort.getSize());

    generator.writeEndObject();

    generator.close();
}

From source file:org.zalando.logbook.servlet.example.ExampleController.java

@RequestMapping(value = "/read-bytes", produces = MediaType.TEXT_PLAIN_VALUE)
public void readBytes(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    final ServletInputStream input = request.getInputStream();
    final ServletOutputStream output = response.getOutputStream();

    final byte[] buffer = new byte[1];

    while (true) {
        final int read = input.read(buffer);
        if (read == -1) {
            break;
        }/*from w w  w .j  a v  a 2s  .  c  o  m*/
        output.write(buffer);
    }
}

From source file:com.thoughtworks.go.agent.testhelper.FakeGoServer.java

private void start() throws Exception {
    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    server.addConnector(connector);//from w w w.  j  a  v a2 s  .  c  o  m

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setCertAlias("cruise");
    sslContextFactory.setKeyStoreResource(Resource.newClassPathResource("testdata/fake-server-keystore"));
    sslContextFactory.setKeyStorePassword("serverKeystorepa55w0rd");

    ServerConnector secureConnnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(new HttpConfiguration()));
    server.addConnector(secureConnnector);

    WebAppContext wac = new WebAppContext(".", "/go");
    ServletHolder holder = new ServletHolder();
    holder.setServlet(new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            resp.getOutputStream().println("Hello");
        }
    });
    wac.addServlet(holder, "/hello");
    addFakeAgentBinaryServlet(wac, "/admin/agent", TEST_AGENT, this);
    addFakeAgentBinaryServlet(wac, "/admin/agent-launcher.jar", TEST_AGENT_LAUNCHER, this);
    addFakeAgentBinaryServlet(wac, "/admin/agent-plugins.zip", TEST_AGENT_PLUGINS, this);
    addFakeAgentBinaryServlet(wac, "/admin/tfs-impl.jar", TEST_TFS_IMPL, this);
    addlatestAgentStatusCall(wac);
    addDefaultServlet(wac);
    server.setHandler(wac);
    server.setStopAtShutdown(true);
    server.start();

    port = connector.getLocalPort();
    securePort = secureConnnector.getLocalPort();
}

From source file:info.magnolia.cms.servlets.Spool.java

/**
 * @param resource File to be returned to the client
 * @param response HttpServletResponse/*from  w  w w. ja v a 2s  . c  o  m*/
 * @return <code>true</code> if the file has been written to the servlet output stream without errors
 * @throws IOException for error in accessing the resource or the servlet output stream
 */
private boolean spool(File resource, HttpServletResponse response) throws IOException {
    FileInputStream in = new FileInputStream(resource);

    try {
        ServletOutputStream os = response.getOutputStream();
        byte[] buffer = new byte[8192];
        int read = 0;
        while ((read = in.read(buffer)) > 0) {
            os.write(buffer, 0, read);
        }
        os.flush();
        IOUtils.closeQuietly(os);
    } catch (IOException e) {
        // only log at debug level, tomcat usually throws a ClientAbortException anytime the user stop loading the
        // page
        if (log.isDebugEnabled())
            log.debug("Unable to spool resource due to a " + e.getClass().getName() + " exception", e); //$NON-NLS-1$ //$NON-NLS-2$
        return false;
    } finally {
        IOUtils.closeQuietly(in);
    }
    return true;
}

From source file:nl.surfnet.coin.mock.MockHandler.java

private void respond(HttpServletResponse response, HttpServletRequest request) throws IOException {
    ServletOutputStream outputStream = response.getOutputStream();
    String requestURI = request.getRequestURI();
    InputStream inputStream = getResponseInputStream(requestURI);
    logger.debug("Received Http request ('" + requestURI + "')");
    if (request.getMethod().equals(HttpMethods.POST)) {
        logger.debug("Received POST request ('" + IOUtils.toString(request.getInputStream()) + "')");
    }/* w  w w  .j  a va  2s  . c  om*/
    if (status != 0) {
        response.setStatus(status);
        //reset
        status = 0;
    }
    IOUtils.copy(inputStream, outputStream);
    outputStream.flush();
}

From source file:org.ow2.proactive.workflow_catalog.rest.controller.WorkflowControllerTest.java

@Test
public void testGetWorkflowsAsArchive() throws IOException {
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletOutputStream sos = mock(ServletOutputStream.class);
    when(response.getOutputStream()).thenReturn(sos);
    List<Long> idList = new ArrayList<>();
    idList.add(0L);//  ww w  . j a va  2 s .  c  o m
    workflowController.get(1L, idList, Optional.of("zip"), response);
    verify(workflowService, times(1)).getWorkflowsAsArchive(1L, idList);
    verify(response, times(1)).setStatus(HttpServletResponse.SC_OK);
    verify(response, times(1)).setContentType("application/zip");
    verify(response, times(1)).addHeader(HttpHeaders.CONTENT_ENCODING, "binary");
    verify(response, times(1)).addHeader(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=\"archive.zip\"");
    verify(sos, times(1)).write(Mockito.any());
    verify(sos, times(1)).flush();
}