Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.hzc.framework.ssh.controller.WebUtil.java

/**
 * ?response//from  ww  w  .j ava2s.  c  o m
 * ???10mdownloadCall
 *
 * @param file
 * @throws IOException
 */
public static void download(File file, String fileName) throws RuntimeException {
    try {
        HttpServletResponse resp = ActionContext.getResp();
        resp.addHeader("Content-Disposition",
                "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
        //            resp.addHeader("Content-Length", "" + attachFile.length);
        //            resp.setContentType("application/octet-stream");
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(IOUtils.toByteArray(new FileInputStream(file)));
        outputStream.flush();
        //            outputStream.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.geminimobile.web.SearchController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException arg3) throws Exception {
    SearchCommand cmd = (SearchCommand) command;
    ModelAndView mav = new ModelAndView(getSuccessView());

    CDRDataAccess cdrAccess = new CDRDataAccess();

    Date toDate = SearchCommand.m_sdf.parse(cmd.getToDate());
    long maxTimestamp = toDate.getTime();

    Date fromDate = SearchCommand.m_sdf.parse(cmd.getFromDate());
    long minTimestamp = fromDate.getTime();

    String msisdn = cmd.getMsisdn();
    String action = cmd.getAction();
    Vector<CDREntry> cdrs;/*from  www. ja  v a  2  s  . com*/

    if (action.compareToIgnoreCase("downloadcsv") == 0) {

        if (msisdn != null && msisdn.length() > 0) {
            cdrs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), 100000); // 100,000 entries max
        } else {
            cdrs = cdrAccess.getCDRsByHour(minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(),
                    MAX_ENTRIES_PER_PAGE);
        }
        StringBuffer sb = new StringBuffer();

        // Write column headers 
        sb.append("Date/Time,Market,Type,MSISDN,MO IP address,MT IP Address,Sender Domain,Recipient Domain\n");

        for (CDREntry entry : cdrs) {
            sb.append(entry.getDisplayTimestamp() + "," + entry.getMarket() + "," + entry.getType() + ","
                    + entry.getMsisdn() + "," + entry.getMoIPAddress() + "," + entry.getMtIPAddress() + ","
                    + entry.getSenderDomain() + "," + entry.getRecipientDomain() + "\n");
        }

        String csvString = sb.toString();

        response.setBufferSize(sb.length());
        response.setContentLength(sb.length());
        response.setContentType("text/plain; charset=UTF-8");
        //response.setContentType( "text/csv" );
        //response.setContentType("application/ms-excel");
        //response.setHeader("Content-disposition", "attachment;filename=cdrResults.csv");
        response.setHeader("Content-Disposition", "attachment; filename=" + "cdrResults.csv" + ";");
        ServletOutputStream os = response.getOutputStream();

        os.write(csvString.getBytes());

        os.flush();
        os.close();

        return null;

    } else if (action.compareToIgnoreCase("graph") == 0) {
        cmd.setGraph(true);
        List<ChartSeries> chartData;
        if (msisdn != null && msisdn.length() > 0) {
            chartData = cdrAccess.getChartDataByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp,
                    cmd.getMarket(), cmd.getMessageType(), 100000);
        } else {
            chartData = cdrAccess.getChartDataByHour(minTimestamp, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), 100000);
        }

        request.getSession().setAttribute("chartData", chartData);

    } else if (action.compareToIgnoreCase("getmore") == 0) {
        cdrs = (Vector<CDREntry>) request.getSession().getAttribute("currentcdrs");
        int numCDRs = cdrs.size();
        CDREntry lastCDR = cdrs.get(numCDRs - 1);
        long lastCDRTime = Long.parseLong(lastCDR.getTimestamp());

        if (msisdn != null && msisdn.length() > 0) {
            Vector<CDREntry> moreCDRs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), lastCDRTime, maxTimestamp,
                    cmd.getMarket(), cmd.getMessageType(), MAX_ENTRIES_PER_PAGE);
            cdrs.addAll(moreCDRs);
        } else {
            Vector<CDREntry> moreCDRs = cdrAccess.getCDRsByHour(lastCDRTime, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), MAX_ENTRIES_PER_PAGE);
            cdrs.addAll(moreCDRs);
        }

        request.getSession().setAttribute("currentcdrs", cdrs);
        mav.addObject("cdrs", cdrs);
    } else {
        // Normal search            
        if (msisdn != null && msisdn.length() > 0) {
            cdrs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp, cmd.getMarket(),
                    cmd.getMessageType(), MAX_ENTRIES_PER_PAGE);
        } else {
            cdrs = cdrAccess.getCDRsByHour(minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(),
                    MAX_ENTRIES_PER_PAGE);
        }

        request.getSession().setAttribute("currentcdrs", cdrs);
        mav.addObject("cdrs", cdrs);
    }

    mav.addObject("searchCmd", cmd);

    List<Option> msgOptions = getMessageOptions();
    mav.addObject("msgTypes", msgOptions);
    List<Option> marketOptions = getMarketOptions();
    mav.addObject("marketTypes", marketOptions);

    return mav;
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphServlet.java

