Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

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  .j a v  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 ww  w  .  j av  a  2s .c om*/
    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:org.rhq.gui.content.ContentHTTPServlet.java

protected boolean writePackageVersionBits(HttpServletRequest request, HttpServletResponse response,
        PackageVersion pkgVer) {//from   w ww . j a  v a 2s  .c om
    //
    // Anaconda does a fetch with specific ranges so it can locate the header in a rpm.
    // Refer to anaconda source: yuminstall.py to see the details.
    // We will default to range values of [0 -> -1] which will allow non-range based fetches to work as usual
    //
    long startRange = getStartRange(request);
    long endRange = getEndRange(request);
    if (endRange < 0) {
        response.setContentType("application/x-rpm");
        response.setContentLength(pkgVer.getFileSize().intValue());
    } else {
        response.setContentType("application/octet-stream");
        log.debug("Range request: start = " + startRange + ", end = " + endRange);
        int contentLength = new Long(endRange).intValue() - new Long(startRange).intValue() + 1;
        log.debug("Setting contentLength = " + contentLength);
        response.setContentLength(contentLength);
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        String rangeHdr = "bytes=" + startRange + "-" + endRange + "/" + contentLength;
        response.setHeader("Content-Range", rangeHdr);
    }
    try {
        ServletOutputStream output = response.getOutputStream();
        contentSourceMgr.outputPackageVersionBits(pkgVer, output, startRange, endRange);
        output.flush();
        output.close();
    } catch (IllegalStateException e) {
        log.error(e);
        return false;
    } catch (IOException e) {
        log.error(e);
        return false;
    }
    return true;
}

From source file:com.seer.datacruncher.spring.ExtraCheckCustomCodeValidator.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String code = request.getParameter("value");
    String name = request.getParameter("name");
    String addReq = request.getParameter("addReq");

    //TODO: take the result message from "locale"
    String result = null;//w w  w. j  a v  a  2  s . c om
    ObjectMapper mapper = new ObjectMapper();
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();
    if (StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) {
        result = I18n.getMessage("error.extracheck.invaliddata");
    } else {
        name = name.trim();
        if (addReq.equalsIgnoreCase("true")) {
            ReadList list = checksTypeDao.findCustomCodeByName(name);
            if (list != null && CollectionUtils.isNotEmpty(list.getResults())) {
                result = I18n.getMessage("error.extracheck.name.alreadyexist");
                out.write(mapper.writeValueAsBytes(result));
                out.flush();
                out.close();
                return null;
            }
        }
        try {
            File sourceDir = new File(System.getProperty("java.io.tmpdir"), "DataCruncher/src");
            sourceDir.mkdirs();
            String classNamePack = name.replace('.', File.separatorChar);
            String srcFilePath = sourceDir + "" + File.separatorChar + classNamePack + ".java";
            File sourceFile = new File(srcFilePath);
            if (sourceFile.exists()) {
                sourceFile.delete();
            }
            FileUtils.writeStringToFile(new File(srcFilePath), code);
            DynamicClassLoader dynacode = DynamicClassLoader.getInstance();
            dynacode.addSourceDir(sourceDir);
            CustomCodeValidator customCodeValidator = (CustomCodeValidator) dynacode
                    .newProxyInstance(CustomCodeValidator.class, name);
            boolean isValid = false;
            if (customCodeValidator != null) {
                Class clazz = dynacode.getLoadedClass(name);
                if (clazz != null) {
                    Class[] interfaces = clazz.getInterfaces();
                    if (ArrayUtils.isNotEmpty(interfaces)) {
                        for (Class clz : interfaces) {
                            if ((clz.getName().equalsIgnoreCase(
                                    "com.seer.datacruncher.utils.validation.SingleValidation"))) {
                                isValid = true;
                            }
                        }
                    }
                }
            }
            if (isValid) {
                result = "Success";
            } else {
                result = I18n.getMessage("error.extracheck.wrongimpl");
            }
        } catch (Exception e) {
            result = "Failed. Reason:" + e.getMessage();
        }
    }
    out.write(mapper.writeValueAsBytes(result));
    out.flush();
    out.close();
    return null;
}

From source file:au.org.ala.layers.web.UserDataService.java

private void setImageBlank(HttpServletResponse response) {
    if (blankImageBytes == null && blankImageObject != null) {
        synchronized (blankImageObject) {
            if (blankImageBytes == null) {
                try {
                    RandomAccessFile raf = new RandomAccessFile(
                            UserDataService.class.getResource("/blank.png").getFile(), "r");
                    blankImageBytes = new byte[(int) raf.length()];
                    raf.read(blankImageBytes);
                    raf.close();//from w ww.ja va2s. co  m
                } catch (IOException e) {
                    logger.error("error reading default blank tile", e);
                }
            }
        }
    }
    if (blankImageObject != null) {
        response.setContentType("image/png");
        try {
            ServletOutputStream outStream = response.getOutputStream();
            outStream.write(blankImageBytes);
            outStream.flush();
            outStream.close();
        } catch (IOException e) {
            logger.error("error outputting blank tile", e);
        }
    }
}

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

@Test
public void testRenderMergedOutputModelJSONP() throws Exception {

    // TODO: Make this test more robust

    // Setup/* w  w  w  .j  ava 2s .  co 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/*w ww. ja va2s  .  c  o m*/
 */
@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// w  ww.  ja va  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);
}

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

