Java Code Examples for org.apache.poi.poifs.filesystem.NPOIFSFileSystem

The following examples show how to use org.apache.poi.poifs.filesystem.NPOIFSFileSystem. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: lams   Source File: OLE2ExtractorFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static POITextExtractor createExtractor(InputStream input) throws IOException {
    Class<?> cls = getOOXMLClass();
    if (cls != null) {
        // Use Reflection to get us the full OOXML-enabled version
        try {
            Method m = cls.getDeclaredMethod("createExtractor", InputStream.class);
            return (POITextExtractor)m.invoke(null, input);
        } catch (IllegalArgumentException iae) {
            throw iae;
        } catch (Exception e) {
            throw new IllegalArgumentException("Error creating Extractor for InputStream", e);
        }
    } else {
        // Best hope it's OLE2....
        return createExtractor(new NPOIFSFileSystem(input));
    }
}
 
Example 2
Source Project: lams   Source File: POIFSDump.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void dump(NPOIFSFileSystem fs, int startBlock, String name, File parent) throws IOException {
    File file = new File(parent, name);
    FileOutputStream out = new FileOutputStream(file);
    try {
        NPOIFSStream stream = new NPOIFSStream(fs, startBlock);

        byte[] b = new byte[fs.getBigBlockSize()];
        for (ByteBuffer bb : stream) {
            int len = bb.remaining();
            bb.get(b);
            out.write(b, 0, len);
        }
    } finally {
        out.close();
    }
}
 
