Example usage for org.apache.poi.util IOUtils copy

List of usage examples for org.apache.poi.util IOUtils copy

Introduction

In this page you can find the example usage for org.apache.poi.util IOUtils copy.

Prototype

public static long copy(InputStream srcStream, File destFile) throws IOException 

Source Link

Document

Copy the contents of the stream to a new file.

Usage

From source file:cdiscisa.StreamUtil.java

public static File stream2file(InputStream in) throws IOException {
        final File tempFile = File.createTempFile(PREFIX, SUFFIX);
        tempFile.deleteOnExit();/*from  w  ww .j  a  va  2  s.  c  om*/
        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            IOUtils.copy(in, out);
        }
        return tempFile;
    }

From source file:com.ezdi.rtf.testRTFParser.RTFObjDataParser.java

License:Apache License

private byte[] handleEmbeddedPOIFS(InputStream is, Metadata metadata, AtomicInteger unknownFilenameCount)
        throws IOException {

    byte[] ret = null;
    try (NPOIFSFileSystem fs = new NPOIFSFileSystem(is)) {

        DirectoryNode root = fs.getRoot();

        if (root == null) {
            return ret;
        }/*w w w .  j  a  v a 2 s  .c om*/

        if (root.hasEntry("Package")) {
            Entry ooxml = root.getEntry("Package");
            TikaInputStream stream = TikaInputStream.get(new DocumentInputStream((DocumentEntry) ooxml));

            ByteArrayOutputStream out = new ByteArrayOutputStream();

            IOUtils.copy(stream, out);
            ret = out.toByteArray();
        } else {
            // try poifs
            POIFSDocumentType type = POIFSDocumentType.detectType(root);
            if (type == POIFSDocumentType.OLE10_NATIVE) {
                try {
                    // Try to un-wrap the OLE10Native record:
                    Ole10Native ole = Ole10Native.createFromEmbeddedOleObject(root);
                    ret = ole.getDataBuffer();
                } catch (Ole10NativeException ex) {
                    // Not a valid OLE10Native record, skip it
                }
            } else if (type == POIFSDocumentType.COMP_OBJ) {

                DocumentEntry contentsEntry;
                try {
                    contentsEntry = (DocumentEntry) root.getEntry("CONTENTS");
                } catch (FileNotFoundException ioe) {
                    contentsEntry = (DocumentEntry) root.getEntry("Contents");
                }

                try (DocumentInputStream inp = new DocumentInputStream(contentsEntry)) {
                    ret = new byte[contentsEntry.getSize()];
                    inp.readFully(ret);
                }
            } else {

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                is.reset();
                IOUtils.copy(is, out);
                ret = out.toByteArray();
                metadata.set(Metadata.RESOURCE_NAME_KEY,
                        "file_" + unknownFilenameCount.getAndIncrement() + "." + type.getExtension());
                metadata.set(Metadata.CONTENT_TYPE, type.getType().toString());
            }
        }
    }
    return ret;
}

From source file:com.github.poi.AesZipFileZipEntrySource.java

License:Apache License

private static void copyToFile(InputStream is, File tmpFile, CipherAlgorithm cipherAlgorithm, byte keyBytes[],
        byte ivBytes[]) throws IOException, GeneralSecurityException {
    SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId);
    Cipher ciEnc = CryptoFunctions.getCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes,
            Cipher.ENCRYPT_MODE, "PKCS5Padding");

    ZipInputStream zis = new ZipInputStream(is);
    FileOutputStream fos = new FileOutputStream(tmpFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    ZipEntry ze;/*from w  w  w  . j av a  2  s  .  c o m*/
    while ((ze = zis.getNextEntry()) != null) {
        // the cipher output stream pads the data, therefore we can't reuse the ZipEntry with set sizes
        // as those will be validated upon close()
        ZipEntry zeNew = new ZipEntry(ze.getName());
        zeNew.setComment(ze.getComment());
        zeNew.setExtra(ze.getExtra());
        zeNew.setTime(ze.getTime());
        // zeNew.setMethod(ze.getMethod());
        zos.putNextEntry(zeNew);
        FilterOutputStream fos2 = new FilterOutputStream(zos) {
            // don't close underlying ZipOutputStream
            @Override
            public void close() {
            }
        };
        CipherOutputStream cos = new CipherOutputStream(fos2, ciEnc);
        IOUtils.copy(zis, cos);
        cos.close();
        fos2.close();
        zos.closeEntry();
        zis.closeEntry();
    }
    zos.close();
    fos.close();
    zis.close();
}

