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.wso2.adminui.AdminUIServletFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    try {/*from   w  w  w. j  ava2  s.co m*/

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if (contextRoot == null) {
            //Context root could be "" or some othervalue
            this.contextRoot = httpServletRequest.getContextPath();
        }

        String requestURI = httpServletRequest.getRequestURI();
        int indexOfDot = requestURI.lastIndexOf(".");
        boolean isFile = false;
        if (indexOfDot != -1) {
            isFile = requestURI.substring(indexOfDot).matches("\\.(.)*");
        }
        if (!isFile && requestURI.lastIndexOf("/") != requestURI.length() - 1) {
            requestURI += "/";
        }
        Map generatedPages = (Map) servletContext.getAttribute(AdminUIConstants.GENERATED_PAGES);
        if (requestURI.equals(contextRoot) || requestURI.equals(contextRoot + "/")) {
            response.setContentType("text/html");
            boolean enableConsole = ((Boolean) servletContext.getAttribute(AdminUIConstants.ENABLE_CONSOLE))
                    .booleanValue();
            if (!enableConsole) {
                ServletOutputStream out = response.getOutputStream();
                out.write(("<b>Management Console has been disabled.</b> "
                        + "Enable it in the server.xml and try again.").getBytes());
                ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_FORBIDDEN);
                out.flush();
                out.close();
                return;
            }
            String fileContents = (String) generatedPages.get("index.html");
            if (fileContents != null) {
                ServletOutputStream op = response.getOutputStream();
                response.setContentLength(fileContents.getBytes().length);
                op.write(fileContents.getBytes());
                return;
            }
        } else {
            String urlKey;
            if (contextRoot.equals("/")) {
                urlKey = requestURI.substring(contextRoot.length(), requestURI.length());
            } else {
                urlKey = requestURI.substring(1 + contextRoot.length(), requestURI.length());
            }

            if (generatedPages != null) {
                String fileContents = (String) generatedPages.get(urlKey);
                if (fileContents != null) {
                    ServletOutputStream op = response.getOutputStream();
                    response.setContentType("text/html");
                    response.setContentLength(fileContents.getBytes().length);
                    op.write(fileContents.getBytes());
                    return;
                }
            }

            /*
             || has been used to support any client who wants to access the "global_params.js"
             regardless of where they want to access.
            */
            if (urlKey.equals(GLOBAL_PARAMS_JS) || urlKey.indexOf(GLOBAL_PARAMS_JS) > -1) {
                initGlobalParams((HttpServletResponse) response);
                return;
            }
        }
    } catch (Exception e) {
        String msg = "Exception occurred while processing Request";
        log.error(msg, e);
        throw new ServletException(msg, e);
    }
    filterChain.doFilter(request, response);
}

From source file:com.hp.security.jauth.admin.controller.BaseController.java