Example 3
Source Project: lams   Source File: POIFSViewer.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void viewFile(String filename, boolean printName) {
    if (printName) {
        StringBuffer flowerbox = new StringBuffer();

        flowerbox.append(".");
        for (int j = 0; j < filename.length(); j++) {
            flowerbox.append("-");
        }
        flowerbox.append(".");
        System.out.println(flowerbox);
        System.out.println("|" + filename + "|");
        System.out.println(flowerbox);
    }
    try {
        NPOIFSFileSystem fs = new NPOIFSFileSystem(new File(filename));
        List<String> strings = POIFSViewEngine.inspectViewable(fs, true, 0, "  ");
        for (String s : strings) {
            System.out.print(s);
        }
        fs.close();
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}
 
Example 4
Source Project: lams   Source File: VBAMacroReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void openOOXML(InputStream zipFile) throws IOException {
    ZipInputStream zis = new ZipInputStream(zipFile);
    ZipEntry zipEntry;
    while ((zipEntry = zis.getNextEntry()) != null) {
        if (endsWithIgnoreCase(zipEntry.getName(), VBA_PROJECT_OOXML)) {
            try {
                // Make a NPOIFS from the contents, and close the stream
                this.fs = new NPOIFSFileSystem(zis);
                return;
            } catch (IOException e) {
                // Tidy up
                zis.close();
                
                // Pass on
                throw e;
            }
        }
    }
    zis.close();
    throw new IllegalArgumentException("No VBA project found");
}
 
Example 5
Source Project: lams   Source File: POIDocument.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Writes out a given ProperySet
 * @param name the (POIFS Level) name of the property to write
 * @param set the PropertySet to write out 
 * @param outFS the NPOIFSFileSystem to write the property into
 * 
 * @throws IOException if an error when writing to the 
 *      {@link NPOIFSFileSystem} occurs
 */
protected void writePropertySet(String name, PropertySet set, NPOIFSFileSystem outFS) throws IOException {
    try {
        PropertySet mSet = new PropertySet(set);
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        mSet.write(bOut);
        byte[] data = bOut.toByteArray();
        ByteArrayInputStream bIn = new ByteArrayInputStream(data);

        // Create or Update the Property Set stream in the POIFS
        outFS.createOrUpdateDocument(bIn, name);

        logger.log(POILogger.INFO, "Wrote property set " + name + " of size " + data.length);
    } catch(org.apache.poi.hpsf.WritingNotSupportedException wnse) {
        logger.log( POILogger.ERROR, "Couldn't write property set with name " + name + " as not supported by HPSF yet");
    }
}
 
Example 6
Source Project: lams   Source File: FormulaViewer.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method run
 * 
 * @throws IOException if the file contained errors 
 */
public void run() throws IOException {
    NPOIFSFileSystem fs  = new NPOIFSFileSystem(new File(file), true);
    try {
        InputStream is = BiffViewer.getPOIFSInputStream(fs);
        try {
            List<Record> records = RecordFactory.createRecords(is);

            for (Record record : records) {
                if (record.getSid() == FormulaRecord.sid) {
                    if (list) {
                        listFormula((FormulaRecord) record);
                    } else {
                        parseFormulaRecord((FormulaRecord) record);
                    }
                }
            }
        } finally {
            is.close();
        }
    } finally {
        fs.close();
    }
}
 
Example 7
Source Project: lams   Source File: EFBiffViewer.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void run() throws IOException {
    NPOIFSFileSystem fs   = new NPOIFSFileSystem(new File(file), true);
    try {
        InputStream     din   = BiffViewer.getPOIFSInputStream(fs);
        try {
            HSSFRequest     req   = new HSSFRequest();
    
            req.addListenerForAllRecords(new HSSFListener()
            {
                public void processRecord(Record rec)
                {
                    System.out.println(rec);
                }
            });
            HSSFEventFactory factory = new HSSFEventFactory();
    
            factory.processEvents(req, din);
        } finally {
            din.close();
        }
    } finally {
        fs.close();
    }
}
 
Example 8
Source Project: lams   Source File: OldExcelExtractor.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void open(InputStream biffStream) throws IOException {
    BufferedInputStream bis = (biffStream instanceof BufferedInputStream) 
        ? (BufferedInputStream)biffStream
        : new BufferedInputStream(biffStream, 8);

    if (NPOIFSFileSystem.hasPOIFSHeader(bis)) {
        NPOIFSFileSystem poifs = new NPOIFSFileSystem(bis);
        try {
            open(poifs);
        } finally {
            poifs.close();
        }
    } else {
        ris = new RecordInputStream(bis);
        toClose = bis;
        prepare();
    }
}
 
Example 9
Source Project: lams   Source File: DrawingDump.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main( String[] args ) throws IOException {
    OutputStreamWriter osw = new OutputStreamWriter(System.out, Charset.defaultCharset());
    PrintWriter pw = new PrintWriter(osw);
    NPOIFSFileSystem fs = new NPOIFSFileSystem(new File(args[0]));
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    try {
        pw.println( "Drawing group:" );
        wb.dumpDrawingGroupRecords(true);

        int i = 1;
        for (Sheet sheet : wb)
        {
            pw.println( "Sheet " + i + "(" + sheet.getSheetName() + "):" );
            ((HSSFSheet) sheet).dumpDrawingRecords(true, pw);
        }
    } finally {
        wb.close();
        fs.close();
    }
}
 
Example 10
Source Project: hop   Source File: PoiWorkbook.java    License: Apache License 2.0 5 votes vote down vote up
public PoiWorkbook( String filename, String encoding ) throws HopException {
  this.filename = filename;
  this.encoding = encoding;
  this.log = HopLogStore.getLogChannelFactory().create( this );
  try {
    FileObject fileObject = HopVfs.getFileObject( filename );
    if ( fileObject instanceof LocalFile ) {
      // This supposedly shaves off a little bit of memory usage by allowing POI to randomly access data in the file
      //
      String localFilename = HopVfs.getFilename( fileObject );
      File excelFile = new File( localFilename );
      try {
        npoifs = new NPOIFSFileSystem( excelFile );
        workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create( npoifs );
      } catch ( Exception ofe ) {
        try {
          opcpkg = OPCPackage.open( excelFile );
          workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create( opcpkg );
        } catch ( Exception ex ) {
          workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create( excelFile );
        }
      }
    } else {
      internalIS = HopVfs.getInputStream( filename );
      workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create( internalIS );
    }
  } catch ( Exception e ) {
    throw new HopException( e );
  }
}
 
Example 11
Source Project: lams   Source File: HPSFPropertiesExtractor.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    for (String file : args) {
        HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(
                new NPOIFSFileSystem(new File(file)));
        try {
            System.out.println(ext.getText());
        } finally {
            ext.close();
        }
    }
}
 
Example 12
/**
 * Write out to the currently open file the properties changes, but nothing else
 */
public void write() throws IOException {
    NPOIFSFileSystem fs = getDirectory().getFileSystem();
    
    validateInPlaceWritePossible();        
    writeProperties(fs, null);
    fs.writeFilesystem();
}
 
Example 13
/**
 * Write out, with any properties changes, but nothing else
 */
public void write(OutputStream out) throws IOException {
    NPOIFSFileSystem fs = new NPOIFSFileSystem();
    try {
        write(fs);
        fs.writeFilesystem(out);
    } finally {
        fs.close();
    }
}
 
