Example usage for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem

List of usage examples for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem

Introduction

In this page you can find the example usage for org.apache.poi.poifs.filesystem POIFSFileSystem POIFSFileSystem.

Prototype

public POIFSFileSystem() 

Source Link

Document

Constructor, intended for writing

Usage

From source file:com.vodafone.poms.ii.helpers.ExportManager.java

private static String addFile(XSSFSheet sh, String filePath, double oleId)
        throws IOException, InvalidFormatException {
    File file = new File(filePath);
    FileInputStream fin = new FileInputStream(file);
    byte[] data;/*w w w.j  a  v a2 s.  co  m*/
    data = new byte[fin.available()];
    fin.read(data);
    Ole10Native ole10 = new Ole10Native(file.getAbsolutePath(), file.getAbsolutePath(), file.getAbsolutePath(),
            data);

    ByteArrayOutputStream bos = new ByteArrayOutputStream(500);
    ole10.writeOut(bos);

    POIFSFileSystem poifs = new POIFSFileSystem();
    poifs.getRoot().createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(bos.toByteArray()));

    poifs.getRoot().setStorageClsid(ClassID.OLE10_PACKAGE);

    final PackagePartName pnOLE = PackagingURIHelper
            .createPartName("/xl/embeddings/oleObject" + oleId + Math.random() + ".bin");
    final PackagePart partOLE = sh.getWorkbook().getPackage().createPart(pnOLE,
            "application/vnd.openxmlformats-officedocument.oleObject");
    PackageRelationship prOLE = sh.getPackagePart().addRelationship(pnOLE, TargetMode.INTERNAL,
            POIXMLDocument.OLE_OBJECT_REL_TYPE);
    OutputStream os = partOLE.getOutputStream();
    poifs.writeFilesystem(os);
    os.close();
    poifs.close();

    return prOLE.getId();

}

From source file:de.jlo.talendcomp.excel.SpreadsheetFile.java

License:Apache License

private static void encryptFile(String inFilePath, String outFilePath, String password) throws Exception {
    if (password == null || password.trim().isEmpty()) {
        throw new Exception("Password cannot be null or empty!");
    }// w  w  w . j  a  va2  s . co  m
    if (inFilePath == null || inFilePath.trim().isEmpty()) {
        throw new Exception("Input file cannot be null or empty!");
    }
    File inFile = new File(inFilePath);
    if (outFilePath == null || outFilePath.trim().isEmpty()) {
        throw new Exception("Output file cannot be null or empty!");
    }
    File outFile = new File(outFilePath);
    if (inFile.exists() == false) {
        throw new Exception("Excel file to encrypt: " + inFile.getAbsolutePath() + " does not exists!");
    }
    ensureDirExists(outFile);
    POIFSFileSystem fs = new POIFSFileSystem();
    EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
    Encryptor enc = info.getEncryptor();
    enc.confirmPassword(password);
    OPCPackage opc = OPCPackage.open(inFile, PackageAccess.READ_WRITE);
    OutputStream os = enc.getDataStream(fs);
    opc.save(os);
    opc.close();
    FileOutputStream fos = null;
    Exception ex = null;
    try {
        fos = new FileOutputStream(outFile);
        fs.writeFilesystem(fos);
    } catch (Exception e) {
        ex = e;
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e1) {
                // ignore
            }
        }
    }
    if (ex != null) {
        throw ex;
    }
}

From source file:org.apache.cocoon.serialization.POIFSSerializer.java

License:Apache License

/**
 *  Constructor
 */

public POIFSSerializer() {
    super();
    _filesystem = new POIFSFileSystem();
}

From source file:org.elasticwarehouse.core.parsers.FileEmbeddedDocumentExtractor.java

License:Apache License

