Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:mx.com.quadrum.contratos.controller.busquedas.DescargarArchivos.java

@ResponseBody
@RequestMapping(value = "descargarArchivos/{idContrato}", method = RequestMethod.GET)
public void descargarArchivos(@PathVariable("idContrato") Integer idContrato, HttpSession session,
        HttpServletRequest request, HttpServletResponse response) {
    if (session.getAttribute(USUARIO) == null && session.getAttribute(CLIENTE) == null) {
        return;/*from   w  w w  .j  a v a 2 s .  c  o m*/
    }

    response.setContentType("application/zip");
    Usuario usuario = (Usuario) session.getAttribute(USUARIO);
    Contrato contrato = contratoService.buscarPorId(idContrato);
    response.setHeader("Content-Disposition", "attachment; filename=\"" + contrato.getNombre() + ".zip\"");
    ServletOutputStream sos;
    String pathFiles = USUARIOS + usuario.getMail() + "/" + contrato.getNombre();

    try {
        ZipFile folder = new ZipFile(pathFiles + "/" + contrato.getNombre() + ".zip");

        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        folder.addFolder(pathFiles, parameters);
        sos = response.getOutputStream();
        File zipFile = new File(pathFiles + "/" + contrato.getNombre() + ".zip");
        sos.write(convierteArchivoToArregloBytes(zipFile));
        sos.flush();
        zipFile.delete();
    } catch (IOException ex) {
        Logger.getLogger(DescargarArchivos.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ZipException ex) {
        Logger.getLogger(DescargarArchivos.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:de.iteratec.iteraplan.presentation.responsegenerators.GraphicsResponseGenerator.java

/**
 * Transforms a report file into an appropriate HTTP response. This method is designed to work
 * independent from the actual graphics format. This detail is delegated to the abstract method
 * {@link #writeGraphics(GraphicExportBean, OutputStream)}. Child class response generators
 * must implement that method according to the format that they are responsible for. Additionally,
 * child class response generators must implement the abstract methods {@link #getContentType()}
 * and getContentDisposition(String,Content).
 * //from www.  java2 s  .  c o  m
 * This implementation first writes the diagram into a temporary file and then writes that file's
 * contents to the response. This detour is necessary to find out the length of the download and
 * set the Content-Length response header.
 * 
 * @param response
 *          HTTP Response where the report file shall be written to.
 * @param graphicsBean
 *          contains the generated diagram, regardless of the specific file format
 * @param reportType
 *          Specifies which diagram type is downloaded. Influences the suggested download filename
 * @param content
 *          Enum to influence the download's Content-Disposition
 */
public void generateResponse(HttpServletResponse response, GraphicExportBean graphicsBean,
        GraphicalReport reportType, Content content) {
    File tempFile = null;
    try {
        // Create a new temporary file
        tempFile = File.createTempFile(TEMPFILE_PREFIX + reportType.getType(), FILE_SUFFIX);

        FileOutputStream tempFileOStream = null;
        try {
            // now write the temporary file
            tempFileOStream = new FileOutputStream(tempFile);
            writeGraphics(graphicsBean, tempFileOStream);
            tempFileOStream.flush();
        } finally {
            IOUtils.closeQuietly(tempFileOStream);
        }

        prepareResponse(response, reportType, content, tempFile.length());
        ServletOutputStream servletOutputStream = response.getOutputStream();

        FileInputStream tempFileInStream = null;
        try {
            // read temp file back in and write it to Servlet response
            tempFileInStream = new FileInputStream(tempFile);
            IOUtils.copy(tempFileInStream, servletOutputStream);
            servletOutputStream.flush();

        } finally {
            IOUtils.closeQuietly(tempFileInStream);
        }

    } catch (Exception e) {
        if (hasBeenAborted(e)) {
            LOGGER.info(
                    "The download of the graphics document has been canceled by the user or has been aborted due to a network error.");
        } else {
            throw new IteraplanTechnicalException(IteraplanErrorMessages.GRAPHIC_GENERATION_FAILED, e);
        }

    } finally {
        // delete temporary file
        if (tempFile != null && !tempFile.delete()) {
            LOGGER.error("Couldn't delete temporary file {0}", tempFile.toString());
        }
    }
}

From source file:net.sf.jsog.spring.JsogViewTest.java

@Test
public void testRenderMergedOutputModelBean() throws Exception {

    // Setup//  w  ww .  ja  v a  2 s. c  om
    String encoding = "ISO-8859-1"; // Default encoding
    JSOG expected = JSOG.object("bean", JSOG.object().put("foo", "foovalue").put("bar", "barvalue"));
    MediaType contentType = MediaType.APPLICATION_JSON;

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("bean", new TestBean());

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter("callback")).andReturn(null);

    // Execution
    replay(request, response, sos);

    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    JSOG actual = JSOG.parse(new String(out.getValue(), encoding));
    assertEquals(actual, expected);
}

From source file:net.sf.jsog.spring.JsogViewTest.java

@Test
public void testRenderMergedOutputModelCustomContentType() throws Exception {

    // Setup/*from  w  w w  . j a  va 2s. c  o m*/
    String encoding = "ISO-8859-1"; // Default encoding
    JSOG expected = new JSOG("foobar");
    MediaType contentType = MediaType.TEXT_PLAIN;
    instance.setOutputContentType(contentType);

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("JSOG", expected);

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter("callback")).andReturn(null);

    // Execution
    replay(request, response, sos);

    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    JSOG actual = JSOG.parse(new String(out.getValue(), encoding));
    assertEquals(actual, expected);
}

From source file:net.sf.jsog.spring.JsogViewTest.java

@Test
public void testRenderMergedOutputModel() throws Exception {

    // TODO: Make this test more robust

    // Setup//ww w . ja  va  2s.c  o m
    String encoding = "ISO-8859-1"; // Default encoding
    JSOG expected = new JSOG("foobar");
    MediaType contentType = MediaType.APPLICATION_JSON;

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("JSOG", expected);

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter("callback")).andReturn(null);

    // Execution
    replay(request, response, sos);

    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    JSOG actual = JSOG.parse(new String(out.getValue(), encoding));
    assertEquals(actual, expected);
}

From source file:net.sf.jsog.spring.JsogViewTest.java

@Test
public void testRenderMergedOutputModelCustomEncodingString() throws Exception {

    // TODO: Make this test more robust

    // Setup/*from   ww  w.jav a2 s.c  o  m*/
    String encoding = "UTF-8";
    JSOG expected = new JSOG("foobar");
    MediaType contentType = MediaType.APPLICATION_JSON;

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("JSOG", expected);

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter("callback")).andReturn(null);

    // Execution
    replay(request, response, sos);
    instance.setEncoding(encoding);
    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    JSOG actual = JSOG.parse(new String(out.getValue(), encoding));
    assertEquals(actual, expected);
}

