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:org.openmrs.module.vcttrac.util.FileExporter.java

/**
 * Auto generated method comment//from ww w  .java2 s  .co  m
 * 
 * @param request
 * @param response
 * @param patientList
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportToCSVFile(HttpServletRequest request, HttpServletResponse response,
        List<VCTClient> clientList, String filename, String title, String searchDescr) throws Exception {
    ServletOutputStream outputStream = null;

    try {
        outputStream = response.getOutputStream();
        //         Person p;

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println(VCTTracUtil.getMessage("vcttrac.export.title.bigtitle", null));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.export.report.title", null) + ", " + title);
        outputStream.println(
                VCTTracUtil.getMessage("vcttrac.export.report.description", null) + ", " + searchDescr);
        outputStream.println();
        outputStream.println(VCTTracUtil.getMessage("vcttrac.export.title.generatedby", null) + ", "
                + Context.getAuthenticatedUser().getPersonName());
        outputStream.println(VCTTracUtil.getMessage("vcttrac.export.title.generatedon", null) + ", "
                + (new SimpleDateFormat("dd-MMM-yyyy HH:mm").format(new Date())));
        outputStream.println(VCTTracUtil.getMessage("vcttrac.export.title.numberofclients", null) + ", "
                + clientList.size());
        outputStream.println();
        //         outputStream
        //                 .println("No., Names, Gender, BirthDay, Registration Date, Counseling Done ?, Got Rsultat ?, Result of HIV Test");
        setColumnTitles(outputStream);
        outputStream.println();

        int ids = 0;

        for (VCTClient client : clientList) {
            ids += 1;
            /*p = client.getClient();
            outputStream.println(ids
            + ","
            + p.getPersonName()
            + ","
            + p.getGender()
            + ","
            + df.format(p.getBirthdate())
            + ","
            + df.format(client.getDateOfRegistration())
            + ","
            + ((client.getCounselingObs() != null) ? "Yes" : "No")
            + ","
            + ((client.getResultObs() != null) ? "Yes" : "No")
            + ","
            + VCTModuleTag.convsetObsValueByConcept(client.getResultObs(), VCTTracUtil
                    .getResultOfHivTestConceptId()));*/

            displayRowValues(outputStream, client, ids);
        }

        outputStream.flush();
    } catch (Exception e) {
        log.error(">>VCT>>Export>>in>>CSV>>Format>> " + e.getMessage());
        e.printStackTrace();
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}

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

private void doSendHistory(HttpServletRequest req, HttpServletResponse res, Document doc) {
    mLogger.info("doSendHistory");
    Element el = doc.getRootElement().getChild("root").getChild("history");

    ServletOutputStream out = null;
    GetMethod request = null;//from   w w  w  . j av a 2  s . com
    String status = null;
    String body = null;
    try {
        out = res.getOutputStream();

        request = new MyGetMethod();

        String url = mURL + "?lzt=agentmessage" + "&url=" + URLEncoder.encode(mAgentURL) + "&group="
                + mAgentGroup + "&to=*&range=user" + "&dset=" + mClientDataset + "&msg="
                + URLEncoder.encode(getXMLHistory());

        mLogger.debug("url: " + url);
        URI uri = new URI(url.toCharArray());
        HostConfiguration hcfg = new HostConfiguration();
        hcfg.setHost(uri);

        String path = uri.getEscapedPath();
        String query = uri.getEscapedQuery();

        mLogger.debug("path: " + path);
        mLogger.debug("query: " + query);

        request.setPath(path);
        request.setQueryString(query);

        HttpClient htc = new HttpClient(mConnectionMgr);
        htc.setHostConfiguration(hcfg);
        int rc = htc.executeMethod(hcfg, request);

        status = HttpStatus.getStatusText(rc);
        if (status == null) {
            status = "" + rc;
        }
        mLogger.debug("remote response status: " + status);

        body = request.getResponseBodyAsString();

        mLogger.debug("response body: " + body);
    } catch (HttpRecoverableException e) {
        mLogger.debug("HttpRecoverableException: " + e.getMessage());
        sendError(out, "<status message=\"HttpRecoverableException " + e.getMessage() + "\" />");
    } catch (HttpException e) {
        mLogger.debug("HttpException: " + e.getMessage());
        sendError(out, "<status message=\"HttpException " + e.getMessage() + "\" />");
    } catch (IOException e) {
        mLogger.debug("IOException: " + e.getMessage());
        sendError(out, "<status message=\"IOException " + e.getMessage() + "\" />");
    } finally {
        if (request != null) {
            request.releaseConnection();
        }
    }

    try {
        if (status != null && status.equals("OK")) {
            out.println("<status message=\"ok\">" + (body != null ? body : "") + "</status>");
        } else {
            out.println("<status message=\"" + mURL + "?lzt=agentmessage" + " " + status + "\" />");
        }
        out.flush();
    } catch (IOException e) {
        mLogger.debug("Client IOException");
        // ignore client ioexception
    } finally {
        close(out);
    }
}

