Example usage for org.apache.commons.io FileUtils openInputStream

List of usage examples for org.apache.commons.io FileUtils openInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils openInputStream.

Prototype

public static FileInputStream openInputStream(File file) throws IOException 

Source Link

Document

Opens a FileInputStream for the specified file, providing better error messages than simply calling new FileInputStream(file).

Usage

From source file:org.sakaiproject.signup.tool.jsf.SignupUIBaseBean.java

/**
 * Send a file for download. // w  w  w  . ja v a2s  . c  o  m
 * 
 * @param filePath
 * 
 */
protected void sendDownload(String filePath, String mimeType) {

    FacesContext fc = FacesContext.getCurrentInstance();
    ServletOutputStream out = null;
    FileInputStream in = null;

    String filename = StringUtils.substringAfterLast(filePath, File.separator);

    try {
        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

        response.reset();
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0");
        response.setContentType(mimeType);
        response.setHeader("Content-disposition", "attachment; filename=" + filename);

        in = FileUtils.openInputStream(new File(filePath));
        out = response.getOutputStream();

        IOUtils.copy(in, out);

        out.flush();
    } catch (IOException ex) {
        logger.warn("Error generating file for download:" + ex.getMessage());
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
    fc.responseComplete();

}

From source file:org.sead.repositories.reference.RefRepository.java

@Path("/researchobjects/{id}/bag")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@GET//from  ww  w.j  a  v  a 2s . c  o m
public Response getBag(@PathParam(value = "id") String id) {

    String path = getDataPathTo(id);
    String bagNameRoot = getBagNameRoot(id);

    File result = new File(path, bagNameRoot + ".zip");
    try {
        final InputStream inputStream = FileUtils.openInputStream(result);

        StreamingOutput stream = new StreamingOutput() {
            public void write(OutputStream os) throws IOException, WebApplicationException {
                IOUtils.copy(inputStream, os);
                IOUtils.closeQuietly(inputStream);
            }
        };

        return Response.ok(stream).build();
    } catch (IOException e) {
        e.printStackTrace();
        return Response.serverError().build();
    }
}

From source file:org.silverpeas.attachment.repository.DocumentRepository.java

/**
 * Get the content./*w ww .jav a  2 s  .  co  m*/
 *
 * @param session the current JCR session.
 * @param pk the document which content is to be added.
 * @param lang the content language.
 * @return the attachment binary content.
 * @throws RepositoryException
 * @throws IOException
 */
public InputStream getContent(Session session, SimpleDocumentPK pk, String lang)
        throws RepositoryException, IOException {
    Node docNode = session.getNodeByIdentifier(pk.getId());
    String language = lang;
    if (!StringUtil.isDefined(language)) {
        language = I18NHelper.defaultLanguage;
    }
    SimpleDocument document = converter.fillDocument(docNode, language);
    return new BufferedInputStream(FileUtils.openInputStream(new File(document.getAttachmentPath())));
}

From source file:org.silverpeas.attachment.webdav.impl.WebdavDocumentRepository.java

private void setContent(Node fileNode, SimpleDocument attachment) throws RepositoryException, IOException {
    InputStream in = FileUtils.openInputStream(new File(attachment.getAttachmentPath()));
    try {//from w  w  w .jav a 2  s. co m
        Binary attachmentBinary = fileNode.getSession().getValueFactory().createBinary(in);
        fileNode.getNode(JCR_CONTENT).setProperty(JCR_DATA, attachmentBinary);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.silverpeas.components.gallery.web.AbstractGalleryResource.java

private Response.ResponseBuilder loadFileContent(final File file) {
    StreamingOutput streamingOutput = output -> {
        try (final InputStream mediaStream = FileUtils.openInputStream(file)) {
            IOUtils.copy(mediaStream, output);
        } catch (IOException e) {
            throw new WebApplicationException(e, Status.NOT_FOUND);
        }/*ww w.ja  v  a2s.  c  o m*/
    };
    return Response.ok(streamingOutput);
}

From source file:org.silverpeas.core.contribution.attachment.repository.DocumentRepository.java

/**
 * Get the content.//from ww  w .j ava  2  s. c  o m
 *
 * @param session the current JCR session.
 * @param pk the document which content is to be added.
 * @param lang the content language.
 * @return the attachment binary content.
 * @throws RepositoryException
 * @throws IOException
 */
public InputStream getContent(Session session, SimpleDocumentPK pk, String lang)
        throws RepositoryException, IOException {
    Node docNode = session.getNodeByIdentifier(pk.getId());
    String language = lang;
    if (!StringUtil.isDefined(language)) {
        language = defaultLanguage;
    }
    SimpleDocument document = converter.fillDocument(docNode, language);
    return new BufferedInputStream(FileUtils.openInputStream(new File(document.getAttachmentPath())));
}

From source file:org.silverpeas.core.io.file.SilverpeasFile.java

/**
 * Opens and returns an input stream to this file.
 * @return a buffered input stream to this file.
 * @throws IOException if an error occurs while opening the input stream.
 *///from  www  .ja va 2s.co  m
public InputStream inputStream() throws IOException {
    return new BufferedInputStream(FileUtils.openInputStream(this));
}

From source file:org.silverpeas.core.process.io.file.FileHandler.java

/**
 * @see FileUtils//from  ww  w.  jav a  2  s . c  om
 */
protected InputStream openInputStream(final FileBasePath basePath, final File file) throws Exception {
    verify(basePath, file);
    final File sessionFile = translateToSessionPath(basePath, file);
    if (sessionFile.exists()) {
        return FileUtils.openInputStream(sessionFile);
    }
    return FileUtils.openInputStream(translateToRealPath(basePath, file));
}

From source file:org.silverpeas.core.util.PdfUtil.java

/**
 * Gets some document info from a PDF file.
 * @param pdfSource the source pdf file, this content is not modified by this method
 * @return a {@link DocumentInfo} instance.
 *//*from  w w  w .j a  v a2  s .  c  o  m*/
public static DocumentInfo getDocumentInfo(File pdfSource) {
    if (pdfSource == null || !pdfSource.isFile()) {
        throw new SilverpeasRuntimeException(PDF_FILE_ERROR_MSG);
    } else if (!FileUtil.isPdf(pdfSource.getPath())) {
        throw new SilverpeasRuntimeException(NOT_PDF_FILE_ERROR_MSG);
    }
    PdfReader reader = null;
    try (final InputStream pdfSourceIS = FileUtils.openInputStream(pdfSource)) {
        reader = new PdfReader(pdfSourceIS);
        final DocumentInfo documentInfo = new DocumentInfo();
        documentInfo.setNbPages(reader.getNumberOfPages());
        for (int i = 1; i <= documentInfo.getNbPages(); i++) {
            final Rectangle rectangle = reader.getPageSize(i);
            final int maxWidth = Math.round(rectangle.getWidth());
            final int maxHeight = Math.round(rectangle.getHeight());
            if (maxWidth > documentInfo.getMaxWidth()) {
                documentInfo.setMaxWidth(maxWidth);
            }
            if (maxHeight > documentInfo.getMaxHeight()) {
                documentInfo.setMaxHeight(maxHeight);
            }
        }
        return documentInfo;
    } catch (Exception e) {
        SilverLogger.getLogger(PdfUtil.class).error(e);
        throw new SilverpeasRuntimeException("A problem has occurred during the reading of a pdf file", e);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.silverpeas.core.util.PdfUtil.java

/**
 * Add a image under or over content on each page of a PDF file.
 * @param pdfSource the source pdf file, this content is not modified by this method
 * @param image the image file//  w  ww .  j av  a 2 s  . c  om
 * @param pdfDestination the destination pdf file, with the image under or over content
 * @param isBackground indicates if image is addes under or over the content of the pdf source
 * file
 */
private static void addImageOnEachPage(File pdfSource, File image, File pdfDestination,
        final boolean isBackground) {
    if (pdfSource == null || !pdfSource.isFile()) {
        throw new SilverpeasRuntimeException(PDF_FILE_ERROR_MSG);
    } else if (!FileUtil.isPdf(pdfSource.getPath())) {
        throw new SilverpeasRuntimeException(NOT_PDF_FILE_ERROR_MSG);
    } else if (pdfDestination == null) {
        throw new SilverpeasRuntimeException(PDF_DESTINATION_ERROR_MSG);
    }

    FileInputStream pdfSourceIS = null;
    FileOutputStream pdfDestinationIS = null;
    try {
        pdfSourceIS = FileUtils.openInputStream(pdfSource);
        pdfDestinationIS = FileUtils.openOutputStream(pdfDestination);
        addImageOnEachPage(pdfSourceIS, image, pdfDestinationIS, isBackground);
    } catch (IOException e) {
        throw new SilverpeasRuntimeException(
                "Pdf source file cannot be opened or pdf destination file cannot be created", e);
    } finally {
        IOUtils.closeQuietly(pdfSourceIS);
        IOUtils.closeQuietly(pdfDestinationIS);
    }
}