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.chos.transaction.passport.controller.CaptchaController.java

@RequestMapping(value = "/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
    BufferedImage bi = new BufferedImage(40, 18, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    String c = generate();//from  ww  w .j  a  va 2  s  . co m
    g.setColor(Color.white);
    g.fillRect(1, 1, 38, 16);

    g.setColor(generateColor());
    g.drawString(c, 4, 13);
    response.setContentType("image/jpeg");
    ServletOutputStream os = response.getOutputStream();
    //      os.write(b)
    //      ImageIO.createImageOutputStream(os);
    ImageIO.write(bi, "jpg", os);
    os.flush();
    os.close();
    request.getSession().setAttribute("captcha", c);
}

From source file:com.nkapps.billing.controllers.OverpaymentController.java

@RequestMapping(value = "/return-text-file", method = RequestMethod.POST)
public void returnTextFile(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String fileName;//www . ja va  2s .  co m
    String fileContent;
    Long issuerSerialNumber = authService.getCertificateInfo().getSerialNumber().longValue();
    String issuerIp = authService.getClientIp(request);

    if ("single".equals(request.getParameter("type"))) {
        fileName = "Vozvrat - "
                + new SimpleDateFormat("dd.MM.yyyy HH-mm-ss").format(Calendar.getInstance().getTime());

        String bankStatementId = request.getParameter("bankStatementId");
        fileContent = overpaymentService.singleReturnBankStatementText(bankStatementId, issuerSerialNumber,
                issuerIp);
    } else {
        fileName = "Vozvrati_v_den - " + request.getParameter("paymentDate");

        Date paymentDate = new SimpleDateFormat("dd.MM.yyyy").parse(request.getParameter("paymentDate"));
        fileContent = overpaymentService.allReturnBankStatementText(paymentDate, issuerSerialNumber, issuerIp);
    }

    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".txt\"");
    response.addHeader("Cache-Control", "max-age=1, must-revalidate");
    response.addHeader("Pragma", "no-cache");

    ServletOutputStream stream = response.getOutputStream();
    stream.write(fileContent.getBytes());
    stream.close();
}

From source file:tilt.handler.get.TiltImageHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws TiltException {
    try {/*from www.  jav  a 2  s . c o m*/
        imageType = ImageType.read(request.getParameter(Params.PICTYPE));
        docid = request.getParameter(Params.DOCID);
        pageid = request.getParameter(Params.PAGEID);
        url = request.getParameter(Params.URL);
        if ((docid != null && pageid != null) || url != null) {
            if (url == null || url.length() == 0)
                url = Utils.getUrl(request.getServerName(), docid, pageid);
            Picture p = PictureRegistry.get(url);
            if (p == null) {
                TextIndex text = null;
                PictureRegistry.prune();
                Double[][] coords = getCropRect(request.getServerName(), docid, pageid);
                Options opts = Options.get(request.getServerName(), docid);
                String imageUrl = Utils.getUrl(request.getServerName(), docid, pageid);
                String url = composeTextUrl(request, docid, pageid);
                String textParam = Utils.getFromUrl(url);
                if (textParam != null)
                    text = new TextIndex(textParam, "en_GB");
                InetAddress poster = getIPAddress(request);
                p = new Picture(opts, imageUrl, text, coords, poster);
            }
            byte[] pic = null;
            switch (imageType) {
            case load:
                p.load();
            case original:
                pic = p.getOrigData();
                break;
            case preflight:
                pic = p.getPreflightData();
                break;
            case greyscale:
                pic = p.getGreyscaleData();
                break;
            case twotone:
                pic = p.getTwoToneData();
                break;
            case cleaned:
                pic = p.getCleanedData();
                break;
            case reconstructed:
                pic = p.getReconstructedData();
                break;
            case baselines:
                pic = p.getBaselinesData();
                break;
            case words:
                pic = p.getWordsData();
                break;
            case link:
                pic = p.getGreyscaleData();
                break;
            }
            if (pic != null) {
                ByteArrayInputStream bis = new ByteArrayInputStream(pic);
                String mimeType = URLConnection.guessContentTypeFromStream(bis);
                response.setContentType(mimeType);
                ServletOutputStream sos = response.getOutputStream();
                sos.write(pic);
                sos.close();
            } else {
                response.getOutputStream().println("<p>image " + docid + " not found</p>");
            }
        } else
            response.getOutputStream().println("<p>please specify a docid and pageid, or a url</p>");
    } catch (Exception e) {
        throw new ImageException(e);
    }
}