From source file:de.unigoettingen.sub.commons.contentlib.servlet.controller.GetImageAction.java

/************************************************************************************
 * exectute all image actions (rotation, scaling etc.) and send image back to output stream of the servlet, after setting correct mime type
 * /*from   ww w. ja v  a  2  s .co  m*/
 * @param request {@link HttpServletRequest} of ServletRequest
 * @param response {@link HttpServletResponse} for writing to response output stream
 * @throws IOException
 * @throws ImageInterpreterException 
 * @throws ServletException
 * @throws ContentLibException
 * @throws URISyntaxException
 * @throws ContentLibPdfException 
 ************************************************************************************/
@Override
public void run(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response)
        throws IOException, URISyntaxException, ContentLibException {
    long startTime = System.currentTimeMillis();

    super.run(servletContext, request, response);

    /*
     * -------------------------------- get central configuration --------------------------------
     */
    URI sourceImageUrl = null;
    ContentServerConfiguration config = ContentServerConfiguration.getInstance();
    if (!request.getParameter("sourcepath").startsWith("file:")
            && !request.getParameter("sourcepath").startsWith("http:")) {
        sourceImageUrl = new URI(config.getRepositoryPathImages() + request.getParameter("sourcepath"));
    } else {
        sourceImageUrl = new URI(request.getParameter("sourcepath"));
    }

    try {
        Cache cc = null;
        ServletOutputStream output = response.getOutputStream();
        if (request.getParameter("thumbnail") != null) {
            cc = ContentServer.getThumbnailCache();
        } else {
            cc = ContentServer.getContentCache();
        }
        // String myUniqueID = getContentCacheIdForRequest(request, config);
        String myUniqueID = getContentCacheIdForParamMap(request.getParameterMap(), config);
        String targetExtension = request.getParameter("format");

        boolean ignoreCache = false;
        /* check if cache should be ignored */
        if (request.getParameter("ignoreCache") != null) {
            String ignore = request.getParameter("ignoreCache").trim();
            ignoreCache = Boolean.parseBoolean(ignore);
        }
        boolean useCache = false;
        if (request.getParameter("thumbnail") != null) {
            useCache = config.getThumbnailCacheUse();
        } else {
            useCache = config.getContentCacheUse();
        }
        if (request.getParameterMap().containsKey("highlight")) {
            useCache = false;
        }
        if (cc == null || !useCache) {
            ignoreCache = true;
            cc = null;
            LOGGER.debug("cache deactivated via configuration");
        }

        if (!ignoreCache && cc.isKeyInCache(myUniqueID + "." + targetExtension)) {
            LOGGER.debug("get file from cache: " + myUniqueID + "." + targetExtension);
            CacheObject co;
            try {
                co = (CacheObject) cc.get(myUniqueID + "." + targetExtension).getObjectValue();
                ByteArrayInputStream in = new ByteArrayInputStream(co.getData());

                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    output.write(buf, 0, len);
                }
                in.close();
                output.flush();
                output.close();
                return;
            } catch (NullPointerException e) {
                LOGGER.debug("element not in cache anymore: " + myUniqueID + "." + targetExtension);
            }

        } else if (!ignoreCache) {
            LOGGER.debug("file not found in cache: " + myUniqueID + "." + targetExtension);
        }

        // if (!ignoreCache && cc.cacheContains(myUniqueID, targetExtension)) {
        // LOGGER.debug("get file from cache: " + myUniqueID);
        // cc.writeToStream(output, myUniqueID, targetExtension);
        // output.flush();
        // output.close();
        // return;
        // } else if (ignoreCache == false) {
        // LOGGER.debug("file not found in cache: " + myUniqueID);
        // }

        // /*
        // * -------------------------------- if there is an internal request from goobiContentServer, you have to overwrite the
        // sourcepath with
        // * given attribute for image url --------------------------------
        // */
        // if (request.getAttribute("sourcepath") != null) {
        // sourceImageUrl = new URI((String) request.getAttribute("sourcepath"));
        // }
        LOGGER.debug("source image:" + sourceImageUrl);

        /*
         * -------------------------------- retrieve source image from url --------------------------------
         */
        ImageManager sourcemanager = new ImageManager(sourceImageUrl.toURL());
        LOGGER.trace("imageManager initialized");

        /*
         * -------------------------------- set the defaults --------------------------------
         */
        int angle = 0;
        int scaleX = 100;
        int scaleY = 100;
        int scaleType = ImageManager.SCALE_BY_PERCENT;
        LinkedList<String> highlightCoordinateList = null;
        Color highlightColor = null;
        Watermark myWatermark = null;
        LOGGER.trace("Variables set");

        /*
         * -------------------------------- rotate --------------------------------
         */
        if (request.getParameterMap().containsKey("rotate")) {
            angle = Integer.parseInt(request.getParameter("rotate"));
            LOGGER.trace("rotate image:" + angle);
        }

        /*
         * -------------------------------- scale: scale the image to some percent value --------------------------------
         */
        if (request.getParameterMap().containsKey("scale")) {
            scaleX = Integer.parseInt(request.getParameter("scale"));
            scaleY = scaleX;
            scaleType = ImageManager.SCALE_BY_PERCENT;
            LOGGER.trace("scale image to percent:" + scaleX);
        }

        if (request.getParameterMap().containsKey("width") && request.getParameterMap().containsKey("height")) {
            scaleX = Integer.parseInt(request.getParameter("width"));
            scaleY = Integer.parseInt(request.getParameter("height"));
            scaleType = ImageManager.SCALE_TO_BOX;
        }

        /*
         * -------------------------------- width: scale image to fixed width --------------------------------
         */
        else if (request.getParameterMap().containsKey("width")) {
            scaleX = Integer.parseInt(request.getParameter("width"));
            scaleY = 0;
            scaleType = ImageManager.SCALE_BY_WIDTH;
            LOGGER.trace("scale image to width:" + scaleX);
        }

        /*
         * -------------------------------- height: scale image to fixed height --------------------------------
         */
        else if (request.getParameterMap().containsKey("height")) {
            scaleY = Integer.parseInt(request.getParameter("height"));
            scaleX = 0;
            scaleType = ImageManager.SCALE_BY_HEIGHT;
            LOGGER.trace("scale image to height:" + scaleY);
        }

        /*
         * -------------------------------- highlight --------------------------------
         */
        if (request.getParameterMap().containsKey("highlight")) {
            highlightCoordinateList = new LinkedList<String>();
            String highlight = request.getParameter("highlight");
            StrTokenizer areas = new StrTokenizer(highlight, "$");
            for (String area : areas.getTokenArray()) {
                StrTokenizer coordinates = new StrTokenizer(area, ",");
                highlightCoordinateList.add(coordinates.getContent());
            }
            highlightColor = config.getDefaultHighlightColor();
        }

        /*
         * -------------------------------- insert watermark, if it should be used --------------------------------
         */
        if (!request.getParameterMap().containsKey("ignoreWatermark") && config.getWatermarkUse()) {
            File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath()));
            myWatermark = Watermark.generateWatermark(request, watermarkfile);
        }

        /*
         * -------------------------------- prepare target --------------------------------
         */
        // change to true if watermark should scale
        RenderedImage targetImage = null;
        if (config.getScaleWatermark()) {
            targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle,
                    highlightCoordinateList, highlightColor, myWatermark, true, ImageManager.BOTTOM);
        } else {
            targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle,
                    highlightCoordinateList, highlightColor, myWatermark, false, ImageManager.BOTTOM);
        }
        LOGGER.trace("Creating ImageInterpreter");
        ImageFileFormat targetFormat = ImageFileFormat.getImageFileFormatFromFileExtension(targetExtension);
        ImageInterpreter wi = targetFormat.getInterpreter(targetImage); // read file
        LOGGER.trace("Image stored in " + wi.getClass().toString());
        /*
         * -------------------------------- set file name and attachment header from parameter or from configuration
         * --------------------------------
         */
        LOGGER.trace("Creating target file");
        StringBuilder targetFileName = new StringBuilder();
        if (config.getSendImageAsAttachment()) {
            targetFileName.append("attachment; ");
        }
        targetFileName.append("filename=");

        if (request.getParameter("targetFileName") != null) {
            targetFileName.append(request.getParameter("targetFileName"));
        } else {
            String filename = ContentLibUtil.getCustomizedFileName(config.getDefaultFileNameImages(),
                    "." + targetFormat.getFileExtension());
            targetFileName.append(filename);
        }
        LOGGER.trace("Adding targetFile " + targetFileName.toString() + " to response");
        response.setHeader("Content-Disposition", targetFileName.toString());
        response.setContentType(targetFormat.getMimeType());

        /*
         * -------------------------------- resolution --------------------------------
         */
        LOGGER.trace("Setting image resolution values");
        if (request.getParameter("resolution") != null) {
            wi.setXResolution(Float.parseFloat(request.getParameter("resolution")));
            wi.setYResolution(Float.parseFloat(request.getParameter("resolution")));
        } else {
            wi.setXResolution(config.getDefaultResolution());
            wi.setYResolution(config.getDefaultResolution());
        }

        LOGGER.trace("Setting image compression");
        if (request.getParameter("compression") != null) {
            String value = request.getParameter("compression");
            try {
                int intvalue = Integer.parseInt(value);
                wi.setWriterCompressionValue(intvalue);
            } catch (Exception e) {
                LOGGER.trace("value is not a number, use default value");
            }
        }

        /*
         * -------------------------------- write target image to stream --------------------------------
         */
        // cc.put(new Element(myUniqueID + "." + targetExtension, wi.getRenderedImage()));

        if (cc != null) {
            byte[] data = wi.writeToStreamAndByteArray(output);
            cc.putIfAbsent(new Element(myUniqueID + "." + targetExtension, new CacheObject(data)));
        } else {
            LOGGER.trace("writing file to servlet response");
            wi.writeToStream(null, output);
        }
        LOGGER.trace("Done writing ImageInterpreter to stream");
        wi.clear();
        LOGGER.trace("Done clearing ImageInterpreter");
    } catch (Exception e) {
        LOGGER.error("CacheException", e);
    }
    long endTime = System.currentTimeMillis();
    LOGGER.trace("Content server time to process request: " + (endTime - startTime) + " ms");
    // try {
    // CommonUtils.appendTextFile("Image request for file " + new File(sourceImageUrl).getAbsolutePath() + "; Time to process: " + (endTime -
    // startTime)
    // + " ms\n", new File(de.unigoettingen.sub.commons.contentlib.servlet.Util.getBaseFolderAsFile(), "timeConsumptionLog.txt"));
    //
    // } catch (IOException e) {
    // LOGGER.info("Unable to write time log file due to IOException " + e.toString());
    // }
}

