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:de.sub.goobi.metadaten.FileManipulation.java

/**
 * Download file./*from www. j  a v a2s . com*/
 */
public void downloadFile() {
    URI downloadFile = null;

    int imageOrder = Integer.parseInt(imageSelection);
    DocStruct page = metadataBean.getDigitalDocument().getPhysicalDocStruct().getAllChildren().get(imageOrder);
    String imagename = page.getImageName();
    String filenamePrefix = imagename.substring(0, imagename.lastIndexOf("."));
    URI processSubTypeURI = serviceManager.getFileService().getProcessSubTypeURI(metadataBean.getProcess(),
            ProcessSubType.IMAGE, currentFolder);
    ArrayList<URI> filesInFolder = fileService.getSubUris(processSubTypeURI);
    for (URI currentFile : filesInFolder) {
        String currentFileName = fileService.getFileName(currentFile);
        String currentFileNamePrefix = currentFileName.substring(0, currentFileName.lastIndexOf("."));
        if (filenamePrefix.equals(currentFileNamePrefix)) {
            downloadFile = currentFile;
            break;
        }
    }

    if (downloadFile == null || !fileService.fileExist(downloadFile)) {
        List<String> paramList = new ArrayList<>();
        // paramList.add(metadataBean.getMyProzess().getTitel());
        paramList.add(filenamePrefix);
        paramList.add(currentFolder);
        Helper.setFehlerMeldung(Helper.getTranslation("MetsEditorMissingFile", paramList));
        return;
    }

    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        InputStream in = null;
        ServletOutputStream out = null;
        try {
            String fileName = fileService.getFileName(downloadFile);
            ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
            String contentType = servletContext.getMimeType(fileName);
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            in = fileService.read(downloadFile);
            out = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int length;
            while ((length = in.read(buffer)) != -1) {
                out.write(buffer, 0, length);
            }
            out.flush();
        } catch (IOException e) {
            logger.error("IOException while exporting run note", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }

        facesContext.responseComplete();
    }

}

From source file:eu.earthobservatory.org.StrabonEndpoint.QueryBean.java

