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:pivotal.au.se.gemfirexdweb.controller.CreateAsyncController.java

@RequestMapping(value = "/createasync", method = RequestMethod.POST)
public String createAsyncAction(@ModelAttribute("asyncAttribute") NewAsync asyncAttribute, 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.ja  va  2  s. c  o 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 Async Event Listener");

    DiskStoreDAO dsDAO = GemFireXDWebDAOFactory.getDiskStoreDAO();

    List<DiskStore> dsks = dsDAO.retrieveDiskStoreForCreateList((String) session.getAttribute("user_key"));

    model.addAttribute("diskstores", dsks);

    String asyncName = asyncAttribute.getAsyncName();
    String listenerClass = asyncAttribute.getListenerClass();

    logger.debug("New Async Event Listener Name = " + asyncName);
    logger.debug("New Async Event Listener Class = " + listenerClass);

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

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

        createAsync.append("CREATE ASYNCEVENTLISTENER " + asyncName + " (\n");
        createAsync.append("LISTENERCLASS '" + listenerClass + "' \n");

        if (!checkIfParameterEmpty(request, "initParams")) {
            createAsync.append("INITPARAMS " + asyncAttribute.getInitParams() + " \n");
        } else {
            createAsync.append("INITPARAMS '' \n");
        }

        if (!checkIfParameterEmpty(request, "manualStart")) {
            createAsync.append("MANUALSTART " + asyncAttribute.getManualStart() + " \n");
        }

        if (!checkIfParameterEmpty(request, "enableBatchConflation")) {
            createAsync.append("ENABLEBATCHCONFLATION " + asyncAttribute.getEnableBatchConflation() + " \n");
        }

        if (!checkIfParameterEmpty(request, "batchSize")) {
            createAsync.append("BATCHSIZE " + asyncAttribute.getBatchSize() + " \n");
        }

        if (!checkIfParameterEmpty(request, "batchTimeInterval")) {
            createAsync.append("BATCHTIMEINTERVAL " + asyncAttribute.getBatchTimeInterval() + " \n");
        }

        if (!checkIfParameterEmpty(request, "enablePersistence")) {
            createAsync.append("ENABLEPERSISTENCE " + asyncAttribute.getEnablePersistence() + " \n");
            if (asyncAttribute.getEnablePersistence().equals("TRUE")) {
                if (!checkIfParameterEmpty(request, "diskStore")) {
                    createAsync.append("DISKSTORENAME " + asyncAttribute.getDiskStore() + " \n");
                }
            }
        }

        if (!checkIfParameterEmpty(request, "maxQueueMemory")) {
            createAsync.append("MAXQUEUEMEMORY " + asyncAttribute.getMaxQueueMemory() + " \n");
        }

        if (!checkIfParameterEmpty(request, "alertThreshold")) {
            createAsync.append("ALERTTHRESHOLD " + asyncAttribute.getAlertThreshold() + " \n");
        }

        createAsync.append(") \n");

        if (!checkIfParameterEmpty(request, "serverGroups")) {
            createAsync.append("SERVER GROUPS (" + asyncAttribute.getServerGroups() + ") \n");
        }

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

            logger.debug("Creating async event listener as -> " + createAsync.toString());

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

            model.addAttribute("result", result);

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

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

    }

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

From source file:com.baidu.stqa.signet.web.common.exception.ExceptionResolver.java