From source file:net.sf.jsog.spring.JsogViewTest.java

@Test
public void testRenderMergedOutputModelCustomEncodingCharset() throws Exception {

    // TODO: Make this test more robust

    // Setup/*from  w ww  .  j a v a 2 s  .  c  o  m*/
    String encoding = "UTF-8";
    JSOG expected = new JSOG("foobar");
    MediaType contentType = MediaType.APPLICATION_JSON;

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("JSOG", expected);

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter("callback")).andReturn(null);

    // Execution
    replay(request, response, sos);
    instance.setEncoding(Charset.forName(encoding));
    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    JSOG actual = JSOG.parse(new String(out.getValue(), encoding));
    assertEquals(actual, expected);
}

From source file:net.sf.jsog.spring.JsogViewTest.java

@Test
public void testRenderMergedOutputModelJSONP() throws Exception {

    // TODO: Make this test more robust

    // Setup//from w  ww.j  a  v  a 2s. c o  m
    String encoding = "ISO-8859-1"; // Default encoding
    String callback = "foo";
    JSOG expectedJson = new JSOG("foobar");
    String expected = callback + "(" + expectedJson + ")";
    MediaType contentType = MediaType.APPLICATION_JSON;

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("JSOG", expectedJson);

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter("callback")).andReturn(callback);

    // Execution
    replay(request, response, sos);

    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    String actual = new String(out.getValue(), encoding);
    assertEquals(actual, expected);
}

From source file:net.sf.jsog.spring.JsogViewTest.java

/**
 * This tests that complex models can be rendered properly.
 * A complex model is one that doesn't have "JSOG" as it's only key (excepting BindingResult values).
 * @throws Exception/*from  www .  j  a  v a  2 s.  c  om*/
 */
@Test
public void testRenderMergedOutputModelComplex() throws Exception {

    // TODO: Make this test more robust

    // Setup
    String encoding = "ISO-8859-1"; // Default encoding
    JSOG expected = JSOG.object("foo", "foovalue").put("bar", "barvalue").put("obj", JSOG.object());
    MediaType contentType = MediaType.APPLICATION_JSON;

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("foo", "foovalue");
    model.put("bar", "barvalue");
    model.put("obj", JSOG.object());

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter("callback")).andReturn(null);

    // Execution
    replay(request, response, sos);

    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    JSOG actual = JSOG.parse(new String(out.getValue(), encoding));
    assertEquals(actual, expected);
}

From source file:net.sf.jsog.spring.JsogViewTest.java

@Test
public void testRenderMergedOutputModelJSONPCustomCallback() throws Exception {

    // TODO: Make this test more robust

    // Setup/*from   w w w. ja  v  a  2 s  .c  om*/
    String encoding = "ISO-8859-1"; // Default encoding
    String callback = "foo";
    String callbackParamName = "bar";
    JSOG expectedJson = new JSOG("foobar");
    String expected = callback + "(" + expectedJson + ")";
    MediaType contentType = MediaType.APPLICATION_JSON;

    // Setup the model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("JSOG", expectedJson);

    // Setup the output stream
    ServletOutputStream sos = createMock(ServletOutputStream.class);
    expect(response.getOutputStream()).andReturn(sos);

    Capture<byte[]> out = new Capture<byte[]>();
    sos.write(capture(out));
    expectLastCall();

    sos.flush();
    expectLastCall();

    sos.close();
    expectLastCall();

    response.setContentType(contentType.toString());
    expectLastCall();

    response.setCharacterEncoding(encoding);
    expectLastCall();

    response.setContentLength(expected.toString().getBytes(encoding).length);
    expectLastCall();

    expect(request.getParameter(callbackParamName)).andReturn(callback);

    // Execution
    replay(request, response, sos);

    instance.setJsonpCallbackParam(callbackParamName);
    instance.renderMergedOutputModel(model, request, response);

    // Verification
    verify(request, response, sos);
    assertTrue(out.hasCaptured());

    // Parse the resulting value
    String actual = new String(out.getValue(), encoding);
    assertEquals(actual, expected);
}