/**
  * Processes the request made from the HTML visual interface of Strabon Endpoint.
  * //w  ww. ja  v a2 s.c  o  m
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
private void processVIEWRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RequestDispatcher dispatcher;

    // check whether Update submit button was fired
    String reqFuncionality = (request.getParameter("submit") == null) ? "" : request.getParameter("submit");

    if (reqFuncionality.equals("Update")) {
        // get the dispatcher for forwarding the rendering of the response
        dispatcher = request.getRequestDispatcher("/Update");
        dispatcher.forward(request, response);

    } else {
        String query = URLDecoder.decode(request.getParameter("query"), "UTF-8");
        String format = request.getParameter("format");
        String handle = request.getParameter("handle");
        String maxLimit = request.getParameter("maxLimit");

        // get stSPARQLQueryResultFormat from given format name
        TupleQueryResultFormat queryResultFormat = stSPARQLQueryResultFormat.valueOf(format);

        if (query == null || format == null || queryResultFormat == null) {
            dispatcher = request.getRequestDispatcher("query.jsp");
            request.setAttribute(ERROR, PARAM_ERROR);
            dispatcher.forward(request, response);

        } else {
            query = strabonWrapper.addLimit(query, maxLimit);
            if ("download".equals(handle)) { // download as attachment
                ServletOutputStream out = response.getOutputStream();

                response.setContentType(queryResultFormat.getDefaultMIMEType());
                response.setHeader("Content-Disposition", "attachment; filename=results."
                        + queryResultFormat.getDefaultFileExtension() + "; " + queryResultFormat.getCharset());

                try {
                    strabonWrapper.query(query, format, out);
                    response.setStatus(HttpServletResponse.SC_OK);

                } catch (Exception e) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    out.print(ResponseMessages.getXMLHeader());
                    out.print(ResponseMessages.getXMLException(e.getMessage()));
                    out.print(ResponseMessages.getXMLFooter());
                }

                out.flush();

            } else if (("map".equals(handle) || "map_local".equals(handle) || "timemap".equals(handle))
                    && (queryResultFormat == stSPARQLQueryResultFormat.KML
                            || queryResultFormat == stSPARQLQueryResultFormat.KMZ)) {
                // show map (only valid for KML/KMZ)

                // get dispatcher
                dispatcher = request.getRequestDispatcher("query.jsp");

                // re-assign handle
                request.setAttribute("handle", handle);

                SecureRandom random = new SecureRandom();
                String temp = new BigInteger(130, random).toString(32);

                // the temporary KML/KMZ file to create in the server
                String tempKMLFile = temp + "." + queryResultFormat.getDefaultFileExtension();
                ;

                try {
                    Date date = new Date();

                    // get the absolute path of the temporary directory
                    if (!request.getParameter("handle").toString().contains("timemap")) {
                        tempDirectory = appName + "-temp";

                        basePath = context.getRealPath("/") + "/../ROOT/" + tempDirectory + "/";
                        // fix the temporary directory for this web application

                        FileUtils.forceMkdir(new File(basePath));

                        @SuppressWarnings("unchecked")
                        Iterator<File> it = FileUtils.iterateFiles(new File(basePath), null, false);
                        while (it.hasNext()) {
                            File tbd = new File((it.next()).getAbsolutePath());
                            if (FileUtils.isFileOlder(new File(tbd.getAbsolutePath()), date.getTime())) {
                                FileUtils.forceDelete(new File(tbd.getAbsolutePath()));
                            }
                        }
                    } else { //timemap case
                        tempDirectory = "js/timemap";
                        basePath = context.getRealPath("/") + tempDirectory + "/";
                        // fix the temporary directory for this web application
                    }

                    // fix the temporary directory for this web application

                    // create temporary KML/KMZ file
                    File file = new File(basePath + tempKMLFile);
                    // if file does not exist, then create it
                    if (!file.exists()) {
                        file.createNewFile();
                    }

                    try {
                        // query and write the result in the temporary KML/KMZ file
                        FileOutputStream fos = new FileOutputStream(basePath + tempKMLFile);
                        strabonWrapper.query(query, format, fos);
                        fos.close();

                        if (request.getParameter("handle").toString().contains("timemap")) {
                            request.setAttribute("pathToKML", tempDirectory + "/" + tempKMLFile);
                        } else {
                            request.setAttribute("pathToKML",
                                    request.getScheme() + "://" + request.getServerName() + ":"
                                            + request.getServerPort() + "/" + tempDirectory + "/"
                                            + tempKMLFile);
                        }

                    } catch (MalformedQueryException e) {
                        logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage());
                        request.setAttribute(ERROR, e.getMessage());

                    } catch (Exception e) {
                        logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                        request.setAttribute(ERROR, e.getMessage());
                    }

                    dispatcher.forward(request, response);

                } catch (IOException e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                }

            } else { // "plain" is assumed as the default
                dispatcher = request.getRequestDispatcher("query.jsp");
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                try {
                    strabonWrapper.query(query, format, bos);
                    if (format.equals(Common.getHTMLFormat())) {
                        request.setAttribute(RESPONSE, bos.toString());
                    } else if (format.equals(Format.PIECHART.toString())
                            || format.equals(Format.AREACHART.toString())
                            || format.equals(Format.COLUMNCHART.toString())) {
                        request.setAttribute("format", "CHART");
                        request.setAttribute(RESPONSE, strabonWrapper.getgChartString());
                    }

                    else {
                        request.setAttribute(RESPONSE, StringEscapeUtils.escapeHtml(bos.toString()));
                    }

                } catch (MalformedQueryException e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage());
                    request.setAttribute(ERROR, e.getMessage());

                } catch (Exception e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                    request.setAttribute(ERROR, e.getMessage());

                } finally {
                    dispatcher.forward(request, response);
                }
            }
        }
    }
}

From source file:org.inbio.ait.web.ajax.controller.SpeciesController.java

/**
 * Return the XML with the results//from   ww w  .  j a v a2s. c o  m
 * @param request
 * @param response
 * @param species
 * @param matchesByPolygon
 * @return
 * @throws java.lang.Exception
 */
private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response,
        List<String> species, List<Node> matchesByPolygon) throws Exception {

    response.setCharacterEncoding("ISO-8859-1");
    response.setContentType("text/xml");
    ServletOutputStream out = response.getOutputStream();
    StringBuilder result = new StringBuilder();

    if (matchesByPolygon == null) { //If there is not geographical criteria
        result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response><speciesList>");
        for (String s : species) {
            result.append("<species>" + s + "</species>");
        }
        result.append("</speciesList><polygons></polygons></response>");
        out.println(result.toString());
    } else { //If there is gegraphical criteria
        result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>");
        result.append("<speciesList></speciesList>");
        result.append("<polygons>");
        for (Node node : matchesByPolygon) {

            result.append("<polygon>");
            result.append("<abs>" + node.getValue1() + "</abs>");
            result.append("<per>" + node.getValue2() + "</per>");
            for (String sp : node.getValue3()) {
                result.append("<sp>" + sp + "</sp>");
            }
            result.append("</polygon>");
        }
        result.append("</polygons></response>");
        out.println(result.toString());
    }

    out.flush();
    out.close();

    return null;
}