@Test
public void testRenderMergedOutputModelBeanCustomBeanJsogFactory() throws Exception {

    // Setup/* w  w w . j a  va 2 s. c  o  m*/
    String encoding = "ISO-8859-1"; // Default encoding
    JSOG beanJsog = JSOG.object("foo", "foovalue").put("bar", "barvalue");
    JSOG expected = JSOG.object("bean", beanJsog);
    MediaType contentType = MediaType.APPLICATION_JSON;

    BeanJsogFactory bjf = createMock(BeanJsogFactory.class);
    instance.setBeanJsogFactory(bjf);

    expect(bjf.create(isA(TestBean.class))).andReturn(beanJsog);

    // 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, bjf);

    instance.renderMergedOutputModel(model, request, response);

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

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

From source file:com.openkm.servlet.frontend.DownloadServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("service({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String path = request.getParameter("path");
    String uuid = request.getParameter("uuid");
    String[] uuidList = request.getParameterValues("uuidList");
    String[] pathList = request.getParameterValues("pathList");
    String checkout = request.getParameter("checkout");
    String ver = request.getParameter("ver");
    boolean export = request.getParameter("export") != null;
    boolean inline = request.getParameter("inline") != null;
    File tmp = File.createTempFile("okm", ".tmp");
    InputStream is = null;//from  w  ww. j ava 2s. c  o  m
    updateSessionManager(request);

    try {
        // Now an document can be located by UUID
        if (uuid != null && !uuid.equals("")) {
            uuid = FormatUtil.sanitizeInput(uuid);
            path = OKMRepository.getInstance().getNodePath(null, uuid);
        } else if (path != null) {
            path = FormatUtil.sanitizeInput(path);
            path = new String(path.getBytes("ISO-8859-1"), "UTF-8");
        }

        if (export) {
            if (exportZip) {
                FileOutputStream os = new FileOutputStream(tmp);
                String fileName = "export.zip";

                if (path != null) {
                    exportFolderAsZip(path, os);
                    fileName = PathUtils.getName(path) + ".zip";
                } else if (uuidList != null || pathList != null) {
                    // Export into a zip file multiple documents
                    List<String> paths = new ArrayList<String>();

                    if (uuidList != null) {
                        for (String uuidElto : uuidList) {
                            String foo = new String(uuidElto.getBytes("ISO-8859-1"), "UTF-8");
                            paths.add(OKMRepository.getInstance().getNodePath(null, foo));
                        }
                    } else if (pathList != null) {
                        for (String pathElto : pathList) {
                            String foo = new String(pathElto.getBytes("ISO-8859-1"), "UTF-8");
                            paths.add(foo);
                        }
                    }

                    fileName = PathUtils.getName(PathUtils.getParent(paths.get(0)));
                    exportDocumentsAsZip(paths, os, fileName);
                    fileName += ".zip";
                }

                os.flush();
                os.close();
                is = new FileInputStream(tmp);

                // Send document
                WebUtils.sendFile(request, response, fileName, MimeTypeConfig.MIME_ZIP, inline, is);
            } else if (exportJar) {
                // Get document
                FileOutputStream os = new FileOutputStream(tmp);
                exportFolderAsJar(path, os);
                os.flush();
                os.close();
                is = new FileInputStream(tmp);

                // Send document
                String fileName = PathUtils.getName(path) + ".jar";
                WebUtils.sendFile(request, response, fileName, "application/x-java-archive", inline, is);
            }
        } else {
            if (OKMDocument.getInstance().isValid(null, path)) {
                // Get document
                Document doc = OKMDocument.getInstance().getProperties(null, path);

                if (ver != null && !ver.equals("")) {
                    is = OKMDocument.getInstance().getContentByVersion(null, path, ver);
                } else {
                    is = OKMDocument.getInstance().getContent(null, path, checkout != null);
                }

                // Send document
                String fileName = PathUtils.getName(doc.getPath());
                WebUtils.sendFile(request, response, fileName, doc.getMimeType(), inline, is);
            } else if (OKMMail.getInstance().isValid(null, path)) {
                // Get mail
                Mail mail = OKMMail.getInstance().getProperties(null, path);

                // Send mail
                ServletOutputStream sos = response.getOutputStream();
                String fileName = PathUtils.getName(mail.getSubject() + ".eml");
                WebUtils.prepareSendFile(request, response, fileName, MimeTypeConfig.MIME_EML, inline);
                response.setContentLength((int) mail.getSize());
                MimeMessage m = MailUtils.create(null, mail);
                m.writeTo(sos);
                sos.flush();
                sos.close();
            }
        }
    } catch (PathNotFoundException e) {
        log.warn(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_PathNotFound),
                e.getMessage()));
    } catch (RepositoryException e) {
        log.warn(e.getMessage(), e);
        throw new ServletException(
                new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Repository),
                        e.getMessage()));
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_IO), e.getMessage()));
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Database), e.getMessage()));
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ServletException(new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_General), e.getMessage()));
    } finally {
        IOUtils.closeQuietly(is);
        FileUtils.deleteQuietly(tmp);
    }

    log.debug("service: void");
}