Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:it.cnr.icar.eric.server.interfaces.rest.URLHandler.java

/**
 * Writes XML RepositoryItems as a RepositoryItemList. Ignores any other
 * type of RepositoryItem.s// www.j ava 2  s  . c  om
 */
void writeRepositoryItems(List<?> eos) throws IOException, RegistryException, ObjectNotFoundException {
    ServerRequestContext context = new ServerRequestContext("URLHandler.writeRepositoryItem", null);
    ServletOutputStream sout = response.getOutputStream();
    boolean doCommit = false;
    try {
        RepositoryItemListType ebRepositoryItemListType = bu.lcmFac.createRepositoryItemListType();

        Iterator<?> iter = eos.iterator();
        while (iter.hasNext()) {
            ExtrinsicObjectType eo = (ExtrinsicObjectType) iter.next();
            String id = eo.getId();

            RepositoryItem ri = QueryManagerFactory.getInstance().getQueryManager().getRepositoryItem(context,
                    id);

            if (ri == null) {
                throw new ObjectNotFoundException(id,
                        ServerResourceBundle.getInstance().getString("message.repositoryItem"));
            } else {
                if (eo.getMimeType().equals("text/xml")) {
                    DataHandler dataHandler = ri.getDataHandler();
                    InputStream fStream = dataHandler.getInputStream();

                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    factory.setNamespaceAware(true);
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document document = builder.parse(fStream);
                    Element rootElement = document.getDocumentElement();

                    ebRepositoryItemListType.getAny().add(rootElement);
                }
            }
        }
        // javax.xml.bind.Marshaller marshaller =
        // bu.lcmFac.createMarshaller();
        javax.xml.bind.Marshaller marshaller = bu.getJAXBContext().createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        JAXBElement<RepositoryItemListType> ebRepositoryItemList = bu.lcmFac
                .createRepositoryItemList(ebRepositoryItemListType);
        marshaller.marshal(ebRepositoryItemList, sout);
        doCommit = true;

    } catch (JAXBException e) {
        throw new RegistryException(e);
    } catch (ParserConfigurationException e) {
        throw new RegistryException(e);
    } catch (SAXException e) {
        throw new RegistryException(e);
    } finally {
        if (sout != null) {
            sout.close();
            sout = null;
        }
        try {
            closeContext(context, doCommit);
        } catch (Exception ex) {
            log.error(ex, ex);
        }
    }
}

From source file:org.structr.web.servlet.HtmlServlet.java