From source file:ispyb.client.mx.results.ViewResultsAction.java

/**
 * forward to the page displaying a edna file
 * /*  www .j a  v  a 2  s .  c o  m*/
 * @param mapping
 * @param actForm
 * @param request
 * @param response
 * @return
 */
public ActionForward displayEDNAFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request,
        HttpServletResponse response) {

    try {
        String filePath = request.getParameter(Constants.EDNA_FILE_PATH);

        LOG.debug("displayEDNAFile: " + filePath);

        if (Constants.SITE_IS_DLS()) {
            byte[] fileContent = FileUtil.fileToString(filePath).getBytes();
            // --- Write Image to output ---
            response.setContentType("text/plain");
            try {
                ServletOutputStream out = response.getOutputStream();
                out.write(fileContent);
                out.flush();
                out.close();
            } catch (IOException ioe) {
                LOG.error("Unable to write to outputStream. (IOException)");
                ioe.printStackTrace();
                return mapping.findForward("error");
            }
        } else {
            // String fileContent = FileUtil.fileToString(filePath);
            //
            // // Populate form
            // form.setDNAContent(fileContent);
            // FormUtils.setFormDisplayMode(request, actForm, FormUtils.INSPECT_MODE);
            byte[] fileContent = FileUtil.fileToString(filePath).getBytes();
            // --- Write Image to output ---
            response.setContentType("text/plain");
            try {
                ServletOutputStream out = response.getOutputStream();
                out.write(fileContent);
                out.flush();
                out.close();
            } catch (IOException ioe) {
                LOG.error("Unable to write to outputStream. (IOException)");
                ioe.printStackTrace();
                return mapping.findForward("error");
            }
        }
    } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.results.viewDNA"));
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString()));
        e.printStackTrace();
    }
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        return (mapping.findForward("error"));
    } else
        // return Constants.SITE_IS_DLS() ? null : mapping.findForward("viewTextFile");
        return null;
}

