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:edu.umn.cs.spatialHadoop.nasa.ShahedServer.java

/**
 * Tries to load the given resource name frmo class path if it exists.
 * Used to serve static files such as HTML pages, images and JavaScript files.
 * @param target//from w ww .  j a  v a  2 s.  c  om
 * @param response
 * @throws IOException
 */
private void tryToLoadStaticResource(String target, HttpServletResponse response) throws IOException {
    LOG.info("Loading resource " + target);
    // Try to load this resource as a static page
    InputStream resource = getClass().getResourceAsStream("/webapps/static/shahedfrontend" + target);
    if (resource == null) {
        reportError(response, "Cannot load resource '" + target + "'", null);
        return;
    }
    byte[] buffer = new byte[1024 * 1024];
    ServletOutputStream outResponse = response.getOutputStream();
    int size;
    while ((size = resource.read(buffer)) != -1) {
        outResponse.write(buffer, 0, size);
    }
    resource.close();
    outResponse.close();
    response.setStatus(HttpServletResponse.SC_OK);
    if (target.endsWith(".js")) {
        response.setContentType("application/javascript");
    } else if (target.endsWith(".css")) {
        response.setContentType("text/css");
    } else {
        response.setContentType(URLConnection.guessContentTypeFromName(target));
    }
    final DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ZZZ");
    final long year = 1000L * 60 * 60 * 24 * 365;
    // Expires in a year
    response.addHeader("Expires", format.format(new Date().getTime() + year));
}

From source file:de.uni_koeln.spinfo.maalr.webapp.controller.EditorController.java

@RequestMapping("/editor/download/{fileName}.html")
public void export(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
    File dir = new File("exports");
    File file = new File(dir, fileName);
    ServletOutputStream out = response.getOutputStream();
    if (!file.exists()) {
        OutputStreamWriter writer = new OutputStreamWriter(out);
        writer.write("This link has expired. Please re-export the data and try again.");
        writer.flush();/*from   w ww. j  a  v  a 2  s  .c  om*/
        return;
    }
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    IOUtils.copy(in, out);
    in.close();
    out.close();
    file.delete();
}

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