private void streamFile(SecurityContext securityContext, final File file, HttpServletRequest request,
        HttpServletResponse response, final EditMode edit) throws IOException {

    if (!securityContext.isVisible(file)) {

        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*  w  w w.j a  v a2  s  .co m*/

    }

    final ServletOutputStream out = response.getOutputStream();
    final String downloadAsFilename = request.getParameter(DOWNLOAD_AS_FILENAME_KEY);
    final Map<String, Object> callbackMap = new LinkedHashMap<>();

    // make edit mode available in callback method
    callbackMap.put("editMode", edit);

    if (downloadAsFilename != null) {
        // Set Content-Disposition header to suggest a default filename and force a "save-as" dialog
        // See:
        // http://en.wikipedia.org/wiki/MIME#Content-Disposition,
        // http://tools.ietf.org/html/rfc2183
        // http://tools.ietf.org/html/rfc1806
        // http://tools.ietf.org/html/rfc2616#section-15.5 and http://tools.ietf.org/html/rfc2616#section-19.5.1
        response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadAsFilename + "\"");

        callbackMap.put("requestedFileName", downloadAsFilename);
    }

    if (!EditMode.WIDGET.equals(edit) && notModifiedSince(request, response, file, false)) {

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

        callbackMap.put("statusCode", HttpServletResponse.SC_NOT_MODIFIED);

    } else {

        final String downloadAsDataUrl = request.getParameter(DOWNLOAD_AS_DATA_URL_KEY);
        if (downloadAsDataUrl != null) {

            IOUtils.write(FileHelper.getBase64String(file), out);
            response.setContentType("text/plain");
            response.setStatus(HttpServletResponse.SC_OK);

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

            callbackMap.put("statusCode", HttpServletResponse.SC_OK);

        } else {

            // 2b: stream file to response
            final InputStream in = file.getInputStream();
            final String contentType = file.getContentType();

            if (contentType != null) {

                response.setContentType(contentType);

            } else {

                // Default
                response.setContentType("application/octet-stream");
            }

            final String range = request.getHeader("Range");

            try {

                if (StringUtils.isNotEmpty(range)) {

                    final long len = file.getSize();
                    long start = 0;
                    long end = len - 1;

                    final Matcher matcher = Pattern.compile("bytes=(?<start>\\d*)-(?<end>\\d*)").matcher(range);

                    if (matcher.matches()) {
                        String startGroup = matcher.group("start");
                        start = startGroup.isEmpty() ? start : Long.valueOf(startGroup);
                        start = Math.max(0, start);

                        String endGroup = matcher.group("end");
                        end = endGroup.isEmpty() ? end : Long.valueOf(endGroup);
                        end = end > len - 1 ? len - 1 : end;
                    }

                    long contentLength = end - start + 1;

                    // Tell the client that we support byte ranges
                    response.setHeader("Accept-Ranges", "bytes");
                    response.setHeader("Content-Range", String.format("bytes %s-%s/%s", start, end, len));
                    response.setHeader("Content-Length", String.format("%s", contentLength));

                    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                    callbackMap.put("statusCode", HttpServletResponse.SC_PARTIAL_CONTENT);

                    IOUtils.copyLarge(in, out, start, contentLength);

                } else {

                    response.setStatus(HttpServletResponse.SC_OK);
                    callbackMap.put("statusCode", HttpServletResponse.SC_OK);

                    IOUtils.copyLarge(in, out);

                }

            } catch (Throwable t) {

            } finally {

                if (out != null) {

                    try {
                        // 3: output content
                        out.flush();
                        out.close();

                    } catch (Throwable t) {
                    }
                }

                if (in != null) {
                    in.close();
                }

                response.setStatus(HttpServletResponse.SC_OK);
            }
        }
    }

    // WIDGET mode means "opened in frontend", which we don't want to count as an external download
    if (!EditMode.WIDGET.equals(edit)) {

        // call onDownload callback
        try {

            file.invokeMethod("onDownload", Collections.EMPTY_MAP, false);

        } catch (FrameworkException fex) {
            fex.printStackTrace();
        }
    }
}

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