@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) {
    Object errors = null;/*from  w  w  w  .j  a  v a2s .co m*/

    if (ex instanceof MethodArgumentNotValidException) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        errors = getDecorateErrors(ex);
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        errors = ex.getMessage();
        LOGGER.error(ex);
    }

    ObjectMapper mapper = new ObjectMapper();
    String errorJson = "Error occur when covert object to json!";
    try {
        errorJson = mapper.writeValueAsString(errors);
    } catch (Exception e) {
        e.printStackTrace();
    }

    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        outputStream.write(errorJson.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:uk.ac.ebi.fgpt.lode.servlet.ExplorerServlet.java

@RequestMapping(produces = "application/rdf+n3")
public @ResponseBody void describeResourceAsN3(@RequestParam(value = "uri", required = true) String uri,
        HttpServletResponse response) throws IOException, LodeException {
    if (uri != null && uri.length() > 0) {
        String query = "DESCRIBE <" + URI.create(uri) + ">";
        log.trace("querying for graph rdf+n3");
        response.setContentType("application/rdf+n3");
        ServletOutputStream out = response.getOutputStream();
        out.println();/*from w ww . j  a  va2  s.  co  m*/
        out.println();
        getSparqlService().query(query, "N3", false, out);
        out.close();
    } else {
        handleBadUriException(new Exception("Malformed or empty URI request: " + uri));
    }
}

From source file:uk.ac.ebi.fgpt.lode.servlet.ExplorerServlet.java

@RequestMapping(produces = "application/rdf+xml")
public @ResponseBody void describeResourceAsXml(@RequestParam(value = "uri", required = true) String uri,
        HttpServletResponse response) throws IOException, LodeException {
    if (uri != null && uri.length() > 0) {
        String query = "DESCRIBE <" + URI.create(uri) + ">";
        response.setContentType("application/rdf+xml");
        ServletOutputStream out = response.getOutputStream();
        out.println();//  w  ww .ja v  a  2  s .  c  om
        out.println();
        getSparqlService().query(query, "RDF/XML", false, out);
        out.close();
    } else {

    }
}

From source file:uk.ac.ebi.fgpt.lode.servlet.ExplorerServlet.java

@RequestMapping(produces = "application/rdf+json")
public @ResponseBody void describeResourceAsJson(@RequestParam(value = "uri", required = true) String uri,
        HttpServletResponse response) throws IOException, LodeException {
    if (uri != null && uri.length() > 0) {
        String query = "DESCRIBE <" + URI.create(uri) + ">";
        log.trace("querying for graph rdf+n3");
        response.setContentType("application/rdf+json");
        ServletOutputStream out = response.getOutputStream();
        out.println();// w  w  w.jav a  2s .  co m
        out.println();
        getSparqlService().query(query, "JSON-LD", false, out);
        out.close();
    } else {
        handleBadUriException(new Exception("Malformed or empty URI request: " + uri));
    }
}

From source file:com.evolveum.midpoint.web.boot.StaticWebServlet.java

protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException, ServletException {
    String relativePath = request.getPathInfo();
    LOGGER.trace("Serving relative path {}", relativePath);

    String requestUri = request.getRequestURI();
    if (relativePath == null || relativePath.length() == 0 || "/".equals(relativePath)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri);
        return;/*from w ww  .jav  a  2  s.  c o  m*/
    }

    File file = new File(base, relativePath);
    if (!file.exists() || !file.isFile()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri);
        return;
    }

    String contentType = getServletContext().getMimeType(file.getName());
    if (contentType == null) {
        contentType = "application/octet-stream";
    }
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(file.length()));

    LOGGER.trace("Serving file {}", file.getPath());

    ServletOutputStream outputStream = response.getOutputStream();
    FileInputStream fileInputStream = new FileInputStream(file);

    try {
        IOUtils.copy(fileInputStream, outputStream);
    } catch (IOException e) {
        throw e;
    } finally {
        fileInputStream.close();
        outputStream.close();
    }

}

From source file:org.intermine.web.struts.FileDownloadAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    //        String path = "WEB-INF/lib/";
    //        String fileName = "intermine-webservice-client.jar";

    try {/* w ww  .  j ava 2s. c  o  m*/
        String path = request.getParameter("path");
        String fileName = request.getParameter("fileName");
        String mimeType = request.getParameter("mimeType");
        String mimeExtension = request.getParameter("mimeExtension");

        if (!fileIsPermitted(fileName)) {
            response.sendError(401);
            return null;
        }

        //          String contextPath = getServlet().getServletContext().getRealPath("/");
        //          String filePath = contextPath + path + fileName;
        //          File file = new File(filePath);
        //          FileOutputStream fos = new FileOutputStream(file);

        // Read the file into a input stream
        InputStream is = getServlet().getServletContext().getResourceAsStream(path + fileName);

        if (is == null) {
            response.sendError(404);
            return null;
        }

        // MIME type
        if (fileName.endsWith(mimeExtension)) {
            response.setContentType(mimeType);
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        }

        ServletOutputStream sos = response.getOutputStream();

        byte[] buff = new byte[2048];
        int bytesRead;

        while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {
            sos.write(buff, 0, bytesRead);
        }

        is.close();
        sos.close();
    } catch (Exception e) {
        e.printStackTrace();
        recordError(new ActionMessage("api.fileDownloadFailed"), request);
        return mapping.findForward("api");
    }

    return null;
}

From source file:org.efs.openreports.actions.ReportRunAction.java