@RequestMapping(value = "/query", method = RequestMethod.GET)
public String worksheet(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 ww .  j  a  v a2  s .  com
        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 show query worksheet");
    UserPref userPrefs = (UserPref) session.getAttribute("prefs");

    String action = request.getParameter("action");
    if (action != null) {

        CommandResult result = new CommandResult();
        ConnectionManager cm = ConnectionManager.getInstance();
        Connection conn = cm.getConnection(session.getId());

        if (action.trim().equals("commit")) {
            logger.debug("commit action requested");
            result = QueryUtil.runCommitOrRollback(conn, true, "N");
            addCommandToHistory(session, userPrefs, "commit");

            model.addAttribute("result", result);
        } else if (action.trim().equals("rollback")) {
            logger.debug("rollback action requested");
            result = QueryUtil.runCommitOrRollback(conn, false, "N");
            addCommandToHistory(session, userPrefs, "rollback");

            model.addAttribute("result", result);
        } else if (action.trim().equals("export")) {
            logger.debug("export data to CSV action requested");
            String query = request.getParameter("query");
            String exportDataCSV = QueryUtil.runQueryForCSV(conn, query);

            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment; filename=" + FILENAME_EXPORT);

            ServletOutputStream out = response.getOutputStream();
            out.println(exportDataCSV);
            out.close();
            return null;
        } else if (action.trim().equals("export_json")) {
            logger.debug("export data to JSON action requested");
            String query = request.getParameter("query");
            String exportDataJSON = QueryUtil.runQueryForJSON(conn, query);

            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment; filename=" + FILENAME_EXPORT_JSON);

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

    }

    // Create new QueryWindow and add to model
    // This is the formBackingObject
    model.addAttribute("queryAttribute", new QueryWindow());

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

From source file:com.exedio.cope.live.MediaServlet.java

void doRequest(final HttpServletRequest request, final HttpServletResponse response, final Anchor anchor) {
    final String featureID = request.getParameter(FEATURE);
    if (featureID == null)
        throw new NullPointerException();
    final Media feature = (Media) model.getFeature(featureID);
    if (feature == null)
        throw new NullPointerException(featureID);

    final String itemID = request.getParameter(ITEM);
    if (itemID == null)
        throw new NullPointerException();

    final Item item;
    try {//from w  w  w.  ja  v  a  2  s  .  c  o m
        startTransaction("media(" + featureID + ',' + itemID + ')');
        item = model.getItem(itemID);
        model.commit();
    } catch (final NoSuchIDException e) {
        throw new RuntimeException(e);
    } finally {
        model.rollbackIfNotCommitted();
    }

    final FileItem fi = anchor.getModification(feature, item);
    if (fi == null)
        throw new NullPointerException(featureID + '-' + itemID);
    response.setContentType(fi.getContentType());
    response.setContentLength((int) fi.getSize());

    InputStream in = null;
    ServletOutputStream out = null;
    try {
        in = fi.getInputStream();
        out = response.getOutputStream();

        final byte[] b = new byte[20 * 1024];
        for (int len = in.read(b); len >= 0; len = in.read(b))
            out.write(b, 0, len);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:au.org.ala.biocache.web.MapController.java

private void displayBlankImage(int width, int height, boolean useBase, HttpServletResponse response) {
    try {//  w  ww  .  jav  a  2  s.c  om
        response.setContentType("image/png");

        BufferedImage baseImage = null;
        if (useBase) {
            baseImage = createBaseMapImage();
        } else {
            baseImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(baseImage, "png", outputStream);
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(outputStream.toByteArray());
        outStream.flush();
        outStream.close();

    } catch (Exception e) {
        logger.error("Unable to write image", e);
    }
}

From source file:com.cisco.ca.cstg.pdi.utils.Util.java

/**
 * This method is used to download files from specified path
 * @param response//  w w w  .ja  v  a  2  s .  co  m
 * @param archiveFile
 */
public static void downloadArchiveFile(HttpServletResponse response, File archiveFile) {
    if (archiveFile.isFile()) {
        response.reset();
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + archiveFile.getName() + "\"");
        FileInputStream is = null;
        ServletOutputStream op = null;
        try {
            op = response.getOutputStream();
            double dLength = archiveFile.length();
            int iLength = 0;
            int num_read = 0;

            if (dLength >= Integer.MIN_VALUE && dLength <= Integer.MAX_VALUE) {
                iLength = (int) dLength;
            }
            byte[] arBytes = new byte[iLength];
            is = new FileInputStream(archiveFile);

            while (num_read < iLength) {
                int count = is.read(arBytes, num_read, iLength - num_read);
                if (count < 0) {
                    throw new IOException("end of stream reached");
                }
                num_read += count;
            }
            op.write(arBytes);
            op.flush();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
            if (null != op) {
                try {
                    op.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:au.org.ala.biocache.web.MapController.java

@RequestMapping(value = "/occurrences/legend", method = RequestMethod.GET)
public void pointLegendImage(
        @RequestParam(value = "colourby", required = false, defaultValue = "0") Integer colourby,
        @RequestParam(value = "width", required = false, defaultValue = "50") Integer widthObj,
        @RequestParam(value = "height", required = false, defaultValue = "50") Integer heightObj,
        HttpServletResponse response) {/*from w w w . java2 s  . c o m*/
    try {
        int width = widthObj.intValue();
        int height = heightObj.intValue();

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) img.getGraphics();

        if (colourby != null) {
            int colour = 0xFF000000 | colourby.intValue();
            Color c = new Color(colour);
            g.setPaint(c);

        } else {
            g.setPaint(Color.blue);
        }

        g.fillOval(0, 0, width, width);

        g.dispose();

        response.setContentType("image/png");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(img, "png", outputStream);
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(outputStream.toByteArray());
        outStream.flush();
        outStream.close();

    } catch (Exception e) {
        logger.error("Unable to write image", e);
    }
}

From source file:nu.mine.kino.jenkins.plugins.projectmanagement.ProjectSummaryAction.java

private void openFile(StaplerRequest req, StaplerResponse res, String filePath)
        throws FileNotFoundException, IOException {

    System.out.println(filePath);
    System.out.println(req.getContextPath());

    System.out.println(owner.getRootDir());
    File file = new File(owner.getRootDir(), filePath);
    FileInputStream in = null;/*  w  w  w. j  a  v  a  2  s .  c om*/
    ServletOutputStream out = res.getOutputStream();
    try {
        in = new FileInputStream(file);
        int i;
        while ((i = in.read()) != -1) {
            out.write(i);
        }
    } finally {
        out.close();
        in.close();
    }
}

From source file:edu.umn.cs.spatialHadoop.visualization.HadoopvizServer.java

/**
 * Tries to load the given resource name frmo class path if it exists. Used to
 * serve static files such as HTML pages, images and JavaScript files.
 * /* w ww. java  2  s  . c  om*/
 * @param target
 * @param response
 * @throws IOException
 */
private void tryToLoadStaticResource(String target, HttpServletResponse response) throws IOException {
    LOG.info("Loading resource " + target);
    // Try to load this resource as a static page
    InputStream resource = getClass().getResourceAsStream("/webapps/static/hadoopviz" + target);
    if (resource == null) {
        reportError(response, "Cannot load resource '" + target + "'", null);
        return;
    }
    byte[] buffer = new byte[1024 * 1024];
    ServletOutputStream outResponse = response.getOutputStream();
    int size;
    while ((size = resource.read(buffer)) != -1) {
        outResponse.write(buffer, 0, size);
    }
    resource.close();
    outResponse.close();
    response.setStatus(HttpServletResponse.SC_OK);
    if (target.endsWith(".js")) {
        response.setContentType("application/javascript");
    } else if (target.endsWith(".css")) {
        response.setContentType("text/css");
    } else {
        response.setContentType(URLConnection.guessContentTypeFromName(target));
    }
}

From source file:util.RelatorioUtil.java

public void criaRelatorio(List listas, String caminhorelatorio, String nomerelatorio)
        throws IOException, JRException {

    FacesContext fcontext = FacesContext.getCurrentInstance();
    ServletContext scontext = (ServletContext) fcontext.getExternalContext().getContext();

    String relJasper = scontext.getRealPath(caminhorelatorio);
    //InputStream inputStream = getClass().getResourceAsStream(relJasper);
    HttpServletResponse response = (HttpServletResponse) fcontext.getExternalContext().getResponse();
    ServletOutputStream responseStream = response.getOutputStream();
    JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(listas);

    Map parameters = new HashMap();
    response.setHeader("Content-Disposition", "inline; filename=" + nomerelatorio);
    response.setHeader("Cache-Control", "no-cache");
    response.setContentType("application/pdf");

    JasperPrint jasperPrint = JasperFillManager.fillReport(relJasper, parameters, ds);
    JasperExportManager.exportReportToPdfStream(jasperPrint, responseStream);
    byte x1[] = JasperExportManager.exportReportToPdf(jasperPrint);
    response.getOutputStream().write(x1);
    responseStream.flush();//from  w w  w .j a va 2s .c om
    responseStream.close();
    fcontext.renderResponse();
    fcontext.responseComplete();

}