private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart charts[],
        Statistic[] stats, long starttime, long endtime, int width, int height) throws IOException {

    try {//from  www. ja  va 2 s . c om
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener(request));
        document.open();

        int index = 0;
        int chapIndex = 0;
        for (Statistic stat : stats) {

            String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
            String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - "
                    + JiveGlobals.formatDate(new Date(endtime));
            Paragraph paragraph = new Paragraph(serverName,
                    FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
            document.add(paragraph);
            paragraph = new Paragraph(dateName, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.PLAIN));
            document.add(paragraph);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);

            Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(),
                    FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD));

            document.add(chapterTitle);
            // total hack: no idea what tags people are going to use in the description
            // possibly recommend that we only use a <p> tag?
            String[] paragraphs = stat.getDescription().split("<p>");
            for (String s : paragraphs) {
                Paragraph p = new Paragraph(s);
                document.add(p);
            }
            document.add(Chunk.NEWLINE);

            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
            charts[index++].draw(graphs2D, rectangle2D);
            graphs2D.dispose();
            float x = (document.getPageSize().width() / 2) - (width / 2);
            contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height);
            document.newPage();
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage());

    }
}

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

/**
 * Create and POST a request to the Watson service
 *
 * @param req/* w  w w.ja v  a  2  s. c o m*/
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet response
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    try {
        String reqURI = req.getRequestURI();
        String endpoint = reqURI.substring(reqURI.lastIndexOf('/') + 1);
        String url = baseURL + "/v1/" + endpoint;
        // concatenate query params
        String queryStr = req.getQueryString();
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();
        logger.info("posting to " + url);

        Request newReq = Request.Post(uri);
        newReq.addHeader("Accept", "application/json");

        String metadata = req.getHeader("x-watson-metadata");
        if (metadata != null) {
            metadata += "client-ip:" + req.getRemoteAddr();
            newReq.addHeader("x-watson-metadata", metadata);
        }

        InputStreamEntity entity = new InputStreamEntity(req.getInputStream());
        newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON);

        Executor executor = this.buildExecutor(uri);
        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();

        logger.info("post done");
    } 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:cpabe.controladores.UploadDecriptacaoServlet.java

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

    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("O nome do arquivo no pode ser null ou vazio.");
    }//from ww w.  j a  va 2 s. co m
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    if (!file.exists()) {
        throw new ServletException("O arquivo desejado no existe no Servidor.");
    }
    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");
}

From source file:com.Uploader.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/* w w  w . j  a  va  2 s . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //  processRequest(request, response);
    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    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");
}

From source file:com.liferay.portal.servlet.ImageServlet.java

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    String path = req.getPathInfo();

    // The image id may be passed in as image_id, img_id, or i_id

    String imageId = ParamUtil.getString(req, "image_id");

    if (Validator.isNull(imageId)) {
        imageId = ParamUtil.getString(req, "img_id");

        if (Validator.isNull(imageId)) {
            imageId = ParamUtil.getString(req, "i_id");
        }/*w  w w  .jav  a2 s.  com*/
    }

    // Company Logo

    if (path.startsWith("/company_logo")) {
        if (ParamUtil.get(req, "png", false)) {
            imageId += ".png";

            res.setContentType("image/png");
        } else if (ParamUtil.get(req, "wbmp", false)) {
            imageId += ".wbmp";

            res.setContentType("image/vnd.wap.wbmp");
        }
    }

    // Image Gallery

    if (path.startsWith("/image_gallery")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".image_gallery.")) {

            imageId = _companyId + ".image_gallery." + imageId;

            if (ParamUtil.get(req, "small", false)) {
                imageId += ".small";
            } else {
                imageId += ".large";
            }
        }
    }

    // Journal Article

    if (path.startsWith("/journal/article")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".journal.article.")) {

            imageId = _companyId + ".journal.article." + imageId;

            String version = req.getParameter("version");

            if (Validator.isNotNull(version)) {
                imageId += "." + version;
            }
        }
    }

    // Journal Template

    if (path.startsWith("/journal/template")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".journal.template.")) {

            imageId = _companyId + ".journal.template." + imageId;
            imageId += ".small";
        }
    }

    // Shopping Item

    else if (path.startsWith("/shopping/item")) {
        if (!imageId.equals(StringPool.BLANK) && !imageId.startsWith(_companyId + ".shopping.item.")) {

            imageId = _companyId + ".shopping.item." + imageId;

            if (ParamUtil.get(req, "small", false)) {
                imageId += ".small";
            } else if (ParamUtil.get(req, "medium", false)) {
                imageId += ".medium";
            } else {
                imageId += ".large";
            }
        }
    }

    Image image = ImageLocalUtil.get(imageId);

    if (Validator.isNull(imageId)) {
        _log.error("Image id should never be null or empty, path is " + req.getPathInfo());
    }

    if (image == null) {
        _log.error("Image should never be null");
    } else {
        if (Validator.isNotNull(image.getType())) {
            res.setContentType("image/" + image.getType());
        }

        /*res.setHeader(
           "Cache-control", "max-age=" + Long.toString(Time.WEEK));*/

        try {
            if (!res.isCommitted()) {
                ServletOutputStream out = res.getOutputStream();

                out.write(image.getTextObj());
                out.flush();
            }
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }
    }
}