/**
 * Auto generated method comment/*from  ww  w  .j av  a  2s.c  o  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.sakaiproject.tool.assessment.ui.servlet.delivery.ShowMediaServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String agentIdString = getAgentString(req, res);
    if (agentIdString == null) {
        String path = "/jsf/delivery/mediaAccessDenied.faces";
        RequestDispatcher dispatcher = req.getRequestDispatcher(path);
        dispatcher.forward(req, res);//from  w w w.  j  av a  2 s  .  co m
        return;
    }
    String mediaId = req.getParameter("mediaId");
    if (mediaId == null || mediaId.trim().equals("")) {
        return;
    }

    // get media
    GradingService gradingService = new GradingService();
    MediaData mediaData = gradingService.getMedia(mediaId);
    String mediaLocation = mediaData.getLocation();
    int fileSize = mediaData.getFileSize().intValue();
    log.info("****1. media file size=" + fileSize);

    //if setMimeType="false" in query string, implies, we want to do a forced download
    //in this case, we set contentType='application/octet-stream'
    String setMimeType = req.getParameter("setMimeType");
    log.info("****2. setMimeType=" + setMimeType);

    // get assessment's ownerId
    // String assessmentCreatedBy = req.getParameter("createdBy");

    // who can access the media? You can,
    // a. if you are the creator.
    // b. if you have a assessment.grade.any or assessment.grade.own permission
    boolean accessDenied = true;
    String currentSiteId = "";
    boolean isAudio = false;
    Long assessmentGradingId = mediaData.getItemGradingData().getAssessmentGradingId();
    PublishedAssessmentIfc pub = gradingService
            .getPublishedAssessmentByAssessmentGradingId(assessmentGradingId.toString());
    if (pub != null) {
        PublishedAssessmentService service = new PublishedAssessmentService();
        currentSiteId = service.getPublishedAssessmentOwner(pub.getPublishedAssessmentId());
    }

    // some log checking
    //log.debug("agentIdString ="+agentIdString);
    //log.debug("****current site Id ="+currentSiteId);

    boolean hasPrivilege = agentIdString != null && (agentIdString.equals(mediaData.getCreatedBy()) // user is creator
            || canGrade(req, res, agentIdString, currentSiteId));
    if (hasPrivilege) {
        accessDenied = false;
    }
    if (accessDenied) {
        String path = "/jsf/delivery/mediaAccessDenied.faces";
        RequestDispatcher dispatcher = req.getRequestDispatcher(path);
        dispatcher.forward(req, res);
    } else {
        String displayType = "inline";
        if (mediaData.getMimeType() != null && !mediaData.getMimeType().equals("application/octet-stream")
                && !(setMimeType != null && ("false").equals(setMimeType))) {
            res.setContentType(mediaData.getMimeType());
        } else {
            displayType = "attachment";
            res.setContentType("application/octet-stream");
        }
        log.debug("****" + displayType + ";filename=\"" + mediaData.getFilename() + "\";");

        res.setHeader("Content-Disposition", displayType + ";filename=\"" + mediaData.getFilename() + "\";");

        int start = 0;
        int end = fileSize - 1;
        int rangeContentLength = end - start + 1;

        String range = req.getHeader("Range");

        if (StringUtils.isNotBlank(range)) {
            Matcher matcher = HTTP_RANGE_PATTERN.matcher(range);

            if (matcher.matches()) {
                String startMatch = matcher.group(1);
                start = startMatch.isEmpty() ? start : Integer.valueOf(startMatch);
                start = start < 0 ? 0 : start;

                String endMatch = matcher.group(2);
                end = endMatch.isEmpty() ? end : Integer.valueOf(endMatch);
                end = end > fileSize - 1 ? fileSize - 1 : end;

                rangeContentLength = end - start + 1;
            }

            res.setHeader("Content-Range", String.format("bytes %s-%s/%s", start, end, fileSize));
            res.setHeader("Content-Length", String.format("%s", rangeContentLength));
            res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        } else {
            res.setContentLength(fileSize);
        }

        //** note that res.setContentType() must be called before res.getOutputStream(). see javadoc on this
        FileInputStream inputStream = null;
        BufferedInputStream buf_inputStream = null;
        ServletOutputStream outputStream = res.getOutputStream();
        BufferedOutputStream buf_outputStream = null;
        ByteArrayInputStream byteArrayInputStream = null;
        if (mediaLocation == null || (mediaLocation.trim()).equals("")) {
            try {
                byteArrayInputStream = new ByteArrayInputStream(mediaData.getMedia());
                buf_inputStream = new BufferedInputStream(byteArrayInputStream);
            } catch (Exception e) {
                log.error("****empty media save to DB=" + e.getMessage());
            }
        } else {
            try {
                inputStream = getFileStream(mediaLocation);
                buf_inputStream = new BufferedInputStream(inputStream);
            } catch (Exception e) {
                log.error("****empty media save to file =" + e.getMessage());
            }

        }

        try {

            buf_outputStream = new BufferedOutputStream(outputStream);
            int i = 0;
            if (buf_inputStream != null) {
                // skip to the start of the possible range request
                buf_inputStream.skip(start);

                int bytesLeft = rangeContentLength;
                byte[] buffer = new byte[1024];

                while ((i = buf_inputStream.read(buffer)) != -1 && bytesLeft > 0) {
                    buf_outputStream.write(buffer);
                    bytesLeft -= i;
                }
            }
            log.debug("**** mediaLocation=" + mediaLocation);

            res.flushBuffer();
        } catch (Exception e) {
            log.warn(e.getMessage());
        } finally {
            if (buf_outputStream != null) {
                try {
                    buf_outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (buf_inputStream != null) {
                try {
                    buf_inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (byteArrayInputStream != null) {
                try {
                    byteArrayInputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }
}

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   w  ww .ja v a2 s. c  o  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:ke.co.tawi.babblesms.server.servlet.export.csv.ExportCsv.java

/**
 * Returns a zipped MS Excel file of the data specified for exporting.
 *
 * @param request/*  w  w w  . j a  v a  2 s .c o  m*/
 * @param response
 * @throws ServletException, IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ServletOutputStream out = response.getOutputStream();
    response.setContentType("application/zip");
    response.setHeader("Cache-Control", "cache, must-revalidate");
    response.setHeader("Pragma", "public");

    HttpSession session = request.getSession(false);
    Account account;
    String fileName;

    String exportExcelOption = request.getParameter("exportExcel");

    String sessionEmail = (String) session.getAttribute(SessionConstants.ACCOUNT_SIGN_IN_KEY);

    Element element = accountsCache.get(sessionEmail);
    account = (Account) element.getObjectValue();

    fileName = new StringBuffer(account.getUsername()).append(" ").append(SPREADSHEET_NAME).toString();

    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + StringUtils.replace(fileName, ".xlsx", ".zip") + "\"");

    File excelFile = new File(FileUtils.getTempDirectoryPath() + File.separator + fileName);
    File csvFile = new File(StringUtils.replace(excelFile.getCanonicalPath(), ".xlsx", ".csv"));
    File zippedFile = new File(StringUtils.replace(excelFile.getCanonicalPath(), ".xlsx", ".zip"));

    // These are to determine whether or not we have created a CSV & Excel file on disk
    boolean successCSVFile = true, successExcelFile = true;

    if (StringUtils.equalsIgnoreCase(exportExcelOption, "Export All")) { //export all pages
        successCSVFile = dbFileUtils.sqlResultToCSV(getExportTopupsSqlQuery(account), csvFile.toString(), '|');

        if (successCSVFile) {
            successExcelFile = AllTopupsExportUtil.createExcelExport(csvFile.toString(), "|",
                    excelFile.toString());
        }

    } else if (StringUtils.equalsIgnoreCase(exportExcelOption, "Export Page")) { //export a single page

        InboxPage inboxPage = (InboxPage) session.getAttribute("currentInboxPage");

        successExcelFile = AllTopupsExportUtil.createExcelExport(inboxPage.getContents(), networkHash,
                networkHash, "|", excelFile.toString());

    } else { //export search results

        InboxPage topupPage = (InboxPage) session.getAttribute("currentSearchPage");

        successExcelFile = AllTopupsExportUtil.createExcelExport(topupPage.getContents(), networkHash,
                networkHash, "|", excelFile.toString());
    }

    if (successExcelFile) { // If we successfully created the MS Excel File on disk  
        // Zip the Excel file
        List<File> filesToZip = new ArrayList<>();
        filesToZip.add(excelFile);
        ZipUtil.compressFiles(filesToZip, zippedFile.toString());

        // Push the file to the request
        FileInputStream input = FileUtils.openInputStream(zippedFile);
        IOUtils.copy(input, out);
    }

    out.close();

    FileUtils.deleteQuietly(excelFile);
    FileUtils.deleteQuietly(csvFile);
    FileUtils.deleteQuietly(zippedFile);
}