public void parseEmbedded(InputStream inputStream, ContentHandler contentHandler, Metadata metadata,
        boolean outputHtml) throws SAXException, IOException {
    String name = metadata.get(Metadata.RESOURCE_NAME_KEY);

    if (name == null) {
        name = "file" + count++;
    }//from  w w  w. j  av  a  2 s.c o  m
    DefaultDetector detector = new DefaultDetector();
    MediaType contentType = detector.detect(inputStream, metadata);

    if (name.indexOf('.') == -1 && contentType != null) {
        try {
            name += config.getMimeRepository().forName(contentType.toString()).getExtension();
        } catch (MimeTypeException e) {
            EWLogger.logerror(e);
            e.printStackTrace();
        }
    }

    String relID = metadata.get(Metadata.EMBEDDED_RELATIONSHIP_ID);
    if (relID != null && !name.startsWith(relID)) {
        name = relID + "_" + name;
    }

    File outputFile = new File(extractDir, FilenameUtils.normalize(name));
    File parent = outputFile.getParentFile();
    if (!parent.exists()) {
        if (!parent.mkdirs()) {
            throw new IOException("unable to create directory \"" + parent + "\"");
        }
    }
    System.out.println("Extracting '" + name + "' (" + contentType + ") to " + outputFile);

    FileOutputStream os = null;

    try {
        os = new FileOutputStream(outputFile);

        if (inputStream instanceof TikaInputStream) {
            TikaInputStream tin = (TikaInputStream) inputStream;

            if (tin.getOpenContainer() != null && tin.getOpenContainer() instanceof DirectoryEntry) {
                POIFSFileSystem fs = new POIFSFileSystem();
                copy((DirectoryEntry) tin.getOpenContainer(), fs.getRoot());
                fs.writeFilesystem(os);
            } else {
                IOUtils.copy(inputStream, os);
            }
        } else {
            IOUtils.copy(inputStream, os);
        }
    } catch (Exception e) {
        //
        // being a CLI program messages should go to the stderr too
        //
        String msg = String.format(Locale.ROOT,
                "Ignoring unexpected exception trying to save embedded file %s (%s)", name, e.getMessage());
        EWLogger.logerror(e);
        System.err.println(msg);
        //logger.warn(msg, e);
    } finally {
        if (os != null) {
            os.close();
        }
    }
}

From source file:poi.hpsf.examples.WriteTitle.java

License:Apache License

/**
 * <p>Runs the example program.</p>
 *
 * @param args Command-line arguments. The first and only command-line 
 * argument is the name of the POI file system to create.
 * @throws java.io.IOException if any I/O exception occurs.
 * @throws WritingNotSupportedException if HPSF does not (yet) support 
 * writing a certain property type.//from  w  w w . j av  a  2 s . c  o m
 */
public static void main(final String[] args) throws WritingNotSupportedException, IOException {
    /* Check whether we have exactly one command-line argument. */
    if (args.length != 1) {
        System.err.println("Usage: " + WriteTitle.class.getName() + "destinationPOIFS");
        System.exit(1);
    }

    final String fileName = args[0];

    /* Create a mutable property set. Initially it contains a single section
     * with no properties. */
    final MutablePropertySet mps = new MutablePropertySet();

    /* Retrieve the section the property set already contains. */
    final MutableSection ms = (MutableSection) mps.getSections().get(0);

    /* Turn the property set into a summary information property. This is
     * done by setting the format ID of its first section to
     * SectionIDMap.SUMMARY_INFORMATION_ID. */
    ms.setFormatID(SectionIDMap.SUMMARY_INFORMATION_ID);

    /* Create an empty property. */
    final MutableProperty p = new MutableProperty();

    /* Fill the property with appropriate settings so that it specifies the
     * document's title. */
    p.setID(PropertyIDMap.PID_TITLE);
    p.setType(Variant.VT_LPWSTR);
    p.setValue("Sample title");

    /* Place the property into the section. */
    ms.setProperty(p);

    /* Create the POI file system the property set is to be written to. */
    final POIFSFileSystem poiFs = new POIFSFileSystem();

    /* For writing the property set into a POI file system it has to be
     * handed over to the POIFS.createDocument() method as an input stream
     * which produces the bytes making out the property set stream. */
    final InputStream is = mps.toInputStream();

    /* Create the summary information property set in the POI file
     * system. It is given the default name most (if not all) summary
     * information property sets have. */
    poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME);

    /* Write the whole POI file system to a disk file. */
    poiFs.writeFilesystem(new FileOutputStream(fileName));
}

From source file:tv.amwa.maj.io.aaf.AAFBuilder.java

License:Apache License

/**
 * @param args/*from w  w  w.j  av a  2 s.  com*/
 */