public String execute() {
    ReportUser user = (ReportUser) ActionContext.getContext().getSession().get(ORStatics.REPORT_USER);

    Report report = (Report) ActionContext.getContext().getSession().get(ORStatics.REPORT);

    int exportType = Integer
            .parseInt((String) ActionContext.getContext().getSession().get(ORStatics.EXPORT_TYPE));

    Map reportParameters = getReportParameterMap(user, report, exportType);
    Map imagesMap = getImagesMap();

    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    // set headers to disable caching      
    response.setHeader("Pragma", "public");
    response.setHeader("Cache-Control", "max-age=0");

    ReportLog reportLog = new ReportLog(user, report, new Date());

    JRVirtualizer virtualizer = null;//w  w w  .j a va2  s  .c o  m

    try {
        if (exportType == ReportEngine.EXPORT_PDF) {
            // Handle "contype" request from Internet Explorer
            if ("contype".equals(request.getHeader("User-Agent"))) {
                response.setContentType("application/pdf");
                response.setContentLength(0);

                ServletOutputStream outputStream = response.getOutputStream();
                outputStream.close();

                return NONE;
            }
        }

        log.debug("Filling report: " + report.getName());

        reportLogProvider.insertReportLog(reportLog);

        if (report.isVirtualizationEnabled() && exportType != ReportEngine.EXPORT_IMAGE) {
            log.debug("Virtualization Enabled");
            virtualizer = new JRFileVirtualizer(2, directoryProvider.getTempDirectory());
            reportParameters.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
        }

        ReportEngineInput reportInput = new ReportEngineInput(report, reportParameters);
        reportInput.setExportType(exportType);
        reportInput.setImagesMap(imagesMap);

        // add any charts
        if (report.getReportChart() != null) {
            log.debug("Adding chart: " + report.getReportChart().getName());

            ChartReportEngine chartEngine = new ChartReportEngine(dataSourceProvider, directoryProvider,
                    propertiesProvider);

            ChartEngineOutput chartOutput = (ChartEngineOutput) chartEngine.generateReport(reportInput);

            reportParameters.put("ChartImage", chartOutput.getContent());
        }

        ReportEngineOutput reportOutput = null;
        JasperPrint jasperPrint = null;

        if (report.isJasperReport()) {
            JasperReportEngine jasperEngine = new JasperReportEngine(dataSourceProvider, directoryProvider,
                    propertiesProvider);

            jasperPrint = jasperEngine.fillReport(reportInput);

            log.debug("Report filled - " + report.getName() + " : size = " + jasperPrint.getPages().size());

            log.debug("Exporting report: " + report.getName());

            reportOutput = jasperEngine.exportReport(jasperPrint, exportType, report.getReportExportOption(),
                    imagesMap, false);
        } else {
            ReportEngine reportEngine = ReportEngineHelper.getReportEngine(report, dataSourceProvider,
                    directoryProvider, propertiesProvider);
            reportOutput = reportEngine.generateReport(reportInput);
        }

        response.setContentType(reportOutput.getContentType());

        if (exportType != ReportEngine.EXPORT_HTML && exportType != ReportEngine.EXPORT_IMAGE) {
            response.setHeader("Content-disposition", "inline; filename="
                    + StringUtils.deleteWhitespace(report.getName()) + reportOutput.getContentExtension());
        }

        if (exportType == ReportEngine.EXPORT_IMAGE) {
            if (jasperPrint != null) {
                ActionContext.getContext().getSession().put(ORStatics.JASPERPRINT, jasperPrint);
            }
        } else {
            byte[] content = reportOutput.getContent();

            response.setContentLength(content.length);

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

        reportLog.setEndTime(new Date());
        reportLog.setStatus(ReportLog.STATUS_SUCCESS);
        reportLogProvider.updateReportLog(reportLog);

        log.debug("Finished report: " + report.getName());
    } catch (Exception e) {
        if (e.getMessage() != null && e.getMessage().indexOf("Empty") > 0) {
            addActionError(LocalStrings.getString(LocalStrings.ERROR_REPORT_EMPTY));
            reportLog.setStatus(ReportLog.STATUS_EMPTY);
        } else {
            addActionError(e.getMessage());

            log.error(e.getMessage());

            reportLog.setMessage(e.getMessage());
            reportLog.setStatus(ReportLog.STATUS_FAILURE);
        }

        reportLog.setEndTime(new Date());

        try {
            reportLogProvider.updateReportLog(reportLog);
        } catch (Exception ex) {
            log.error("Unable to create ReportLog: " + ex.getMessage());
        }

        return ERROR;
    } finally {
        if (virtualizer != null) {
            reportParameters.remove(JRParameter.REPORT_VIRTUALIZER);
            virtualizer.cleanup();
        }
    }

    if (exportType == ReportEngine.EXPORT_IMAGE)
        return SUCCESS;

    return NONE;
}

From source file:de.mpg.escidoc.pubman.statistic_charts.StatisticChartServlet.java

public synchronized void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String numberOfMonthsString = request.getParameter(numberOfMonthsParameterName);
    if (numberOfMonthsString == null) {
        numberOfMonths = 12;/*from ww  w . j a v a2 s  .  c  o m*/
    } else {
        numberOfMonths = Integer.parseInt(numberOfMonthsString);
    }

    String lang = request.getParameter(languageParameterName);
    if (lang == null) {
        this.language = "en";
    } else {
        this.language = lang;
    }

    id = request.getParameter(idParameterName);
    type = request.getParameter(typeParameterName);

    try {

        CategoryDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset);
        BufferedImage img = chart.createBufferedImage(630, 250);
        byte[] image = new KeypointPNGEncoderAdapter().encode(img);

        response.setContentType(CONTENT_TYPE);
        ServletOutputStream out = response.getOutputStream();
        out.write(image);
        out.flush();
        out.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:UploadDownloadFile.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);//w  ww .  java 2  s.c o m
    System.out.println("--> doGet -->");
    String filePath;

    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }
    final String clientip = request.getRemoteAddr().replace(":", "_");
    filePath = "/Users/" + currentuser + "/GlassFish_Server/glassfish/domains/domain1/tmpfiles/Uploaded/"
            + clientip + "/";
    File file = new File(filePath + File.separator + fileName);

    System.out.println("download file = " + file);
    if (!file.exists()) {
        throw new ServletException("File doesn't exists on server.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while ((read = fis.read(bufferData)) != -1) {
        os.write(bufferData, 0, read);
    }
    os.flush();
    os.close();
    fis.close();
    System.out.println("File downloaded at client successfully");
}