From source file:org.openlaszlo.servlets.HistoryServlet.java

private void doHelp(HttpServletRequest req, HttpServletResponse res, String xxx) {
    ServletOutputStream out = null;
    try {/* w  w w  . j av  a 2s  .  c o m*/
        out = res.getOutputStream();

        out.println("<!-- " + xxx + " -->");

        out.println("<help>");
        out.println("You must pass in an xml query parameter (?xml=...).  ");
        out.println("The following are valid xml values.");

        out.println("<xml description=\"Save message.\" >");
        out.println("<resultset>");
        out.println("<root dset=\"message\"><from name=\"aName\" />messageText</root>");
        out.println("</resultset>");
        out.println("</xml>");

        out.println("<xml description=\"Get message history.\" >");
        out.println("<resultset>");
        out.println("<root><history/></root>");
        out.println("</resultset>");
        out.println("</xml>");

        out.println("<xml description=\"LPS push of client disconnect.\" >");
        out.println("<resultset>");
        out.println("<root dset=\"__LPSUSERDISCONNECT\">username</root>");
        out.println("</resultset>");
        out.println("</xml>");

        out.println("</help>");
        out.flush();
    } catch (IOException e) {
        mLogger.info("IOException: " + e.getMessage());
    } finally {
        close(out);
    }
}

From source file:org.apache.wookie.WidgetAdminServlet.java

private void doDownload(HttpServletRequest req, HttpServletResponse resp, File f, String original_filename)
        throws IOException {
    int BUFSIZE = 1024;

    // File f = new File(filename);
    int length = 0;
    ServletOutputStream op = resp.getOutputStream();
    ServletContext context = getServletConfig().getServletContext();
    String mimetype = context.getMimeType(f.getAbsolutePath());

    ////from  w  w  w.  j  ava  2s . com
    // Set the response and go!
    //
    //
    resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
    resp.setContentLength((int) f.length());
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + original_filename + "\"");

    //
    // Stream to the requester.
    //
    byte[] bbuf = new byte[BUFSIZE];
    DataInputStream in = new DataInputStream(new FileInputStream(f));

    while ((in != null) && ((length = in.read(bbuf)) != -1)) {
        op.write(bbuf, 0, length);
    }

    in.close();
    op.flush();
    op.close();
}

From source file:org.etudes.tool.melete.BookmarkPage.java

/**
 * writes the text file to browser/*from w w  w  .  jav  a 2  s  . co  m*/
 *
 * @param file -
 *            text file to download
 * @throws Exception
 */
private void download(File file) throws Exception {
    FileInputStream fis = null;
    ServletOutputStream out = null;
    try {
        String disposition = "attachment; filename=\"" + file.getName() + "\"";
        fis = new FileInputStream(file);

        FacesContext cxt = FacesContext.getCurrentInstance();
        ExternalContext context = cxt.getExternalContext();
        HttpServletResponse response = (HttpServletResponse) context.getResponse();
        response.setContentType("application/text"); // application/text
        response.addHeader("Content-Disposition", disposition);
        // Contributed by Diego for ME-233
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "public, post-check=0, must-revalidate, pre-check=0");

        out = response.getOutputStream();

        int len;
        byte buf[] = new byte[102400];
        while ((len = fis.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        out.flush();
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e1) {
        }

        try {
            if (fis != null)
                fis.close();
        } catch (IOException e2) {
        }
    }
}

From source file:eu.earthobservatory.org.StrabonEndpoint.BrowseBean.java

/**
 * Processes the request made by a client of the endpoint that uses it as a
 * service.//from   w w w .  ja v a  2  s.c  o  m
 * 
 * @param request
 * @param response
 * @throws IOException
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ServletOutputStream out = response.getOutputStream();

    // get the stSPARQL Query Result format (we check only the Accept
    // header)
    stSPARQLQueryResultFormat format = stSPARQLQueryResultFormat.forMIMEType(request.getHeader("accept"));

    // get the query
    String query = request.getParameter("query");

    // check for required parameters
    if (format == null || query == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.print(ResponseMessages.getXMLHeader());
        out.print(ResponseMessages.getXMLException(PARAM_ERROR));
        out.print(ResponseMessages.getXMLFooter());

    } else {
        // decode the query
        query = URLDecoder.decode(request.getParameter("query"), "UTF-8");

        response.setContentType(format.getDefaultMIMEType());
        try {
            strabonWrapper.query(query, format.getName(), out);
            response.setStatus(HttpServletResponse.SC_OK);

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print(ResponseMessages.getXMLHeader());
            out.print(ResponseMessages.getXMLException(e.getMessage()));
            out.print(ResponseMessages.getXMLFooter());
        }
    }

    out.flush();
}

From source file:org.mskcc.pathdb.action.web_api.NeighborhoodMapRetriever.java

/**
 * Writes html code that constructs frameset for map/legend.
 *
 * @param response HttpServletResponse/*ww  w. j av a  2 s. c om*/
 * @throws IOException
 */