From source file:ispyb.client.mx.results.ViewResultsAction.java

/**
 * Display EDNA results content on the page
 * /*from   w  ww.  j  a  v a 2 s  .  c  om*/
 * @param mapping
 * @param actForm
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ActionForward displayEDNAPagesContent(ActionMapping mapping, ActionForm actForm,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    ActionMessages errors = new ActionMessages();

    dataCollectionIdst = request.getParameter(Constants.DATA_COLLECTION_ID);
    Integer dataCollectionId = new Integer(dataCollectionIdst);
    DataCollection3VO dc = dataCollectionService.findByPk(dataCollectionId, false, false);
    String archivePath = Constants.SITE_IS_DLS() ? PathUtils.getFullEDNAPath(dc) : PathUtils.getFullDNAPath(dc);
    // String fullEDNAPath = archivePath + Constants.EDNA_FILES_SUFIX;
    if (Constants.SITE_IS_EMBL()) {
        String[] archivePathDir = archivePath.split("/");
        String beamLineName = dc.getDataCollectionGroupVO().getSessionVO().getBeamlineName().toLowerCase();
        archivePath = Constants.DATA_FILEPATH_START + beamLineName + "/";
        for (int k = 4; k < archivePathDir.length; k++) {
            archivePath = archivePath + archivePathDir[k] + "/";
        }
    }

    boolean isFileExist = new File(archivePath + Constants.EDNA_FILES_SUFIX).exists();
    String fullEDNAPath = archivePath;
    if (Constants.SITE_IS_DLS() || (isFileExist)) {
        fullEDNAPath += Constants.EDNA_FILES_SUFIX;
    }
    String indexPath = Constants.SITE_IS_DLS() ? archivePath + EDNA_FILES_INDEX_FILE
            : archivePath + getEdna_index_file(dc);

    LOG.debug("Check if the Characterisation results index file " + indexPath + " exists... ");
    boolean isFileExist2 = new File(indexPath).exists();
    String fileContent = null;
    if (isFileExist2)
        fileContent = FileUtil.fileToString(indexPath);
    else {
        fileContent = "Sorry, but no EDNA files can be retrieved for this data collection.";
    }
    // new path to view images
    // String pathImageUrl = request.getContextPath() + "/user/imageDownload.do?reqCode=getEDNAImage";
    String pathImageUrl = "imageDownload.do?reqCode=getEDNAImage";

    // String hrefImageUrl = request.getContextPath() + "/user/viewResults.do?reqCode=viewEDNAImage";
    String hrefImageUrl = "viewResults.do?reqCode=viewEDNAImage";

    String hrefFileUrl = "viewResults.do?reqCode=displayEDNAFile";

    // Case where the file is not found
    if (fileContent == null) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.results.viewDNA"));
        return this.display(mapping, actForm, request, response);
    }

    // Format the file: change the <a href and <img src tags
    byte[] fileContentChanged = (UrlUtils.formatEDNApageURL(fileContent, pathImageUrl, hrefImageUrl,
            hrefFileUrl, fullEDNAPath)).getBytes();

    // --- Write Image to output ---
    response.setContentType("text/html");
    try {
        ServletOutputStream out = response.getOutputStream();
        out.write(fileContentChanged);
        out.flush();
        out.close();
    } catch (IOException ioe) {
        LOG.error("Unable to write to outputStream. (IOException)");
        ioe.printStackTrace();
        return mapping.findForward("error");
    }

    return null;
}