@RequestMapping("getResource")
public void getResource(String path, HttpServletRequest request, HttpServletResponse response)
        throws IOException, TemplateException {
    if (null != path) {
        if (path.endsWith(".js")) {
            response.setContentType("text/js");
        } else if (path.endsWith(".css")) {
            response.setContentType("text/css");
        } else if (path.endsWith(".gif")) {
            response.setContentType("image/gif");
        } else if (path.endsWith(".jpg") || path.endsWith(".jpeg")) {
            response.setContentType("image/jpeg");
        } else if (path.endsWith(".png")) {
            response.setContentType("image/png");
        } else {/*from   w  ww. j ava  2  s  .  c  o  m*/
            response.setContentType("text/html");
        }
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resource = resolver.getResource("jauth/resources/" + path);
        ServletOutputStream out = response.getOutputStream();
        InputStream is = resource.getInputStream();
        int read = 0;
        byte[] buffer = new byte[8192];
        while ((read = is.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        out.flush();
        out.close();
    }
}

From source file:nz.net.orcon.kanban.controllers.XmlFileController.java

private void generateXml(HttpServletResponse response, String boardId, Collection<Card> cardList)
        throws Exception {
    String xmlFileName = boardId + "-" + Calendar.getInstance().getTime() + ".xml";
    HashMap<String, String> aliases = new HashMap<String, String>();
    aliases.put("Card", "nz.net.orcon.kanban.model.Card");
    xstreamMarshaller.setAliases(aliases);
    XStream xStream = xstreamMarshaller.getXStream();
    xStream.registerConverter(new CardConverter());

    StringBuffer xmlCards = new StringBuffer();
    xmlCards.append("<Cards> \n");
    for (Card card : cardList) {
        xmlCards.append(xStream.toXML(card));
        xmlCards.append("\n");
    }/*from w  w w  .  j a v  a 2 s .  com*/
    xmlCards.append("</Cards>");

    InputStream in = new ByteArrayInputStream(xmlCards.toString().getBytes("UTF-8"));
    ServletOutputStream out = response.getOutputStream();
    response.setContentLength(xmlCards.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + xmlFileName + "\"");

    byte[] outputByte = new byte[4096];
    //copy binary content to output stream
    while (in.read(outputByte, 0, 4096) != -1) {
        out.write(outputByte, 0, 4096);
    }
    in.close();
    out.flush();
    out.close();
}

From source file:com.rplt.studioMusik.controller.MemberController.java

@RequestMapping(value = "/cetakNota", method = RequestMethod.GET)
public String cetakNota(HttpServletResponse response) {
    //        Connection conn = DatabaseConnection.getmConnection();
    //            File reportFile = new File(application.getRealPath("Coba.jasper"));//your report_name.jasper file
    File reportFile = new File(
            servletConfig.getServletContext().getRealPath("/resources/report/nota_persewaan.jasper"));

    //        Map<String, Object> params = new HashMap<String, Object>();
    //        params.put("P_KODESEWA", request.getParameter("kodeSewa"));

    byte[] bytes = persewaanStudioMusik.cetakNota(request.getParameter("kodeSewa"), reportFile);
    //        /* w  w  w .  j av a2s  . c  o  m*/
    //        try {
    //            bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), params, conn);
    //        } catch (JRException ex) {
    //            Logger.getLogger(MemberController.class.getName()).log(Level.SEVERE, null, ex);
    //        }

    response.setContentType("application/pdf");
    response.setContentLength(bytes.length);

    try {
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(bytes, 0, bytes.length);
        outStream.flush();
        outStream.close();
    } catch (IOException ex) {
        Logger.getLogger(MemberController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "halaman-cetakNota-operator";
}

From source file:ostepu.cconfig.help.java

/**
 * der Aufruf des help-Befehls//from w w w. j a  v a2  s .c o m
 *
 * @param context  der Kontext des Servlet
 * @param request  die eingehende Anfrage
 * @param response das Antwortobjekt
 */
public static void request(ServletContext context, HttpServletRequest request, HttpServletResponse response) {
    String pathInfo = request.getPathInfo();

    if (pathInfo == null) {
        try {
            response.sendError(404);
        } catch (IOException ex) {
            Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
            response.setStatus(500);
        }
        return;
    }

    if (!"GET".equals(request.getMethod())) {
        try {
            response.sendError(404);
        } catch (IOException ex) {
            Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
            response.setStatus(500);
        }
        return;
    }

    ServletOutputStream out;
    try {
        out = response.getOutputStream();
    } catch (IOException ex) {
        Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
        response.setStatus(500);
        return;
    }

    String[] helpPath = pathInfo.split("/");
    String extension = FilenameUtils.getExtension(pathInfo);
    String language = helpPath[1];
    helpPath[helpPath.length - 1] = helpPath[helpPath.length - 1].substring(0,
            helpPath[helpPath.length - 1].length() - extension.length() - 1);
    helpPath = Arrays.copyOfRange(helpPath, 2, helpPath.length);

    Path helpFile = Paths.get(
            context.getRealPath("/data/help/" + String.join("_", helpPath) + "_" + language + "." + extension));

    try {
        if (Files.exists(helpFile)) {
            InputStream inp = new FileInputStream(helpFile.toFile());
            byte[] res = IOUtils.toByteArray(inp);
            inp.close();
            out.write(res);
            response.setStatus(200);
            response.setHeader("Content-Type", "charset=utf-8");
        } else {
            response.sendError(404);
        }
    } catch (IOException ex) {
        Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
        response.setStatus(500);
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(help.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.pf4j.demo.web.mbean.PluginsMBean.java

/**
 * Download./*from   w w  w  .j  av a 2  s. c om*/
 *
 * @param p the p
 * @param plugin the plugin
 * @return the string
 */
public String download(Person p, ExporterBase plugin) {

    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();

        out.write(plugin.export(p));
        response.setContentType(plugin.getContentType());
        response.addHeader("Content-Disposition", "attachment; filename=\"Person\"");
        out.flush();
    } catch (IOException e1) {
    }
    try {
        if (out != null) {
            out.close();
        }
        FacesContext.getCurrentInstance().responseComplete();
    } catch (IOException e) {

    }

    return "";
}

From source file:com.redoute.datamap.servlet.GenerateGraph.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w  w  .  j  a  v  a2 s  .  com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("image/png");
    ServletOutputStream os = response.getOutputStream();

    try {
        String stream = request.getParameter("stream");

        ApplicationContext appContext = WebApplicationContextUtils
                .getWebApplicationContext(this.getServletContext());
        IDatamapService datamapService = appContext.getBean(IDatamapService.class);

        BufferedImage graph = datamapService.dataImplementedByCriteria("stream", stream);

        ImageIO.write(graph, "png", os);
        os.close();

    } finally {
        os.close();
    }
}

From source file:it.jugpadova.controllers.EventController.java

@RequestMapping
public ModelAndView rss(HttpServletRequest req, HttpServletResponse res) throws Exception {
    try {//from www.j  a  v a 2s . c om
        EventSearch eventSearch = buildEventSearch(req);
        List<Event> events = eventBo.search(eventSearch);
        Channel channel = feedsBo.buildChannel(events, Utilities.getBaseUrl(req), buildChannelLink(req));
        // flush it in the res
        WireFeedOutput wfo = new WireFeedOutput();
        res.setHeader("Cache-Control", "no-store");
        res.setHeader("Pragma", "no-cache");
        res.setDateHeader("Expires", 0);
        res.setContentType("text/xml");
        res.setCharacterEncoding("UTF-8");
        ServletOutputStream resOutputStream = res.getOutputStream();
        wfo.output(channel, new OutputStreamWriter(resOutputStream, "UTF-8"));
        resOutputStream.flush();
        resOutputStream.close();
    } catch (Exception exception) {
        logger.error("Error producing RSS", exception);
        throw exception;
    }
    return null;
}

From source file:org.webguitoolkit.ui.util.export.PDFTableExport.java

public void writeTo(Table table, HttpServletResponse response) {

    TableExportOptions exportOptions = table.getExportOptions();

    try {//from   w w  w .  j a v a  2  s.  c  o m
        String filename = exportOptions.getFileName();
        if (StringUtils.isEmpty(filename)) {
            filename = StringUtils.isNotEmpty(table.getTitle()) ? table.getTitle() : "pdf";
        }

        response.setContentType("application/pdf");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + ".pdf\"");
        ServletOutputStream out = response.getOutputStream();
        try {
            writeTo(table, out);
        } catch (RuntimeException ex) {
            logger.error("Error writing table to stream!", ex);
            response.sendError(500, ex.getMessage());
        }
        out.close();
    } catch (IOException e) {
        logger.error("Error writing table to stream!", e);
    } finally {

    }
}