public static void main(String[] args) throws IOException {

    if (args.length != 2)
        System.exit(1);

    final String inputFilename = args[0];
    final String outputFilename = args[1];

    POIFSReader r = new AAFReader();

    LocalAAFEventReader eventReader = new LocalAAFEventReader();
    r.registerListener(eventReader);

    AvidFactory.registerAvidExtensions();

    FileInputStream fis = null;

    long startTime = System.nanoTime();
    try {
        fis = new FileInputStream(inputFilename);
        r.read(new FileInputStream(inputFilename));
        eventReader.resolveEntries();
    } finally {
        if (fis != null)
            try {
                fis.close();
            } catch (Exception e) {
            }
    }
    long endTime = System.nanoTime();

    System.out.println("AAF file read in " + (endTime - startTime) + "ns.");

    ((PrefaceImpl) eventReader.getPreface()).setByteOrder(tv.amwa.maj.enumeration.ByteOrder.Big);
    System.out.println(eventReader.getPreface().getByteOrder());

    POIFSFileSystem outputFileSystem = new POIFSFileSystem();

    DirectoryEntry rootDir = outputFileSystem.getRoot();

    AAFWriterListener aafWriter = makeAAFWriterListener();
    DirectoryEntry metaDictionaryDir = rootDir.createDirectory(META_DICTIONARY_DIRNAME);
    DirectoryEntry prefaceDir = rootDir.createDirectory(PREFACE_DIRNAME);

    generateAAFStructure(prefaceDir, aafWriter, eventReader.getPreface());
    generateMetaDictionary(metaDictionaryDir, aafWriter, eventReader.getPreface());
    rootDir.createDocument(PROPERTIES_STREAMNAME, 70, aafWriter);
    rootDir.createDocument(REFERENCED_PROPERTIES_STREAMNAME, aafWriter.getReferencedPropertiesSize(),
            aafWriter);

    //       rootDir.setStorageClsid(
    //             (outputFileSystem.getBigBlockSize() == 4096) ?
    //                   new AAFClassID(AAFSignatureSSBin4K) :
    //                      new AAFClassID(AAFSignatureSSBinary));

    rootDir.setStorageClsid(new ClassID(rootEntryClassID, 0));

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(outputFilename);
        outputFileSystem.writeFilesystem(fos);
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (Exception e) {
            }
    }

    // AAF puts a signature in bytes 8-23 of the file
    // POIFS cannot write this

    RandomAccessFile fixFile = null;
    FileChannel fixChannel = null;
    try {
        fixFile = new RandomAccessFile(outputFilename, "rw");
        fixChannel = fixFile.getChannel();

        fixChannel.position(8);
        if (outputFileSystem.getBigBlockSize() == 4096)
            fixChannel.write(ByteBuffer.wrap(AAFSignatureSSBin4KBytes));
        else
            fixChannel.write(ByteBuffer.wrap(AAFSignatureSSBinaryBytes));
    } finally {
        if (fixChannel != null)
            fixChannel.close();
    }
}

From source file:tv.amwa.maj.io.aaf.AAFFactory.java

License:Apache License

/**
 * <p>Write an AAF file with the given filename that is constructed from the given {@linkplain Preface preface}.<p>
 * /* ww w  . ja v a 2s.  com*/
 * <p>Note that this version of MAJ only supports writing metadata-only files.</p>
 * 
 * @param preface Preface to use to construct an AAF file from.
 * @param outputFilename File path specification for the file to write the preface to.
 * 
 * @throws IOException An error occurred when writing the AAF file.
 * 
 * @see #readPreface(String)
 */
public final static void writePreface(Preface preface, String outputFilename) throws IOException {

    POIFSFileSystem outputFileSystem = new POIFSFileSystem();

    DirectoryEntry rootDir = outputFileSystem.getRoot();

    preface.updateDictionaries();
    //       System.out.println(preface);

    AAFWriterListener aafWriter = AAFBuilder.makeAAFWriterListener();
    DirectoryEntry metaDictionaryDir = rootDir.createDirectory(META_DICTIONARY_DIRNAME);
    DirectoryEntry prefaceDir = rootDir.createDirectory(PREFACE_DIRNAME);

    AAFBuilder.generateAAFStructure(prefaceDir, aafWriter, preface);
    AAFBuilder.generateMetaDictionary(metaDictionaryDir, aafWriter, preface);
    rootDir.createDocument(PROPERTIES_STREAMNAME, 70, aafWriter);
    rootDir.createDocument(REFERENCED_PROPERTIES_STREAMNAME, aafWriter.getReferencedPropertiesSize(),
            aafWriter);

    //       rootDir.setStorageClsid(
    //             (outputFileSystem.getBigBlockSize() == 4096) ?
    //                   new AAFClassID(AAFSignatureSSBin4K) :
    //                      new AAFClassID(AAFSignatureSSBinary));

    rootDir.setStorageClsid(new ClassID(rootEntryClassID, 0));

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(outputFilename);
        outputFileSystem.writeFilesystem(fos);
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (Exception e) {
            }
    }

    // AAF puts a signature in bytes 8-23 of the file
    // POIFS cannot write this

    RandomAccessFile fixFile = null;
    FileChannel fixChannel = null;
    try {
        fixFile = new RandomAccessFile(outputFilename, "rw");
        fixChannel = fixFile.getChannel();

        fixChannel.position(8);
        if (outputFileSystem.getBigBlockSize() == 4096)
            fixChannel.write(ByteBuffer.wrap(AAFSignatureSSBin4KBytes));
        else
            fixChannel.write(ByteBuffer.wrap(AAFSignatureSSBinaryBytes));
    } finally {
        if (fixChannel != null)
            fixChannel.close();
    }
}