From source file:ispyb.client.mx.results.ViewResultsAction.java

/**
 * getDataFromFile//from w  w w .jav  a 2  s  .c om
 * 
 * @param mapping
 * @param actForm
 * @param request
 * @param response
 * @return
 */
public ActionForward getDataFromFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request,
        HttpServletResponse response) {

    ActionMessages errors = new ActionMessages();
    boolean isWindows = (System.getProperty("os.name").indexOf("Win") != -1) ? true : false;
    String tmpDirectory = ((isWindows) ? Constants.BZIP2_PATH_W : Constants.BZIP2_PATH_OUT);

    try {
        Integer proposalId = (Integer) request.getSession().getAttribute(Constants.PROPOSAL_ID);
        Integer imageId = new Integer(request.getParameter(Constants.IMAGE_ID));

        List<Image3VO> imageFetchedList = imageService.findByImageIdAndProposalId(imageId, proposalId);

        if (imageFetchedList.size() == 1) {
            Image3VO selectedImage = (imageFetchedList.get(0));
            // --- Create File Names ---
            String _sourceFileName = selectedImage.getFileLocation() + "/" + selectedImage.getFileName();
            _sourceFileName = (isWindows) ? "C:" + _sourceFileName : _sourceFileName;

            String _destinationFileName = selectedImage.getFileName();
            String _destinationfullFilename = tmpDirectory + "/" + _destinationFileName;
            String _bz2FileName = _destinationFileName + ".bz2";
            String _bz2FullFileName = _destinationfullFilename + ".bz2";

            // --- Copy Files ---
            File source = new File(_sourceFileName);
            File destination = new File(_destinationfullFilename);
            File bz2File = new File(_bz2FullFileName);
            FileUtils.copyFile(source, destination, false);

            // --- BZIP2 File ---
            String cmd = ((isWindows) ? Constants.BZIP2_PATH_W : Constants.BZIP2_PATH);
            String argument = Constants.BZIP2_ARGS;
            argument = " " + argument + " " + _destinationfullFilename;
            cmd = cmd + argument;
            this.CmdExec(cmd, false);

            // --- Active Wait for the .bz2 File to be created + timeout ---
            Date now = new Date();
            long startTime = now.getTime();
            long timeNow = now.getTime();
            long timeOut = 60000;
            boolean filePresent = false;

            while (!filePresent && (timeNow - startTime) < timeOut) {
                Date d2 = new Date();
                timeNow = d2.getTime();
                filePresent = bz2File.exists();
            }
            if (filePresent)
                Thread.sleep(10000);

            // --- Write Image to output ---
            byte[] imageBytes = FileUtil.readBytes(_bz2FullFileName);
            response.setContentLength(imageBytes.length);
            response.setHeader("Content-Disposition", "attachment; filename=" + _bz2FileName);
            response.setContentType("application/x-bzip");
            ServletOutputStream out = response.getOutputStream();

            out.write(imageBytes);
            out.flush();
            out.close();

            // --- Clean up things ---
            FileCleaner fileCleaner = new FileCleaner(60000, _bz2FullFileName);
            fileCleaner.start();

            return null;
        } else {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("error.user.results.viewImageId", imageId));
            LOG.warn("List fetched has a size != 1!!");
        }

        FormUtils.setFormDisplayMode(request, actForm, FormUtils.INSPECT_MODE);

    } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.results.general.image"));
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString()));
        e.printStackTrace();
    }

    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        return (mapping.findForward("error"));
    } else
        return mapping.findForward("viewJpegImage");

}

