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:org.obm.push.impl.ResponderImpl.java

@Override
public void sendResponseFile(String contentType, InputStream file) {
    Preconditions.checkNotNull(contentType);
    Preconditions.checkNotNull(file);/*from w  ww.j  av  a  2 s  . co  m*/

    logger.debug("response: send file");
    try {
        byte[] b = FileUtils.streamBytes(file, false);
        resp.setContentType(contentType);
        resp.setContentLength(b.length);
        ServletOutputStream out = resp.getOutputStream();
        out.write(b);
        out.flush();
        out.close();
        resp.setStatus(HttpServletResponse.SC_OK);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.denimgroup.threadfix.webapp.controller.DocumentController.java

@RequestMapping(value = "/{docId}/download", method = RequestMethod.POST)
public String downloadDocument(Model model, @PathVariable("orgId") Integer orgId,
        @PathVariable("appId") Integer appId, @PathVariable("docId") Integer docId, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, IOException {

    if (!permissionService.isAuthorized(Permission.READ_ACCESS, orgId, appId)) {
        return "403";
    }//from   w w w.j a  v a 2 s .co m

    Document document = null;
    if (docId != null) {
        document = documentService.loadDocument(docId);
    }

    if (document == null) {
        if (orgId != null && appId != null)
            return "redirect:/organizations/" + orgId + "/applications/" + appId + "/documents";
        else if (orgId != null)
            return "redirect:/organizations/" + orgId;
        else
            return "redirect:/";
    }
    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + document.getName() + "." + document.getType() + "\"");
    response.setContentType(document.getContentType());
    InputStream in = document.getFile().getBinaryStream();
    ServletOutputStream out = response.getOutputStream();
    IOUtils.copy(in, out);
    in.close();
    out.flush();
    out.close();

    return null;
}

From source file:com.denimgroup.threadfix.webapp.controller.DocumentController.java

@RequestMapping(value = "/{docId}/view", method = RequestMethod.GET)
public String detailDocument(Model model, @PathVariable("orgId") Integer orgId,
        @PathVariable("appId") Integer appId, @PathVariable("docId") Integer docId, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, IOException {

    if (!permissionService.isAuthorized(Permission.READ_ACCESS, orgId, appId)) {
        return "403";
    }//from  w  ww  .j av a2s .  co m

    Document document = null;
    if (docId != null) {
        document = documentService.loadDocument(docId);
    }

    if (document == null) {
        if (orgId != null && appId != null)
            return "redirect:/organizations/" + orgId + "/applications/" + appId + "/documents";
        else if (orgId != null)
            return "redirect:/organizations/" + orgId;
        else
            return "redirect:/";
    }

    String contentType = document.getContentType();
    //      if (contentType == null || contentType.contains("htm") || contentType.contains("js")) {
    //         contentType = "text/plain";
    //      }
    response.setContentType(contentType);
    if (contentType.equals(documentService.getContentTypeService().getDefaultType()) || contentType == null) {
        response.addHeader("Content-Disposition",
                "attachment; filename=\"" + document.getName() + "." + document.getType() + "\"");
        response.setContentType("application/octet-stream");
    }
    response.addHeader("X-Content-Type-Options", "nosniff");
    InputStream in = document.getFile().getBinaryStream();
    ServletOutputStream out = response.getOutputStream();
    IOUtils.copy(in, out);
    in.close();
    out.flush();
    out.close();

    return null;
}

From source file:pivotal.au.se.gemfirexdweb.controller.CreateDiskStoreController.java

@RequestMapping(value = "/creatediskstore", method = RequestMethod.POST)
public String createHDFSStoreAction(@ModelAttribute("diskStoreAttribute") NewDiskStore diskStoreAttribute,
        Model model, HttpServletResponse response, HttpServletRequest request, HttpSession session)
        throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {/* w w w .j a v  a2 s.  co m*/
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for create Disk Store");

    String diskStoreName = diskStoreAttribute.getDiskStoreName();

    logger.debug("New Disk Store Name = " + diskStoreName);

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");

    if (submit != null) {
        // build create HDFS Store SQL
        StringBuffer createDiskStore = new StringBuffer();

        createDiskStore.append("create DISKSTORE " + diskStoreName + " \n");

        if (!checkIfParameterEmpty(request, "maxLogSize")) {
            createDiskStore.append("MAXLOGSIZE " + diskStoreAttribute.getMaxLogSize() + " \n");
        }

        if (!checkIfParameterEmpty(request, "autoCompact")) {
            createDiskStore.append("AUTOCOMPACT " + diskStoreAttribute.getAutoCompact() + " \n");
        }

        if (!checkIfParameterEmpty(request, "allowForceCompaction")) {
            createDiskStore
                    .append("ALLOWFORCECOMPACTION " + diskStoreAttribute.getAllowForceCompaction() + " \n");
        }

        if (!checkIfParameterEmpty(request, "compactionThreshold")) {
            createDiskStore
                    .append("COMPACTIONTHRESHOLD " + diskStoreAttribute.getCompactionThreshold() + " \n");
        }

        if (!checkIfParameterEmpty(request, "timeInterval")) {
            createDiskStore.append("TIMEINTERVAL " + diskStoreAttribute.getTimeInterval() + " \n");
        }

        if (!checkIfParameterEmpty(request, "writeBufferSize")) {
            createDiskStore.append("WRITEBUFFERSIZE " + diskStoreAttribute.getWriteBufferSize() + " \n");
        }

        if (!checkIfParameterEmpty(request, "additionalParams")) {
            createDiskStore.append(diskStoreAttribute.getAdditionalParams());
        }

        if (submit.equalsIgnoreCase("create")) {
            Result result = new Result();

            logger.debug("Creating disk store as -> " + createDiskStore.toString());

            result = GemFireXDWebDAOUtil.runCommand(createDiskStore.toString(),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("result", result);

        } else if (submit.equalsIgnoreCase("Show SQL")) {
            logger.debug("Create Disk Store SQL as follows as -> " + createDiskStore.toString());
            model.addAttribute("sql", createDiskStore.toString());
        } else if (submit.equalsIgnoreCase("Save to File")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + String.format(FILENAME, diskStoreName));

            ServletOutputStream out = response.getOutputStream();
            out.println(createDiskStore.toString());
            out.close();
            return null;
        }

    }

    // This will resolve to /WEB-INF/jsp/create-diskstore.jsp
    return "create-diskstore";
}

From source file:pivotal.au.se.gemfirexdweb.controller.CreateSynonymController.java

@RequestMapping(value = "/createsynonym", method = RequestMethod.POST)
public String createSynonymAction(@ModelAttribute("synonymAttribute") NewSynonym synonymAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {//from w w w.j  a  v a2 s. co m
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for create synonym");

    String schema = synonymAttribute.getSchemaName().trim();

    if (schema.length() == 0) {
        schema = (String) session.getAttribute("schema");
    }

    logger.debug("New synonym name = " + synonymAttribute.getSynonymName());

    TableDAO tableDAO = GemFireXDWebDAOFactory.getTableDAO();
    ViewDAO viewDAO = GemFireXDWebDAOFactory.getViewDAO();

    List<View> views = viewDAO.retrieveViewList((String) session.getAttribute("schema"), null,
            (String) session.getAttribute("user_key"));

    model.addAttribute("views", views);

    List<Table> tbls = tableDAO.retrieveTableList((String) session.getAttribute("schema"), null,
            (String) session.getAttribute("user_key"), "ORDINARY");

    model.addAttribute("tables", tbls);

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");

    if (submit != null) {
        // build create HDFS Store SQL
        StringBuffer createSynonym = new StringBuffer();

        createSynonym.append("CREATE SYNONYM " + schema + "." + synonymAttribute.getSynonymName() + " \n");
        createSynonym.append("FOR " + synonymAttribute.getObjectName() + " \n");

        if (submit.equalsIgnoreCase("create")) {
            Result result = new Result();

            logger.debug("Creating synonym as -> " + createSynonym.toString());

            result = GemFireXDWebDAOUtil.runCommand(createSynonym.toString(),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("result", result);

        } else if (submit.equalsIgnoreCase("Show SQL")) {
            logger.debug("Create UDT (Type) SQL as follows as -> " + createSynonym.toString());
            model.addAttribute("sql", createSynonym.toString());
            model.addAttribute("objectName", request.getParameter("objectName"));
        } else if (submit.equalsIgnoreCase("Save to File")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + String.format(FILENAME, synonymAttribute.getSynonymName()));

            ServletOutputStream out = response.getOutputStream();
            out.println(createSynonym.toString());
            out.close();
            return null;
        }

    }

    // This will resolve to /WEB-INF/jsp/create-synonym.jsp
    return "create-synonym";
}

From source file:com.seer.datacruncher.profiler.spring.ProfilerLoadController.java

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

    HttpSession session = request.getSession();

    ObjectMapper mapper = new ObjectMapper();

    ServletOutputStream out;
    response.setContentType("application/text");
    out = response.getOutputStream();/* w  w w. j ava 2 s  .c o m*/

    out.write(mapper.writeValueAsBytes(session.getAttribute("tableNames")));
    out.flush();
    out.close();

    return null;
}

From source file:org.efs.openreports.actions.admin.ReportUploadAction.java

@Override
public String execute() {
    try {/*from   w  ww .j  a  v a2  s .  co  m*/
        if ("upload".equals(command)) {
            if (reportFile != null) {
                File destinationFile = new File(directoryProvider.getReportDirectory() + reportFileFileName);

                try {
                    if (destinationFile.exists()) {
                        int revisionCount = reportProvider.getReportTemplate(reportFileFileName)
                                .getRevisionCount();
                        File versionedFile = new File(directoryProvider.getReportDirectory()
                                + reportFileFileName + "." + revisionCount);
                        FileUtils.copyFile(destinationFile, versionedFile);
                    }

                    FileUtils.copyFile(reportFile, destinationFile);
                } catch (IOException ioe) {
                    addActionError(ioe.toString());
                    return SUCCESS;
                }
            } else {
                addActionError("Invalid File.");
            }
        }

        if ("download".equals(command)) {
            String templateFileName = revision;

            // if there is a revision at the end of the file name, strip it off
            if (StringUtils.countMatches(templateFileName, ".") > 1) {
                templateFileName = revision.substring(0, revision.lastIndexOf("."));
            }

            File templateFile = new File(directoryProvider.getReportDirectory() + revision);
            byte[] template = FileUtils.readFileToByteArray(templateFile);

            HttpServletResponse response = ServletActionContext.getResponse();
            response.setHeader("Content-disposition", "inline; filename=" + templateFileName);
            response.setContentType("application/octet-stream");
            response.setContentLength(template.length);

            ServletOutputStream out = response.getOutputStream();
            out.write(template, 0, template.length);
            out.flush();
            out.close();
        }

        if ("revert".equals(command)) {
            String templateFileName = revision.substring(0, revision.lastIndexOf("."));

            File revisionFile = new File(directoryProvider.getReportDirectory() + revision);
            File currentFile = new File(directoryProvider.getReportDirectory() + templateFileName);

            // create a new revision from the current version
            int revisionCount = reportProvider.getReportTemplate(templateFileName).getRevisionCount();
            File versionedFile = new File(
                    directoryProvider.getReportDirectory() + templateFileName + "." + revisionCount);
            FileUtils.copyFile(currentFile, versionedFile);

            // copy the selected revision to the current version
            FileUtils.copyFile(revisionFile, currentFile);
        }

        reportTemplates = reportProvider.getReportTemplates();
    } catch (Exception pe) {
        addActionError(pe.getMessage());
    }

    return SUCCESS;
}

From source file:com.seer.datacruncher.profiler.spring.ProfilerLoadController.java

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

    HttpSession session = request.getSession();

    ObjectMapper mapper = new ObjectMapper();

    ServletOutputStream out;
    response.setContentType("application/text");
    out = response.getOutputStream();//w  w  w  . j ava 2 s .c o  m

    out.write(mapper.writeValueAsBytes(session.getAttribute("columnNames")));
    out.flush();
    out.close();

    return null;
}

From source file:org.exoplatform.frameworks.jcr.command.web.DisplayResourceCommand.java

public boolean execute(Context context) throws Exception {
    GenericWebAppContext webCtx = (GenericWebAppContext) context;
    HttpServletResponse response = webCtx.getResponse();
    HttpServletRequest request = webCtx.getRequest();

    // standalone request?
    String servletPath = request.getPathInfo();
    boolean doClose = true;
    // or included?
    if (servletPath == null) {
        servletPath = (String) request.getAttribute("javax.servlet.include.path_info");
        if (servletPath != null)
            doClose = false;/*w ww  . j a v  a  2s .  c om*/
    }

    Node file = (Node) webCtx.getSession().getItem((String) context.get(pathKey));
    file.refresh(false);

    Node content = null;

    try {
        content = JCRCommandHelper.getNtResourceRecursively(file);
    } catch (ItemNotFoundException e) {
        // Patch for ver 1.0 back compatibility
        // as exo:image was not primary item
        if (file.isNodeType("exo:article")) {
            try {
                content = file.getNode("exo:image");
            } catch (PathNotFoundException e1) {
                throw e; // new ItemNotFoundException("No nt:resource node found at
                // "+file.getPath()+" nor primary items of nt:resource type
                // ");
            }
        } else {
            throw e; // new ItemNotFoundException("No nt:resource node found at
            // "+file.getPath()+" nor primary items of nt:resource type
            // ");
        }

    }

    // if(file.isNodeType("nt:file")) {
    // content = file.getNode("jcr:content");
    // } else if(file.isNodeType("exo:article")) {
    // content = file.getNode("exo:image");
    // } else
    // throw new Exception("Invalid node type, expected nt:file or exo:article,
    // have "+file.getPrimaryNodeType().getName()+" at "+file.getPath());

    Property data;
    try {
        data = content.getProperty("jcr:data");
    } catch (PathNotFoundException e) {
        throw new PathNotFoundException("No jcr:data node found at " + content.getPath());
    }

    String mime = content.getProperty("jcr:mimeType").getString();
    String encoding = content.hasProperty("jcr:encoding") ? content.getProperty("jcr:encoding").getString()
            : DEFAULT_ENCODING;

    MimeTypeResolver resolver = new MimeTypeResolver();
    String fileName = file.getName();
    String fileExt = "";
    if (fileName.lastIndexOf(".") > -1) {
        fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
        fileName = fileName.substring(0, fileName.lastIndexOf("."));
    }
    String mimeExt = resolver.getExtension(mime);
    if (fileExt == null || fileExt.length() == 0) {
        fileExt = mimeExt;
    }
    response.setContentType(mime + "; charset=" + encoding);
    String parameter = (String) context.get("cache-control-max-age");
    String cacheControl = parameter == null ? "" : "public, max-age=" + parameter;
    response.setHeader("Cache-Control: ", cacheControl);
    response.setHeader("Pragma: ", ""); // leave blank to avoid IE errors
    response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "." + fileExt + "\"");

    if (mime.startsWith("text")) {
        PrintWriter out = response.getWriter();
        out.write(data.getString());
        out.flush();
        if (doClose)
            out.close();
    } else {
        InputStream is = data.getStream();
        byte[] buf = new byte[is.available()];
        is.read(buf);
        ServletOutputStream os = response.getOutputStream();
        os.write(buf);
        os.flush();
        if (doClose)
            os.close();
    }

    return true;
}

From source file:nu.kelvin.jfileshare.servlets.FileDownloadServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, java.io.IOException {
    // By the time we get here, the fileauthfilter has done the sanity
    // checking and authentication already. We can jump right into
    // serving the file.
    Conf conf = (Conf) getServletContext().getAttribute("conf");
    FileItem file = (FileItem) req.getAttribute("file");
    File fileOnDisk = new File(conf.getPathStore() + "/" + file.getFid().toString());

    logger.info("Preparing to stream file");
    resp.setContentType(file.getType());
    String disposition = req.getServletPath().equals("/file/get")
            && "image".equals(file.getType().substring(0, 5)) ? "inline" : "attachment";
    resp.setHeader("Content-disposition", disposition + "; filename=\"" + file.getName() + "\"");
    resp.setHeader("Content-length", Long.toString(fileOnDisk.length()));

    FileInputStream instream = new FileInputStream(fileOnDisk);
    ServletOutputStream outstream = resp.getOutputStream();

    try {//  w w  w  .  j  a  va2  s  . c o m
        IOUtils.copyLarge(instream, outstream);
    } finally {
        if (instream != null) {
            instream.close();
        }
        if (outstream != null) {
            outstream.close();
        }
    }
    file.logDownload(ds, req.getRemoteAddr());
}