From source file:com.googlecode.fascinator.common.storage.impl.GenericPayload.java

License:Open Source License

/**
 * Sets the input stream to access the content for this payload. Note this
 * stores the stream into memory, proper Payload implementations should
 * override this method./*from  ww w . j  a  v  a2 s  . c  o m*/
 * 
 * @param in the content input stream
 */
public void setInputStream(InputStream in) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        IOUtils.copy(in, out);
        ramStore = out.toByteArray();
        setContentType(MimeTypeUtil.getMimeType(ramStore, getId()));
    } catch (Exception e) {
        log.error("Failed to copy content to memory", e);
    } finally {
        try {
            in.close();
        } catch (IOException ioe) {
            log.error("Failed to close content input stream", ioe);
        }
    }
}

From source file:com.googlecode.fascinator.storage.fedora.Fedora36DigitalObject.java

License:Open Source License

/**
 * Turn an InputStream into a temporary File for uploading.
 *
 * @param pid//w  w  w. j a  v a2  s .  com
 *            the local Fascinator Payload ID used in creating a temp file
 * @param in
 *            an InputStream containing the data to upload
 * @return File the new temporary File, NULL if there is an error
 */
private File createTempFile(String pid, InputStream in) {
    File tempFile = null;
    FileOutputStream out = null;

    pid = escapeSpaces(pid);
    // Work out a robust temp file name
    // TODO: 20th Oct 2011: Do we still need this? Leaving it in for now.
    String prefix = FilenameUtils.getBaseName(pid);
    String suffix = FilenameUtils.getExtension(pid);
    prefix = StringUtils.rightPad(prefix, 3, "_");
    suffix = "".equals(suffix) ? null : "." + suffix;
    try {
        // Create and access our empty file in temp space
        tempFile = File.createTempFile(prefix, suffix);
        out = new FileOutputStream(tempFile);
        // Stream the data into storage
        IOUtils.copy(in, out);
    } catch (IOException ex) {
        log.error("Error creating temp file: ", ex);
        return null;
    } finally {
        Fedora36.close(in);
        Fedora36.close(out);
    }

    return tempFile;
}

From source file:com.googlecode.fascinator.storage.fedora.Fedora3DigitalObject.java

License:Open Source License

/**
 * Turn an InputStream into a temporary File for uploading.
 * //from   w  w w. j  a  va  2s.c  o m
 * @param pid the local Fascinator Payload ID used in creating a temp file
 * @param in an InputStream containing the data to upload
 * @return File the new temporary File, NULL if there is an error
 */
private File createTempFile(String pid, InputStream in) {
    File tempFile = null;
    FileOutputStream out = null;

    // Work out a robust temp file name
    // TODO: 20th Oct 2011: Do we still need this? Leaving it in for now.
    String prefix = FilenameUtils.getBaseName(pid);
    String suffix = FilenameUtils.getExtension(pid);
    prefix = StringUtils.rightPad(prefix, 3, "_");
    suffix = "".equals(suffix) ? null : "." + suffix;
    try {
        // Create and access our empty file in temp space
        tempFile = File.createTempFile(prefix, suffix);
        out = new FileOutputStream(tempFile);
        // Stream the data into storage
        IOUtils.copy(in, out);
    } catch (IOException ex) {
        log.error("Error creating temp file: ", ex);
        return null;
    } finally {
        Fedora3.close(in);
        Fedora3.close(out);
    }

    return tempFile;
}

From source file:com.hp.autonomy.frontend.reports.powerpoint.PowerPointServiceImpl.java

License:MIT License