From source file:net.bafeimao.umbrella.web.controller.CaptchaController.java

@RequestMapping("")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setDateHeader("Expires", 0);
    // Set standard HTTP/1.1 no-cache headers.
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    // Set standard HTTP/1.0 no-cache header.
    response.setHeader("Pragma", "no-cache");
    // return a jpeg
    response.setContentType("image/jpeg");
    // create the text for the image
    String capText = captchaProducer.createText();
    // store the text in the session
    request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    // create the image with the text
    BufferedImage bi = captchaProducer.createImage(capText);
    ServletOutputStream out = response.getOutputStream();
    // write the data out
    ImageIO.write(bi, "jpg", out);

    try {//from w  w w .j  a  v a2 s  .c  om
        out.flush();
    } finally {
        out.close();
    }

    return null;
}

From source file:com.ibm.watson.ta.retail.ImportHousingServlet.java

/**
 * Forward the request to the index.jsp file
 *
 * @param req the req//from w ww .ja va 2  s . com
 * @param resp the resp
 * @throws ServletException the servlet exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Override
protected void doGet(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    logger.info("forwarding...");

    req.setCharacterEncoding("UTF-8");
    try {
        String queryStr = req.getQueryString();
        String url = baseURL;
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();

        Request newReq = Request.Get(uri);
        newReq.addHeader("Authorization", "Basic c2ltcGx5cmV0czpzaW1wbHlyZXRz");
        logger.log(Level.SEVERE, "My custom log:" + queryStr);

        Executor executor = Executor.newInstance();
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:org.ow2.clif.jenkins.chart.AbstractChart.java

public void doPng(File rootDir, StaplerRequest req, StaplerResponse rsp) throws IOException {

    File imageFile = getImageFile(rootDir);

    try {/*w ww . ja  va2 s . c o m*/
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        rsp.setContentType("image/png");
        ServletOutputStream os = rsp.getOutputStream();
        ImageIO.write(bufferedImage, "PNG", os);
        os.close();
    } catch (Error e) {
        /* OpenJDK on ARM produces an error like this in case of headless error
             Caused by: java.lang.Error: Probable fatal error:No fonts found.
                   at sun.font.FontManager.getDefaultPhysicalFont(FontManager.java:1088)
                   at sun.font.FontManager.initialiseDeferredFont(FontManager.java:967)
                   at sun.font.CompositeFont.doDeferredInitialisation(CompositeFont.java:254)
                   at sun.font.CompositeFont.getSlotFont(CompositeFont.java:334)
                   at sun.font.CompositeStrike.getStrikeForSlot(CompositeStrike.java:77)
                   at sun.font.CompositeStrike.getFontMetrics(CompositeStrike.java:93)
                   at sun.font.Font2D.getFontMetrics(Font2D.java:387)
                   at java.awt.Font.defaultLineMetrics(Font.java:2082)
                   at java.awt.Font.getLineMetrics(Font.java:2152)
                   at org.jfree.chart.axis.NumberAxis.estimateMaximumTickLabelHeight(NumberAxis.java:974)
                   at org.jfree.chart.axis.NumberAxis.selectVerticalAutoTickUnit(NumberAxis.java:1104)
                   at org.jfree.chart.axis.NumberAxis.selectAutoTickUnit(NumberAxis.java:1048)
                   at org.jfree.chart.axis.NumberAxis.refreshTicksVertical(NumberAxis.java:1249)
                   at org.jfree.chart.axis.NumberAxis.refreshTicks(NumberAxis.java:1149)
                   at org.jfree.chart.axis.ValueAxis.reserveSpace(ValueAxis.java:788)
                   at org.jfree.chart.plot.CategoryPlot.calculateRangeAxisSpace(CategoryPlot.java:2650)
                   at org.jfree.chart.plot.CategoryPlot.calculateAxisSpace(CategoryPlot.java:2669)
                   at org.jfree.chart.plot.CategoryPlot.draw(CategoryPlot.java:2716)
                   at org.jfree.chart.JFreeChart.draw(JFreeChart.java:1222)
                   at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1396)
                   at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1376)
                   at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1361)
                   at hudson.util.ChartUtil.generateGraph(ChartUtil.java:116)
                   at hudson.util.ChartUtil.generateGraph(ChartUtil.java:99)
                   at hudson.tasks.test.AbstractTestResultAction.doPng(AbstractTestResultAction.java:196)
                   at hudson.tasks.test.TestResultProjectAction.doTrend(TestResultProjectAction.java:97)
                   ... 37 more
           */
        if (e.getMessage().contains("Probable fatal error:No fonts found")) {
            rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
            return;
        }
        throw e; // otherwise let the caller deal with it
    } catch (HeadlessException e) {
        // not available. send out error message
        rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
    }

}

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