From source file:net.sf.ginp.GinpPictureServlet.java

/**
 *  Central Processor of HTTP GET and POST Methods. This method gets the
 *  model for the users session, and returns the correctly sized picture
 *  based on the command parameters in the request and the model state.
 *
 *@param  req                   HTTP Request
 *@param  res                   HTTP Response
 *@exception  IOException       Description of the Exception
 *///from  w  ww . ja v a 2  s.  co  m
final void doHttpMethod(final HttpServletRequest req, final HttpServletResponse res) throws IOException {
    ServletOutputStream sos = res.getOutputStream();
    GinpModel model = null;

    //Retrieve the model for this web app
    try {
        model = ModelUtil.getModel(req);
    } catch (Exception ex) {
        log.error("Problem getting model", ex);

        return;
    }

    String filename = req.getParameter("name");
    String path = req.getParameter("path");

    res.setContentType("image/jpeg");

    //Only allow files below the given directory
    if (filename != null) {
        filename = filename.replaceAll("\\.\\./", "");
        filename = filename.replaceAll("\\.\\.\\\\", "");

        // Only deliver JPEGs
        if (!((filename.toLowerCase()).endsWith(".jpg") || (filename.toLowerCase()).endsWith(".jpeg"))) {
            filename = null;
        }
    }

    if (path != null) {
        path = path.replaceAll("\\.\\./", "");
        path = path.replaceAll("\\.\\.\\\\", "");
    }

    if (filename != null) {
        String absPath = getImagePath(model, path);

        int maxSize = 0;
        File fl;

        if (req.getParameter("maxsize") != null) {
            maxSize = GinpUtil.parseInteger(req, "maxsize", 0);
            fl = getThumbnailPath(filename, absPath, maxSize);
        } else {
            fl = new File(absPath + filename);
        }

        fl = handleMissingPicture(req, res, fl);

        FileInputStream is = new FileInputStream(fl);

        String heightParm = req.getParameter("height");
        String widthParm = req.getParameter("width");

        // debug output
        //if (log.isDebugEnabled()) {
        log.info("doHttpMethod filename=" + filename + " absPath=" + absPath + " path=" + path + " heightParm="
                + heightParm + " widthParm=" + widthParm + " maxSize=" + maxSize + " ImageFile="
                + fl.getPath());

        //}
        if ((heightParm != null) || (widthParm != null)) {
            int width = GinpUtil.parseInteger(req, "width", 0);
            int height = GinpUtil.parseInteger(req, "height", 0);
            GinpUtil.writeScaledImageToStream(sos, is, width, height);
        } else {
            // deliver raw image
            GinpUtil.writeInputStreamToOutputStream(sos, is);
        }
    } else {
        // is this a request to set client info
        if ((req.getParameter("cmd") != null) && req.getParameter("cmd").equals("setprops")) {
            if (req.getParameter("pagewidth") != null) {
                int i = GinpUtil.parseInteger(req, "pagewidth", 0);

                if (i > 0) {
                    model.setPageWidth(i);
                }
            }

            if (req.getParameter("pageheight") != null) {
                int i = GinpUtil.parseInteger(req, "pageheight", 0);

                if (i > 0) {
                    model.setPageHeight(i);
                }
            }
        }

        deliverSpacer(req, sos);
    }

    sos.flush();
    sos.close();
}

From source file:ispyb.client.mx.results.ViewResultsAction.java