Example 14
private void write(NPOIFSFileSystem fs) throws IOException {
    // For tracking what we've written out, so far
    List<String> excepts = new ArrayList<String>(2);

    // Write out our HPFS properties, with any changes
    writeProperties(fs, excepts);
    
    // Copy over everything else unchanged
    FilteringDirectoryNode src = new FilteringDirectoryNode(getDirectory(), excepts);
    FilteringDirectoryNode dest = new FilteringDirectoryNode(fs.getRoot(), excepts);
    EntryUtils.copyNodes(src, dest);
    
    // Caller will save the resultant POIFSFileSystem to the stream/file
}
 
Example 15
Source Project: lams   Source File: SlideShowFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a SlideShow from the given NPOIFSFileSystem, which may
 * be password protected
 *
 * @param fs The {@link NPOIFSFileSystem} to read the document from
 * @param password The password that should be used or null if no password is necessary.
 *
 * @return The created SlideShow
 *
 * @throws IOException if an error occurs while reading the data
 */
public static SlideShow<?,?> create(final NPOIFSFileSystem fs, String password) throws IOException {
    DirectoryNode root = fs.getRoot();

    // Encrypted OOXML files go inside OLE2 containers, is this one?
    if (root.hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) {
        InputStream stream = null;
        try {
            stream = DocumentFactoryHelper.getDecryptedStream(fs, password);

            return createXSLFSlideShow(stream);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    // If we get here, it isn't an encrypted PPTX file
    // So, treat it as a regular HSLF PPT one
    boolean passwordSet = false;
    if (password != null) {
        Biff8EncryptionKey.setCurrentUserPassword(password);
        passwordSet = true;
    }
    try {
        return createHSLFSlideShow(fs);
    } finally {
        if (passwordSet) {
            Biff8EncryptionKey.setCurrentUserPassword(null);
        }
    }
}
 
Example 16
Source Project: lams   Source File: NPropertyTable.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * reading constructor (used when we've read in a file and we want
 * to extract the property table from it). Populates the
 * properties thoroughly
 *
 * @param headerBlock the header block of the file
 * @param filesystem the filesystem to read from
 *
 * @exception IOException if anything goes wrong (which should be
 *            a result of the input being NFG)
 */
public NPropertyTable(final HeaderBlock headerBlock,
                      final NPOIFSFileSystem filesystem)
    throws IOException
{
    super(
          headerBlock,
          buildProperties(
                (new NPOIFSStream(filesystem, headerBlock.getPropertyStart())).iterator(),
                headerBlock.getBigBlockSize()
          )
    );
    _bigBigBlockSize = headerBlock.getBigBlockSize();
}
 
Example 17
Source Project: lams   Source File: VBAMacroReader.java    License: GNU General Public License v2.0 5 votes vote down vote up
public VBAMacroReader(InputStream rstream) throws IOException {
    InputStream is = FileMagic.prepareToCheckMagic(rstream);
    FileMagic fm = FileMagic.valueOf(is);
    if (fm == FileMagic.OLE2) {
        fs = new NPOIFSFileSystem(is);
    } else {
        openOOXML(is);
    }
}
 
Example 18
Source Project: lams   Source File: VBAMacroReader.java    License: GNU General Public License v2.0 5 votes vote down vote up
public VBAMacroReader(File file) throws IOException {
    try {
        this.fs = new NPOIFSFileSystem(file);
    } catch (OfficeXmlFileException e) {
        openOOXML(new FileInputStream(file));
    }
}
 
Example 19
Source Project: lams   Source File: POIDocument.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * check if we were created by POIFS otherwise create a new dummy POIFS
 * for storing the package data
 * 
 * @return {@code true} if dummy directory was created, {@code false} otherwise
 */
@SuppressWarnings("resource")
@Internal
protected boolean initDirectory() {
    if (directory == null) {
        directory = new NPOIFSFileSystem().getRoot(); // NOSONAR
        return true;
    }
    return false;
}
 
Example 20
Source Project: lams   Source File: HSSFWorkbook.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** Writes the workbook out to a brand new, empty POIFS */
private void write(NPOIFSFileSystem fs) throws IOException {
    // For tracking what we've written out, used if we're
    //  going to be preserving nodes
    List<String> excepts = new ArrayList<String>(1);

    // Write out the Workbook stream
    fs.createDocument(new ByteArrayInputStream(getBytes()), "Workbook");

    // Write out our HPFS properties, if we have them
    writeProperties(fs, excepts);
    
    if (preserveNodes) {
        // Don't write out the old Workbook, we'll be doing our new one
        // If the file had an "incorrect" name for the workbook stream,
        // don't write the old one as we'll use the correct name shortly
        excepts.addAll(Arrays.asList(WORKBOOK_DIR_ENTRY_NAMES));

        // summary information has been already written via writeProperties and might go in a
        // different stream, if the file is cryptoapi encrypted
        excepts.addAll(Arrays.asList(
            DocumentSummaryInformation.DEFAULT_STREAM_NAME,
            SummaryInformation.DEFAULT_STREAM_NAME,
            getEncryptedPropertyStreamName()
        ));

        // Copy over all the other nodes to our new poifs
        EntryUtils.copyNodes(
                new FilteringDirectoryNode(getDirectory(), excepts)
                , new FilteringDirectoryNode(fs.getRoot(), excepts)
                );

        // YK: preserve StorageClsid, it is important for embedded workbooks,
        // see Bugzilla 47920
        fs.getRoot().setStorageClsid(getDirectory().getStorageClsid());
    }
}
 
Example 21
Source Project: lams   Source File: HPSFPropertiesExtractor.java    License: GNU General Public License v2.0 4 votes vote down vote up
public HPSFPropertiesExtractor(NPOIFSFileSystem fs) {
    super(new HPSFPropertiesOnlyDocument(fs));
}
 
Example 22
public HPSFPropertiesOnlyDocument(NPOIFSFileSystem fs) {
    super(fs.getRoot());
}
 
Example 23
Source Project: lams   Source File: OLE2ExtractorFactory.java    License: GNU General Public License v2.0 4 votes vote down vote up
public static POIOLE2TextExtractor createExtractor(NPOIFSFileSystem fs) throws IOException {
    // Only ever an OLE2 one from the root of the FS
    return (POIOLE2TextExtractor)createExtractor(fs.getRoot());
}
 
Example 24
Source Project: lams   Source File: POIFSLister.java    License: GNU General Public License v2.0 4 votes vote down vote up
public static void viewFile(final String filename, boolean withSizes) throws IOException {
   NPOIFSFileSystem fs = new NPOIFSFileSystem(new File(filename));
   displayDirectory(fs.getRoot(), "", withSizes);
   fs.close();
}
 
Example 25
Source Project: lams   Source File: VBAMacroReader.java    License: GNU General Public License v2.0 4 votes vote down vote up
public VBAMacroReader(NPOIFSFileSystem fs) {
    this.fs = fs;
}
 
Example 26
Source Project: lams   Source File: EncryptionInfo.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Opens for decryption
 */
public EncryptionInfo(NPOIFSFileSystem fs) throws IOException {
   this(fs.getRoot());
}
 
Example 27
Source Project: lams   Source File: Encryptor.java    License: GNU General Public License v2.0 4 votes vote down vote up
public OutputStream getDataStream(NPOIFSFileSystem fs) throws IOException, GeneralSecurityException {
    return getDataStream(fs.getRoot());
}
 
Example 28
Source Project: lams   Source File: CryptoAPIEncryptor.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Encrypt the Document-/SummaryInformation and other optionally streams.
 * Opposed to other crypto modes, cryptoapi is record based and can't be used
 * to stream-encrypt a whole file
 * 
 * @see <a href="http://msdn.microsoft.com/en-us/library/dd943321(v=office.12).aspx">2.3.5.4 RC4 CryptoAPI Encrypted Summary Stream</a>
 */
public void setSummaryEntries(DirectoryNode dir, String encryptedStream, NPOIFSFileSystem entries)
throws IOException, GeneralSecurityException {
    CryptoAPIDocumentOutputStream bos = new CryptoAPIDocumentOutputStream(this); // NOSONAR
    byte buf[] = new byte[8];
    
    bos.write(buf, 0, 8); // skip header
    List<StreamDescriptorEntry> descList = new ArrayList<StreamDescriptorEntry>();

    int block = 0;
    for (Entry entry : entries.getRoot()) {
        if (entry.isDirectoryEntry()) {
            continue;
        }
        StreamDescriptorEntry descEntry = new StreamDescriptorEntry();
        descEntry.block = block;
        descEntry.streamOffset = bos.size();
        descEntry.streamName = entry.getName();
        descEntry.flags = StreamDescriptorEntry.flagStream.setValue(0, 1);
        descEntry.reserved2 = 0;
        
        bos.setBlock(block);
        DocumentInputStream dis = dir.createDocumentInputStream(entry);
        IOUtils.copy(dis, bos);
        dis.close();
        
        descEntry.streamSize = bos.size() - descEntry.streamOffset;
        descList.add(descEntry);
        
        block++;
    }
    
    int streamDescriptorArrayOffset = bos.size();
    
    bos.setBlock(0);
    LittleEndian.putUInt(buf, 0, descList.size());
    bos.write(buf, 0, 4);
    
    for (StreamDescriptorEntry sde : descList) {
        LittleEndian.putUInt(buf, 0, sde.streamOffset);
        bos.write(buf, 0, 4);
        LittleEndian.putUInt(buf, 0, sde.streamSize);
        bos.write(buf, 0, 4);
        LittleEndian.putUShort(buf, 0, sde.block);
        bos.write(buf, 0, 2);
        LittleEndian.putUByte(buf, 0, (short)sde.streamName.length());
        bos.write(buf, 0, 1);
        LittleEndian.putUByte(buf, 0, (short)sde.flags);
        bos.write(buf, 0, 1);
        LittleEndian.putUInt(buf, 0, sde.reserved2);
        bos.write(buf, 0, 4);
        byte nameBytes[] = StringUtil.getToUnicodeLE(sde.streamName);
        bos.write(nameBytes, 0, nameBytes.length);
        LittleEndian.putShort(buf, 0, (short)0); // null-termination
        bos.write(buf, 0, 2);
    }
    
    int savedSize = bos.size();
    int streamDescriptorArraySize = savedSize - streamDescriptorArrayOffset;
    LittleEndian.putUInt(buf, 0, streamDescriptorArrayOffset);
    LittleEndian.putUInt(buf, 4, streamDescriptorArraySize);

    bos.reset();
    bos.setBlock(0);
    bos.write(buf, 0, 8);
    bos.setSize(savedSize);
    
    dir.createDocument(encryptedStream, new ByteArrayInputStream(bos.getBuf(), 0, savedSize));
}
 
Example 29
Source Project: lams   Source File: Decryptor.java    License: GNU General Public License v2.0 4 votes vote down vote up
public InputStream getDataStream(NPOIFSFileSystem fs) throws IOException, GeneralSecurityException {
    return getDataStream(fs.getRoot());
}
 
Example 30
Source Project: lams   Source File: POIDocument.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Writes out the standard Document Information Properties (HPSF)
 * @param outFS the NPOIFSFileSystem to write the properties into
 * @param writtenEntries a list of POIFS entries to add the property names too
 * 
 * @throws IOException if an error when writing to the 
 *      {@link NPOIFSFileSystem} occurs
 */
protected void writeProperties(NPOIFSFileSystem outFS, List<String> writtenEntries) throws IOException {
    EncryptionInfo ei = getEncryptionInfo();
    final boolean encryptProps = (ei != null && ei.isDocPropsEncrypted());
    NPOIFSFileSystem fs = (encryptProps) ? new NPOIFSFileSystem() : outFS;
    
    SummaryInformation si = getSummaryInformation();
    if (si != null) {
        writePropertySet(SummaryInformation.DEFAULT_STREAM_NAME, si, fs);
        if(writtenEntries != null) {
            writtenEntries.add(SummaryInformation.DEFAULT_STREAM_NAME);
        }
    }
    DocumentSummaryInformation dsi = getDocumentSummaryInformation();
    if (dsi != null) {
        writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsi, fs);
        if(writtenEntries != null) {
            writtenEntries.add(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
        }
    }

    if (!encryptProps) {
        return;
    }

    // create empty document summary
    dsi = PropertySetFactory.newDocumentSummaryInformation();
    writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsi, outFS);
    // remove summary, if previously available
    if (outFS.getRoot().hasEntry(SummaryInformation.DEFAULT_STREAM_NAME)) {
        outFS.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME).delete();
    }
    Encryptor encGen = ei.getEncryptor();
    if (!(encGen instanceof CryptoAPIEncryptor)) {
        throw new EncryptedDocumentException("Using "+ei.getEncryptionMode()+" encryption. Only CryptoAPI encryption supports encrypted property sets!");
    }
    CryptoAPIEncryptor enc = (CryptoAPIEncryptor)encGen;
    try {
        enc.setSummaryEntries(outFS.getRoot(), getEncryptedPropertyStreamName(), fs);
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    } finally {
        fs.close();
    }
}