@RequestMapping(value = "/lihatlaporan")
public String lihatLaporan(ModelMap model, HttpServletResponse response) {
    String tanggalAwal = request.getParameter("tanggalAwal").toUpperCase();
    String tanggalAkhir = request.getParameter("tanggalAkhir").toUpperCase();

    //        List<PersewaanStudioMusik> dataListByMonth = persewaanStudioMusik.getDataListByMonth(tanggalAwal, tanggalAkhir);
    //        //from   w  w w  .j  a v  a  2  s.  co m
    //        model.addAttribute("bulan", tanggalAwal);
    //        model.addAttribute("tahun", tanggalAkhir);
    //        model.addAttribute("dataListByMonth", dataListByMonth);

    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/laporan_pemasukan.jasper"));

    Map parameters = new HashMap();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("TANGGAL_AWAL", tanggalAwal);
    params.put("TANGGAL_AKHIR", tanggalAkhir);
    byte[] bytes = null;
    try {
        bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), params, conn);
    } catch (JRException ex) {
        Logger.getLogger(OperatorController.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(OperatorController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "halaman-cetakReport-owner";
}

From source file:mx.com.quadrum.contratos.controller.busquedas.MuestraPdf.java

@RequestMapping(value = "muestraPdf/{idContrato}", method = RequestMethod.GET)
public void muestraPdf(@PathVariable("idContrato") Integer idContrato, HttpSession session,
        HttpServletRequest request, HttpServletResponse response) {
    if (session.getAttribute(USUARIO) == null && session.getAttribute(CLIENTE) == null) {
        return;/*from  w w w.j  a va 2s  .  co m*/
    }
    Contrato contrato = contratoService.buscarPorId(idContrato);

    Usuario usuario = (Usuario) session.getAttribute(USUARIO);
    response.setContentType("application/pdf");

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    File pdf = new File(
            USUARIOS + usuario.getMail() + "\\" + contrato.getNombre() + "\\" + contrato.getNombre() + ".pdf");
    try {
        InputStream in = new FileInputStream(pdf);
        byte[] data = new byte[in.available()];
        in.read(data);
        javax.servlet.ServletOutputStream servletoutputstream = response.getOutputStream();

        servletoutputstream.write(data);
        servletoutputstream.flush();
        servletoutputstream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:mx.com.quadrum.contratos.controller.busquedas.MuestraPdf.java

@RequestMapping(value = "muestraPdf/{idContrato}/{idEmpleado}", method = RequestMethod.GET)
public void muestraPdf(@PathVariable("idContrato") Integer idContrato,
        @PathVariable("idEmpleado") Integer idEmpleado, HttpSession session, HttpServletRequest request,
        HttpServletResponse response) {/*from ww w  . j  a v  a  2 s. c o  m*/

    if (session.getAttribute(USUARIO) == null && session.getAttribute(CLIENTE) == null) {
        return;
    }
    Contrato contrato = contratoService.buscarPorId(idContrato);
    response.setContentType("application/pdf");

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    Usuario usuario = usuarioService.buscarPorId(idEmpleado);
    File pdf = new File(
            USUARIOS + usuario.getMail() + "\\" + contrato.getNombre() + "\\" + contrato.getNombre() + ".pdf");
    try {
        InputStream in = new FileInputStream(pdf);
        byte[] data = new byte[in.available()];
        in.read(data);
        javax.servlet.ServletOutputStream servletoutputstream = response.getOutputStream();

        servletoutputstream.write(data);
        servletoutputstream.flush();
        servletoutputstream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:isl.FIMS.utils.Utils.java

public static void downloadZip(ServletOutputStream outStream, File file) {
    DataInputStream in = null;//from w  w w .j a v  a 2  s .  c  om
    int BUFSIZE = 8192;

    try {
        byte[] byteBuffer = new byte[BUFSIZE];
        in = new DataInputStream(new FileInputStream(file));
        int bytesRead;
        while ((bytesRead = in.read(byteBuffer)) != -1) {
            outStream.write(byteBuffer, 0, bytesRead);
        }
        in.close();
        outStream.close();
    } catch (IOException ex) {
    } finally {
        try {
            in.close();
        } catch (IOException ex) {
        }
    }
}