private void writeFramesetToResponse(HttpServletResponse response) throws IOException {

    log.info("NeighborhoodMapRetriever.writeFramesetToResponse");

    // set content type
    response.setContentType("text/html");
    CONTENT_TYPE_SET = true;
    ServletOutputStream stream = response.getOutputStream();

    // write out html to define frameset
    stream.println("<html>");
    stream.println("<head>");
    stream.println("<title>Neighborhood Map</title>");
    stream.println("</head>");
    stream.println("<frameset cols=\"60%,40%\">");
    stream.println("<frame src=\"webservice.do?" + ProtocolRequest.ARG_VERSION + "="
            + ProtocolConstantsVersion3.VERSION_3 + "&" + ProtocolRequest.ARG_COMMAND + "="
            + ProtocolConstantsVersion2.COMMAND_GET_NEIGHBORS + "&" + ProtocolRequest.ARG_QUERY + "="
            + Long.toString(PHYSICAL_ENTITY_RECORD_ID) + "&" + ProtocolRequest.ARG_DATA_SOURCE + "="
            + PROTOCOL_REQUEST.getDataSource() + "&" + ProtocolRequest.ARG_OUTPUT + "="
            + ProtocolConstantsVersion2.FORMAT_IMAGE_MAP + "\">");
    stream.println("<frame src=\"sif_legend.do\">");
    stream.println("</frameset>");
    stream.println("</html>");

    // outta here
    stream.flush();
    stream.close();
}

From source file:com.gae.ImageServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    MemoryFileItemFactory factory = new MemoryFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    //resp.setContentType("image/png");
    ServletOutputStream out = resp.getOutputStream();
    try {/*from   w  w w  .java 2 s.  co m*/
        List<FileItem> list = upload.parseRequest(req);
        for (FileItem item : list) {
            if (!(item.isFormField())) {
                String fileName = item.getName();

                //Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
                //BlobKey blobKey = blobs.get("myFile");                 

                if (fileName != null && !"".equals(fileName)) {
                    int size = (int) item.getSize();
                    byte[] data = new byte[size];
                    InputStream in = item.getInputStream();
                    in.read(data);
                    //ImagesService imagesService = ImagesServiceFactory.getImagesService(); 

                    /*
                    Image oldImage = ImagesServiceFactory.makeImage(data); 
                    Transform resize = ImagesServiceFactory.makeResize(180, 150); 
                    Image newImage = imagesService.applyTransform(resize, oldImage, OutputEncoding.PNG); 
                    byte[] newImageData = newImage.getImageData();
                    out.write(newImageData);
                    */
                    /*
                    Image image = ImagesServiceFactory.makeImage(data); 
                    byte[] ImageData = image.getImageData();
                    */
                    out.flush();
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:org.openmrs.module.pmtct.util.FileExporter.java

public void exportToCSVFile2(HttpServletRequest request, HttpServletResponse response, List<Object> patientList,
        String filename, String title) throws Exception {
    ServletOutputStream outputStream = null;
    try {/*from www .  ja  va 2s. com*/
        outputStream = response.getOutputStream();
        Patient p;
        PatientService ps = Context.getPatientService();

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println("" + title);
        outputStream.println("Number of Patients: " + patientList.size());
        outputStream.println();
        outputStream.println("No.,Identifier, Names, Gender, BirthDay, Enrollment Date");
        outputStream.println();

        int ids = 0;

        for (Object patient : patientList) {
            Object[] o = (Object[]) patient;
            p = ps.getPatient(Integer.parseInt(o[1].toString()));
            ids += 1;
            outputStream.println(
                    ids + "," + p.getActiveIdentifiers().get(0).getIdentifier() + "," + p.getPersonName() + ","
                            + p.getGender() + "," + sdf.format(p.getBirthdate()) + "," + o[4].toString());
        }

        outputStream.flush();
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}