From source file:org.oscarehr.document.web.ManageDocumentAction.java

public ActionForward getPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, int pageNum) {
    ServletOutputStream outs = null;
    BufferedInputStream bfis = null;
    try {//from  ww w  .j av  a2 s .c o  m
        String doc_no = request.getParameter("doc_no");
        log.debug("Document No :" + doc_no);

        LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ,
                LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr());

        Document d = documentDAO.getDocument(doc_no);
        log.debug("Document Name :" + d.getDocfilename());

        outs = response.getOutputStream();
        if (d.getContenttype().equals("application/pdf")) {
            File outfile = hasCacheVersion(d, pageNum);
            if (outfile == null) {
                log.debug("No Cache Version");
                outfile = createCacheVersion(d, pageNum);
            } else {
                log.debug("THERE WAS A CACHE Version " + outfile);
            }

            response.setContentType("image/png");
            //read the file name.
            response.setHeader("Content-Disposition", "attachment;filename=" + d.getDocfilename());
            bfis = new BufferedInputStream(new FileInputStream(outfile));
            int data;
            while ((data = bfis.read()) != -1) {
                outs.write(data);
            }
            bfis.close();

        } else {
            File outfile = new File(EDocUtil.getDocumentPath(d.getDocfilename()));

            response.setContentType(d.getContenttype());
            response.setHeader("Content-Disposition", "attachment;filename=" + d.getDocfilename());

            bfis = new BufferedInputStream(new FileInputStream(outfile));
            int data;
            while ((data = bfis.read()) != -1) {
                outs.write(data);
            }
        }
        outs.flush();
    } catch (java.net.SocketException se) {
        MiscUtils.getLogger().error("Error", se);
    } catch (Exception e) {
        MiscUtils.getLogger().error("Error", e);
    } finally {
        if (bfis != null)
            try {
                bfis.close();
            } catch (IOException e) {
            }
        if (outs != null)
            try {
                outs.close();
            } catch (IOException e) {
            }
    }
    return null;
}

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

/**
 * Display EDNA results content on the page
 * //from   ww  w.  j a va  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

/**
 * forward to the page displaying a edna file
 * //from www  . jav  a  2 s. com
 * @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

/**
 * getDataFromFile/*from  w  ww. java2s  .  c o m*/
 * 
 * @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");

}