From source file:org.apache.nifi.remote.client.http.TestHttpClient.java

private static void respondWithJson(HttpServletResponse resp, Object entity, int statusCode)
        throws IOException {
    resp.setContentType("application/json");
    resp.setStatus(statusCode);//  ww w  . j a  va2 s  . co  m
    final ServletOutputStream out = resp.getOutputStream();
    new ObjectMapper().writer().writeValue(out, entity);
    out.flush();
}

From source file:edu.umd.cs.submitServer.servlets.RobotDownloadPassingSubmissions.java

/**
 * The doGet method of the servlet. <br>
 *
 *
 * @param request//from   w w  w. ja v a 2  s  .  co  m
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    File tempfile = null;
    FileOutputStream fileOutputStream = null;
    FileInputStream fis = null;
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    PrintWriter names = new PrintWriter(byteOutputStream);
    try {
        conn = getConnection();

        // get the project and all the student registrations
        Map<Integer, Submission> lastSubmissionMap = (Map<Integer, Submission>) request
                .getAttribute("lastSubmission");
        Map<Integer, Submission> bestSubmissionMap = (Map<Integer, Submission>) request
                .getAttribute("bestSubmissionMap");

        Project project = (Project) request.getAttribute("project");
        Set<StudentRegistration> registrationSet = (Set<StudentRegistration>) request
                .getAttribute("studentRegistrationSet");

        // write everything to a tempfile, then send the tempfile
        tempfile = File.createTempFile("temp", "zipfile");
        fileOutputStream = new FileOutputStream(tempfile);

        // zip aggregator
        ZipFileAggregator zipAggregator = new ZipFileAggregator(fileOutputStream);

        for (StudentRegistration registration : registrationSet) {
            @StudentRegistration.PK
            Integer studentRegistrationPK = registration.getStudentRegistrationPK();
            Submission submission = (Submission) lastSubmissionMap.get(studentRegistrationPK);
            if (!isOK(submission, conn)) {
                submission = (Submission) bestSubmissionMap.get(studentRegistrationPK);
                if (!isOK(submission, conn))
                    continue;
            }

            String status = "";
            if (registration.getInstructorLevel() != StudentRegistration.STUDENT_CAPABILITY_LEVEL)
                status = "*";
            String timestamp = submission.getFormattedSubmissionTimestamp();
            names.printf("%s,%s,%s,%s %s%n", registration.getClassAccount(), timestamp, status,
                    registration.getFirstname(), registration.getLastname());
            try {
                byte[] bytes = submission.downloadArchive(conn);
                zipAggregator.addFileFromBytes(registration.getClassAccount(),
                        submission.getSubmissionTimestamp().getTime(), bytes);
            } catch (ZipFileAggregator.BadInputZipFileException ignore) {
                // ignore, since students could submit things that aren't
                // zipfiles
                getSubmitServerServletLog().warn(ignore.getMessage(), ignore);
            }

        }
        names.close();
        try {
            zipAggregator.addPlainFileFromBytes("names.txt", byteOutputStream.toByteArray());
        } catch (BadInputZipFileException e) {
            throw new ServletException(e);
        }
        zipAggregator.close();

        // write the zipfile to the client
        response.setContentType("application/zip");
        response.setContentLength((int) tempfile.length());

        // take into account the inability of certain browsers to download
        // zipfiles
        String filename = "p" + project.getProjectNumber() + ".zip";
        Util.setAttachmentHeaders(response, filename);

        ServletOutputStream out = response.getOutputStream();
        fis = new FileInputStream(tempfile);

        IO.copyStream(fis, out);

        out.flush();
        out.close();
    } catch (SQLException e) {
        handleSQLException(e);
        throw new ServletException(e);
    } finally {
        releaseConnection(conn);
        if (tempfile != null && !tempfile.delete())
            getSubmitServerServletLog().warn("Unable to delete temporary file " + tempfile.getAbsolutePath());
        IOUtils.closeQuietly(fileOutputStream);
        IOUtils.closeQuietly(fis);
    }
}

From source file:org.magnum.dataup.VideoService.java

@RequestMapping(value = VideoSvcApi.VIDEO_DATA_PATH, method = RequestMethod.GET)
public HttpServletResponse getData(@PathVariable("id") long id, HttpServletResponse response) {
    Video v = videos.get(id);// www.  j a v  a 2s. com
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
    } catch (Exception e) {
        sendError(response, 500, "Internal error.");
    }
    try {
        vfm.copyVideoData(v, out);
        out.flush();
    } catch (Exception e) {
        sendError(response, 404, "Video data could not be found.");
    }
    return response;
}