/**
 * Utility function to write a chart object to a slide based on a template.
 * Creates new copies of referred objects in the chart, e.g. colors1.xml and style1.xml, and writes the Excel
 *   workbook data to new files in the PowerPoint .zip structure.
 * @param pptx the presentation to add to.
 * @param slide the slide to add to.//from  ww  w.ja  va  2 s  . c om
 * @param templateChart the original template chart XML reference object from the template.
 * @param modifiedChart the new chart XML object.
 * @param workbook the Excel workbook data corresponding to the chart XML data.
 * @param relId the relation id for the new chart.
 * @throws IOException if there's IO errors working with the chart.
 * @throws InvalidFormatException if there's errors generating new package part names for the new copies of the data.
 */
private static void writeChart(final XMLSlideShow pptx, final XSLFSlide slide, final XSLFChart templateChart,
        final CTChartSpace modifiedChart, final XSSFWorkbook workbook, final String relId)
        throws IOException, InvalidFormatException {
    final OPCPackage opcPackage = pptx.getPackage();
    final PackagePartName chartName = generateNewName(opcPackage,
            templateChart.getPackagePart().getPartName().getURI().getPath());

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
    xmlOptions.setSaveSyntheticDocumentElement(
            new QName(CTChartSpace.type.getName().getNamespaceURI(), "chartSpace", "c"));
    modifiedChart.save(baos, xmlOptions);

    final PackagePart chartPart = opcPackage.createPart(chartName, XSLFRelation.CHART.getContentType(), baos);

    slide.getPackagePart().addRelationship(chartName, TargetMode.INTERNAL, XSLFRelation.CHART.getRelation(),
            relId);

    for (final POIXMLDocumentPart.RelationPart part : templateChart.getRelationParts()) {
        final ByteArrayOutputStream partCopy = new ByteArrayOutputStream();
        final URI targetURI = part.getRelationship().getTargetURI();

        final PackagePartName name = generateNewName(opcPackage, targetURI.getPath());

        final String contentType = part.getDocumentPart().getPackagePart().getContentType();

        if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType)) {
            workbook.write(partCopy);
        } else {
            IOUtils.copy(part.getDocumentPart().getPackagePart().getInputStream(), partCopy);
        }

        opcPackage.createPart(name, contentType, partCopy);
        chartPart.addRelationship(name, TargetMode.INTERNAL, part.getRelationship().getRelationshipType());
    }
}

From source file:com.hp.autonomy.frontend.reports.powerpoint.WebAndDataUriImageSource.java

License:MIT License

/**
 * Accepts HTTP/HTTPs URLs or base64-encoded image data and converts them to image data.
 * @param imageId the image identifier.//  www.  ja v  a 2s.c o  m
 * @return image data corresponding to the image.
 * @throws IllegalArgumentException if we can't fetch the image.
 */
@Override
public ImageData getImageData(final String imageId) throws IllegalArgumentException {
    if (imageId.startsWith("https:") || imageId.startsWith("http:")) {
        try {
            final URI uri = new URI(imageId);

            if (allowHttpURI(uri)) {
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();

                final HttpURLConnection conn = (HttpURLConnection) new URL(imageId).openConnection();
                conn.connect();
                final String contentType = conn.getContentType();

                for (final PictureData.PictureType pictureType : PictureData.PictureType.values()) {
                    if (pictureType.contentType.equalsIgnoreCase(contentType)) {
                        try (final InputStream input = conn.getInputStream()) {
                            IOUtils.copy(input, baos);
                            return new ImageData(pictureType, baos.toByteArray());
                        }
                    }
                }

                throw new IllegalArgumentException(
                        "Selected image URI uses an unsupported content type: " + imageId);
            }
        } catch (URISyntaxException | IOException e) {
            throw new IllegalArgumentException("Selected image URI cannot be fetched: " + imageId, e);
        }

        throw new IllegalArgumentException("Selected image cannot be fetched: " + imageId);
    } else {
        return super.getImageData(imageId);
    }
}

From source file:com.jaeksoft.searchlib.crawler.cache.HadoopCrawlCache.java

License:Open Source License

private void write(Path path, InputStream in) throws IOException {
    FSDataOutputStream out = fileSystem.create(path, true);
    try {/*w w w . ja va 2  s  . co  m*/
        IOUtils.copy(in, out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.jslsolucoes.tagria.lib.grid.exporter.impl.CsvExporter.java

License:Apache License

public void doExport(OutputStream outputStream) throws IOException {
    IOUtils.copy(export(), outputStream);
}