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:com.thoughtworks.go.agent.testhelpers.FakeAgentCertificateServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ObjectOutputStream outputStream = null;
    try {//from   ww w .j a va 2  s .c  o m
        outputStream = new ObjectOutputStream(response.getOutputStream());
        outputStream.writeObject(AgentCertificateMother.agentCertificate());
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:com.github.dbourdette.glass.web.controller.FilesController.java

private void serveResource(String name, HttpServletResponse response) throws IOException {
    InputStream inputStream = getClass().getResourceAsStream(name);
    OutputStream outputStream = response.getOutputStream();

    byte[] buffer = new byte[BUFFER_SIZE];

    int size = 0;
    while ((size = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, size);
    }//from   w w w  .  j  av  a  2 s.  co m

    inputStream.close();
}

From source file:fi.okm.mpass.shibboleth.profile.impl.WriteMonitoringResultTest.java

@Test
public void testIOError() throws Exception {
    HttpServletResponse httpResponse = Mockito.mock(HttpServletResponse.class);
    Mockito.when(httpResponse.getOutputStream()).thenThrow(new IOException("mock"));
    action = new WriteMonitoringResult();
    action.setHttpServletResponse(httpResponse);
    action.initialize();/*  w w w  . j a v a2 s  .c om*/
    Event event = action.execute(src);
    Assert.assertEquals(event.getId(), EventIds.IO_ERROR);
}

From source file:com.webbfontaine.valuewebb.model.util.Utils.java

public static void sendBytes(byte[] bytes, String filename, String contentType) {
    if (bytes != null) {
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();

        response.setContentType(contentType);
        response.addHeader("Content-disposition", "attachment; filename=" + filename);
        response.addHeader("Content-Length", String.valueOf(bytes.length));
        ServletOutputStream os = null;//from ww  w.  j  av  a2s  .c  o  m
        try {
            os = response.getOutputStream();
            os.write(bytes);
            os.flush();
            FacesContext.getCurrentInstance().responseComplete();
        } catch (IOException e) {
            LOGGER.error("Sending content failed {0}", filename, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close stream after sending", e);
                }
            }
        }
    }
}

From source file:com.mycompany.thymeleafspringapp.controller.DealsController.java

@RequestMapping(value = "/deals/{dealid}/{imgid}", method = RequestMethod.GET)
public void getImage(@PathVariable(value = "imgid") long imgId, @PathVariable(value = "dealid") long dealId,
        HttpServletResponse response) throws IOException {
    Users user = getUserDetails();// ww  w  .ja v a 2  s. co m
    response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
    response.getOutputStream().write(ds.getScreenshotById(user.getUserId(), imgId));
    response.getOutputStream().close();
}

From source file:com.sharksharding.util.web.http.QueryViewServlet.java

/**
 * ?/*w  ww . ja va  2  s . co m*/
 * 
 * @author gaoxianglong
 * 
 * @param response
 *            http?
 * 
 * @param data
 *            ??
 * 
 * @throws IOException
 * 
 * @return void
 */
public void write(HttpServletResponse response, byte[] data) throws IOException {
    response.getOutputStream().write(data);
    response.getOutputStream().flush();
    response.getOutputStream().close();
}

From source file:net.sf.jsfcomp.chartcreator.ChartListener.java

private void writeChartWithServletResponse(HttpServletResponse response, JFreeChart chart, ChartData chartData)
        throws IOException {
    OutputStream stream = response.getOutputStream();
    response.setContentType(ChartUtils.resolveContentType(chartData.getOutput()));
    writeChart(stream, chart, chartData);
}

From source file:org.bedework.webcommon.location.FetchLocationsAction.java

protected void writeJson(final HttpServletResponse resp, final Object val) throws ServletException {
    try {//from   w w  w  . j av  a 2s  . com
        mapper.writeValue(resp.getOutputStream(), val);
    } catch (final Throwable t) {
        throw new ServletException(t);
    }
}

From source file:fr.ensimag.biblio.controllers.StatImg.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from   w  ww.  j  a v  a 2  s  .  c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    OutputStream out = response.getOutputStream();
    response.setContentType("image/png");
    //int val1 = 40;
    //int val2 = 60;
    try {
        DefaultPieDataset dataset = new DefaultPieDataset();
        String title = "Statistiques";
        boolean legend = true;

        Map<String, String[]> params = request.getParameterMap();
        for (Map.Entry<String, String[]> param : params.entrySet()) {
            String key = param.getKey();
            String[] value = param.getValue();
            System.out.println("key : " + key + "value : " + value[0]);
            if (key.equals("legend"))
                legend = Boolean.parseBoolean(value[0]);
            else
                dataset.setValue(key, Double.parseDouble(value[0]));
        }

        //dataset.setValue("Valeur 1", val1);
        //dataset.setValue("Valeur 2", val2);
        JFreeChart chart = ChartFactory.createPieChart(title, dataset, legend, false, false);
        chart.setBackgroundPaint(Color.WHITE);
        ChartUtilities.writeChartAsPNG(out, chart, 500, 300);
    } finally {
        out.close();
    }
}

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

@RequestMapping(method = RequestMethod.GET)
public void exportForm(@RequestParam(value = "id", required = true) Long formId,
        @RequestParam(value = "format", required = true) String format, HttpServletResponse response) {

    try {//from   w  w w.  j  a v  a  2 s.  c  om
        OutputStream oStream = response.getOutputStream();
        Cure cureXml = dataExporter.constructFormXML(formId);
        JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model");

        if (ExportFormat.XML.name().endsWith(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xml;", formId);
            response.setHeader("Content-Disposition", fileNameHeader);
            response.setContentType("application/xml");

            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(cureXml, oStream);
            oStream.flush();
        } else if (ExportFormat.EXCEL.name().equals(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xlxml;", formId);
            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));
        }
    } 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);
    }
}