public ActionForward displayCorrectionFile(ActionMapping mapping, ActionForm actForm,
        HttpServletRequest request, HttpServletResponse response) {
    ActionMessages errors = new ActionMessages();

    String filename = "";
    String fullFilePath = "";

    try {//from  ww  w .  jav  a  2 s. c o  m
        if (request.getParameter("fileName") != null)
            filename = new String(request.getParameter("fileName"));
        Integer dataCollectionId = null;
        if (BreadCrumbsForm.getIt(request).getSelectedDataCollection() != null)
            dataCollectionId = BreadCrumbsForm.getIt(request).getSelectedDataCollection().getDataCollectionId();
        else {
            dataCollectionId = new Integer(request.getParameter(Constants.SESSION_ID));
        }
        if (dataCollectionId != null) {
            DataCollection3VO dataCollection = dataCollectionService.findByPk(dataCollectionId, false, false);
            String beamLineName = dataCollection.getDataCollectionGroupVO().getSessionVO().getBeamlineName();
            String[] correctionFiles = ESRFBeamlineEnum.retrieveCorrectionFilesNameWithName(beamLineName);
            if (correctionFiles != null) {
                for (int k = 0; k < correctionFiles.length; k++) {
                    String correctionFileName = correctionFiles[k];
                    if (correctionFileName != null && correctionFileName.equals(filename)) {
                        String dir = ESRFBeamlineEnum.retrieveDirectoryNameWithName(beamLineName);
                        if (dir != null) {
                            String correctionFilePath = "/data/pyarch/" + dir + "/" + correctionFileName;
                            fullFilePath = PathUtils.FitPathToOS(correctionFilePath);
                            java.io.FileInputStream in;
                            in = new java.io.FileInputStream(new File(fullFilePath));
                            response.setContentType("application/octet-stream");
                            response.setHeader("Content-Disposition", "attachment;filename=" + filename);

                            ServletOutputStream out = response.getOutputStream();

                            byte[] buf = new byte[4096];
                            int bytesRead;

                            while ((bytesRead = in.read(buf)) != -1) {
                                out.write(buf, 0, bytesRead);
                            }
                            in.close();
                            out.flush();
                            out.close();
                            return null;
                        }
                    }
                }
            }
        }

    } catch (java.io.IOException e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("errors.detail", "Unable to download file: " + fullFilePath));
        saveErrors(request, errors);
        e.printStackTrace();
        return mapping.findForward("error");
    } catch (Exception e) {
        e.printStackTrace();
        return mapping.findForward("error");
    }
    errors.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("errors.detail", "Unable to download file: " + filename));
    saveErrors(request, errors);
    return mapping.findForward("error");
}

From source file:com.ephesoft.gxt.batchinstance.server.BatchInfoDownloadServlet.java

/**
 * Creates a zipped file containing the selected artifacts and downloads it if Download was selected or copies it to the path
 * entered by user if DownloadTo was selected.
 * /*from w ww  .j  a v a 2  s  .  c om*/
 * @param response {@link HttpServletResponse} the response object.
 * @param writer {@link PrintWriter} the writer object associated with response.
 * @param batchInstance {@link BatchInstance} th batch instance.
 * @param batchSchemaService {@link BatchSchemaService}
 * @param batchClass {@link BatchClass} the batch class.
 * @throws IOException {@link IOException}
 */
private void downloadOrDownloadtoPath(final HttpServletResponse response, PrintWriter writer,
        final BatchInstance batchInstance, final BatchSchemaService batchSchemaService,
        final BatchClass batchClass) throws IOException {
    File downloadToFolder = null;

    // checks if the download to folder path is valid
    if (DOWNLOAD_TO_RADIO.equalsIgnoreCase(selectedRadioButton)) {
        downloadToFolder = new File(downloadToFolderPath);
        downloadToFolder.mkdirs();
        if (!downloadToFolder.exists()) {

            // Removed response.sendError code to fix JIRA bug id EPHESOFT-12355. Did not returned expected results.
            log.error(PATH_SPECIFIED_IS_NOT_VALID);
            writer = response.getWriter();
            writer.write(BatchInstanceConstants.ERROR_CODE_TEXT);
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        writer = response.getWriter();
        response.setContentType(IUtilCommonConstants.CONTENT_TYPE_HTML);
    }

    ServletOutputStream out = null;
    ZipOutputStream zout = null;
    FileOutputStream fout = null;
    String zippedFilePath = null;
    String batchInstanceIdentifier = null;
    if (null != batchInstance) {
        batchInstanceIdentifier = batchInstance.getIdentifier();
    }
    String zipFileName = createZipFileName(batchInstanceIdentifier);
    String downloadFolderPath = createDownloadFolderPathName(batchInstanceIdentifier, baseFolderPath);
    File downloadFolder = new File(downloadFolderPath);
    downloadFolder.mkdirs();

    if (downloadFolder.exists()) {
        // copies the selected folders to download folder
        copySelectedFolders(batchInstance, batchSchemaService, batchClass, downloadFolderPath, downloadFolder);
        if (writer != null) {
            writer.write(copyTroubleshootingArtifacts.getFoldersNotCopied());
        }
        if (downloadFolderPath.lastIndexOf(File.separator) != -1) {
            zippedFilePath = EphesoftStringUtil.concatenate(
                    downloadFolderPath.substring(0, downloadFolderPath.lastIndexOf(File.separator)),
                    File.separator, zipFileName, ZIP_EXT);
            LOGGER.info(zippedFilePath);
        } else {
            LOGGER.error(EphesoftStringUtil.concatenate("zipped file path ", zippedFilePath));
            return;
        }
        try {
            if (0 != downloadFolder.list().length) {
                // when download button is clicked
                if (DOWNLOAD_RADIO.equalsIgnoreCase(selectedRadioButton)) {
                    response.setContentType(IUtilCommonConstants.CONTENT_TYPE_ZIP);
                    response.setHeader("Content-Disposition", EphesoftStringUtil
                            .concatenate("attachment; filename=\"", zipFileName, ZIP_EXT, "\"\r\n"));
                    out = response.getOutputStream();
                    zout = new ZipOutputStream(out);
                } else {
                    fout = new FileOutputStream(zippedFilePath);
                    zout = new ZipOutputStream(fout);
                }
                FileUtils.zipDirectoryWithFullName(downloadFolderPath, zout);
            }

            // if download to is selected copy the zip file to the download to path
            if (DOWNLOAD_TO_RADIO.equalsIgnoreCase(selectedRadioButton) && !new File(
                    EphesoftStringUtil.concatenate(downloadToFolderPath, File.separator, zipFileName, ZIP_EXT))
                            .exists()
                    && 0 != downloadFolder.list().length) {
                copyZipFileToDownloadToFolder(zippedFilePath, zipFileName);
            }
            if (out != null) {
                out.flush();
            }
            if (writer != null) {
                writer.flush();
            }
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (IOException ioException) {

            // Unable to create the temporary export file(s)/folder(s)
            log.error(EphesoftStringUtil.concatenate("Error occurred while creating the zip file. ",
                    ioException.getMessage()), ioException);
        } finally {

            // clean up code
            closeResources(out, zout, fout, writer);
            if (downloadFolder != null) {
                FileUtils.deleteDirectoryAndContentsRecursive(downloadFolder);
            }
        }
    } else {
        LOGGER.error("Unable to create download folder.");
    }
}

From source file:org.fcrepo.server.access.FedoraAccessServlet.java

/**
 * <p>/*from  w ww.  java 2s  . com*/
 * This method calls the Fedora Access Subsystem to retrieve a MIME-typed
 * stream corresponding to the dissemination request.
 * </p>
 *
 * @param context
 *        The read only context of the request.
 * @param PID
 *        The persistent identifier of the Digital Object.
 * @param sDefPID
 *        The persistent identifier of the Service Definition object.
 * @param methodName
 *        The method name.
 * @param userParms
 *        An array of user-supplied method parameters.
 * @param asOfDateTime
 *        The version datetime stamp of the digital object.
 * @param response
 *        The servlet response.
 * @param request
 *        The servlet request.
 * @throws IOException
 *         If an error occurrs with an input or output operation.
 * @throws ServerException
 *         If an error occurs in the Access Subsystem.
 */
public void getDissemination(Context context, String PID, String sDefPID, String methodName,
        Property[] userParms, Date asOfDateTime, HttpServletResponse response, HttpServletRequest request)
        throws IOException, ServerException {
    ServletOutputStream out = null;
    MIMETypedStream dissemination = null;
    dissemination = m_access.getDissemination(context, PID, sDefPID, methodName, userParms, asOfDateTime);
    out = response.getOutputStream();
    try {
        // testing to see what's in request header that might be of interest
        if (logger.isDebugEnabled()) {
            for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                Enumeration<?> headerValues = request.getHeaders(name);
                StringBuffer sb = new StringBuffer();
                while (headerValues.hasMoreElements()) {
                    sb.append((String) headerValues.nextElement());
                }
                String value = sb.toString();
                logger.debug("FEDORASERVLET REQUEST HEADER CONTAINED: {} : {}", name, value);
            }
        }

        // Dissemination was successful;
        // Return MIMETypedStream back to browser client
        if (dissemination.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            String location = "";
            for (Property prop : dissemination.header) {
                if (prop.name.equalsIgnoreCase(HttpHeaders.LOCATION)) {
                    location = prop.value;
                    break;
                }
            }

            response.sendRedirect(location);
        } else {
            response.setContentType(dissemination.getMIMEType());
            Property[] headerArray = dissemination.header;
            if (headerArray != null) {
                for (int i = 0; i < headerArray.length; i++) {
                    if (headerArray[i].name != null
                            && !headerArray[i].name.equalsIgnoreCase("transfer-encoding")
                            && !headerArray[i].name.equalsIgnoreCase("content-type")) {
                        response.addHeader(headerArray[i].name, headerArray[i].value);
                        logger.debug(
                                "THIS WAS ADDED TO FEDORASERVLET  RESPONSE HEADER FROM ORIGINATING  PROVIDER {} : {}",
                                headerArray[i].name, headerArray[i].value);
                    }
                }
            }
            int byteStream = 0;
            logger.debug("Started reading dissemination stream");
            InputStream dissemResult = dissemination.getStream();
            byte[] buffer = new byte[BUF];
            while ((byteStream = dissemResult.read(buffer)) != -1) {
                out.write(buffer, 0, byteStream);
            }
            buffer = null;
            dissemResult.close();
            dissemResult = null;
            out.flush();
            out.close();
            logger.debug("Finished reading dissemination stream");
        }
    } finally {
        dissemination.close();
    }
}