PageRenderTime 71ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/ppt/poi/org/apache/poi/poifs/filesystem/POIFSFileSystem.java

https://github.com/minstrelsy/POI-Android
Java | 614 lines | 314 code | 81 blank | 219 comment | 22 complexity | 5083d727a84f9c004bece7393d2ae9b8 MD5 | raw file
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.poifs.filesystem;
  16. import java.io.ByteArrayInputStream;
  17. import java.io.FileInputStream;
  18. import java.io.FileOutputStream;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.io.PushbackInputStream;
  23. import java.io.RandomAccessFile;
  24. import java.util.ArrayList;
  25. import java.util.Collections;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import org.apache.poi.poifs.common.POIFSBigBlockSize;
  29. import org.apache.poi.poifs.common.POIFSConstants;
  30. import org.apache.poi.poifs.dev.POIFSViewable;
  31. import org.apache.poi.poifs.property.DirectoryProperty;
  32. import org.apache.poi.poifs.property.Property;
  33. import org.apache.poi.poifs.property.PropertyTable;
  34. import org.apache.poi.poifs.storage.BATBlock;
  35. import org.apache.poi.poifs.storage.BlockAllocationTableReader;
  36. import org.apache.poi.poifs.storage.BlockAllocationTableWriter;
  37. import org.apache.poi.poifs.storage.BlockList;
  38. import org.apache.poi.poifs.storage.BlockWritable;
  39. import org.apache.poi.poifs.storage.HeaderBlockConstants;
  40. import org.apache.poi.poifs.storage.HeaderBlock;
  41. import org.apache.poi.poifs.storage.HeaderBlockWriter;
  42. import org.apache.poi.poifs.storage.RawDataBlockList;
  43. import org.apache.poi.poifs.storage.SmallBlockTableReader;
  44. import org.apache.poi.poifs.storage.SmallBlockTableWriter;
  45. import org.apache.poi.util.CloseIgnoringInputStream;
  46. import org.apache.poi.util.IOUtils;
  47. import org.apache.poi.util.LongField;
  48. import org.apache.poi.util.POILogFactory;
  49. import org.apache.poi.util.POILogger;
  50. /**
  51. * This is the main class of the POIFS system; it manages the entire
  52. * life cycle of the filesystem.
  53. *
  54. * @author Marc Johnson (mjohnson at apache dot org)
  55. */
  56. public class POIFSFileSystem
  57. implements POIFSViewable
  58. {
  59. private static final POILogger _logger =
  60. POILogFactory.getLogger(POIFSFileSystem.class);
  61. /**
  62. * Convenience method for clients that want to avoid the auto-close behaviour of the constructor.
  63. */
  64. public static InputStream createNonClosingInputStream(InputStream is) {
  65. return new CloseIgnoringInputStream(is);
  66. }
  67. private PropertyTable _property_table;
  68. private List _documents;
  69. private DirectoryNode _root;
  70. /**
  71. * What big block size the file uses. Most files
  72. * use 512 bytes, but a few use 4096
  73. */
  74. private POIFSBigBlockSize bigBlockSize =
  75. POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS;
  76. /**
  77. * Constructor, intended for writing
  78. */
  79. public POIFSFileSystem()
  80. {
  81. HeaderBlock header_block = new HeaderBlock(bigBlockSize);
  82. _property_table = new PropertyTable(header_block);
  83. _documents = new ArrayList();
  84. _root = null;
  85. }
  86. /**
  87. * Create a POIFSFileSystem from an <tt>InputStream</tt>. Normally the stream is read until
  88. * EOF. The stream is always closed.<p/>
  89. *
  90. * Some streams are usable after reaching EOF (typically those that return <code>true</code>
  91. * for <tt>markSupported()</tt>). In the unlikely case that the caller has such a stream
  92. * <i>and</i> needs to use it after this constructor completes, a work around is to wrap the
  93. * stream in order to trap the <tt>close()</tt> call. A convenience method (
  94. * <tt>createNonClosingInputStream()</tt>) has been provided for this purpose:
  95. * <pre>
  96. * InputStream wrappedStream = POIFSFileSystem.createNonClosingInputStream(is);
  97. * HSSFWorkbook wb = new HSSFWorkbook(wrappedStream);
  98. * is.reset();
  99. * doSomethingElse(is);
  100. * </pre>
  101. * Note also the special case of <tt>ByteArrayInputStream</tt> for which the <tt>close()</tt>
  102. * method does nothing.
  103. * <pre>
  104. * ByteArrayInputStream bais = ...
  105. * HSSFWorkbook wb = new HSSFWorkbook(bais); // calls bais.close() !
  106. * bais.reset(); // no problem
  107. * doSomethingElse(bais);
  108. * </pre>
  109. *
  110. * @param stream the InputStream from which to read the data
  111. *
  112. * @exception IOException on errors reading, or on invalid data
  113. */
  114. public POIFSFileSystem(InputStream stream)
  115. throws IOException
  116. {
  117. this();
  118. boolean success = false;
  119. HeaderBlock header_block;
  120. RawDataBlockList data_blocks;
  121. try {
  122. // read the header block from the stream
  123. header_block = new HeaderBlock(stream);
  124. bigBlockSize = header_block.getBigBlockSize();
  125. // read the rest of the stream into blocks
  126. data_blocks = new RawDataBlockList(stream, bigBlockSize);
  127. success = true;
  128. } finally {
  129. closeInputStream(stream, success);
  130. }
  131. // set up the block allocation table (necessary for the
  132. // data_blocks to be manageable
  133. new BlockAllocationTableReader(header_block.getBigBlockSize(),
  134. header_block.getBATCount(),
  135. header_block.getBATArray(),
  136. header_block.getXBATCount(),
  137. header_block.getXBATIndex(),
  138. data_blocks);
  139. // get property table from the document
  140. PropertyTable properties =
  141. new PropertyTable(header_block, data_blocks);
  142. // init documents
  143. processProperties(
  144. SmallBlockTableReader.getSmallDocumentBlocks(
  145. bigBlockSize, data_blocks, properties.getRoot(),
  146. header_block.getSBATStart()
  147. ),
  148. data_blocks,
  149. properties.getRoot().getChildren(),
  150. null,
  151. header_block.getPropertyStart()
  152. );
  153. // For whatever reason CLSID of root is always 0.
  154. getRoot().setStorageClsid(properties.getRoot().getStorageClsid());
  155. }
  156. /**
  157. * @param stream the stream to be closed
  158. * @param success <code>false</code> if an exception is currently being thrown in the calling method
  159. */
  160. private void closeInputStream(InputStream stream, boolean success) {
  161. if(stream.markSupported() && !(stream instanceof ByteArrayInputStream)) {
  162. String msg = "POIFS is closing the supplied input stream of type ("
  163. + stream.getClass().getName() + ") which supports mark/reset. "
  164. + "This will be a problem for the caller if the stream will still be used. "
  165. + "If that is the case the caller should wrap the input stream to avoid this close logic. "
  166. + "This warning is only temporary and will not be present in future versions of POI.";
  167. _logger.log(POILogger.WARN, msg);
  168. }
  169. try {
  170. stream.close();
  171. } catch (IOException e) {
  172. if(success) {
  173. throw new RuntimeException(e);
  174. }
  175. // else not success? Try block did not complete normally
  176. // just print stack trace and leave original ex to be thrown
  177. e.printStackTrace();
  178. }
  179. }
  180. /**
  181. * Checks that the supplied InputStream (which MUST
  182. * support mark and reset, or be a PushbackInputStream)
  183. * has a POIFS (OLE2) header at the start of it.
  184. * If your InputStream does not support mark / reset,
  185. * then wrap it in a PushBackInputStream, then be
  186. * sure to always use that, and not the original!
  187. * @param inp An InputStream which supports either mark/reset, or is a PushbackInputStream
  188. */
  189. public static boolean hasPOIFSHeader(InputStream inp) throws IOException {
  190. // We want to peek at the first 8 bytes
  191. inp.mark(8);
  192. byte[] header = new byte[8];
  193. IOUtils.readFully(inp, header);
  194. LongField signature = new LongField(HeaderBlockConstants._signature_offset, header);
  195. // Wind back those 8 bytes
  196. if(inp instanceof PushbackInputStream) {
  197. PushbackInputStream pin = (PushbackInputStream)inp;
  198. pin.unread(header);
  199. } else {
  200. inp.reset();
  201. }
  202. // Did it match the signature?
  203. return (signature.get() == HeaderBlockConstants._signature);
  204. }
  205. /**
  206. * Create a new document to be added to the root directory
  207. *
  208. * @param stream the InputStream from which the document's data
  209. * will be obtained
  210. * @param name the name of the new POIFSDocument
  211. *
  212. * @return the new DocumentEntry
  213. *
  214. * @exception IOException on error creating the new POIFSDocument
  215. */
  216. public DocumentEntry createDocument(final InputStream stream,
  217. final String name)
  218. throws IOException
  219. {
  220. return getRoot().createDocument(name, stream);
  221. }
  222. /**
  223. * create a new DocumentEntry in the root entry; the data will be
  224. * provided later
  225. *
  226. * @param name the name of the new DocumentEntry
  227. * @param size the size of the new DocumentEntry
  228. * @param writer the writer of the new DocumentEntry
  229. *
  230. * @return the new DocumentEntry
  231. *
  232. * @exception IOException
  233. */
  234. public DocumentEntry createDocument(final String name, final int size,
  235. final POIFSWriterListener writer)
  236. throws IOException
  237. {
  238. return getRoot().createDocument(name, size, writer);
  239. }
  240. /**
  241. * create a new DirectoryEntry in the root directory
  242. *
  243. * @param name the name of the new DirectoryEntry
  244. *
  245. * @return the new DirectoryEntry
  246. *
  247. * @exception IOException on name duplication
  248. */
  249. public DirectoryEntry createDirectory(final String name)
  250. throws IOException
  251. {
  252. return getRoot().createDirectory(name);
  253. }
  254. /**
  255. * Write the filesystem out
  256. *
  257. * @param stream the OutputStream to which the filesystem will be
  258. * written
  259. *
  260. * @exception IOException thrown on errors writing to the stream
  261. */
  262. public void writeFilesystem(final OutputStream stream)
  263. throws IOException
  264. {
  265. // get the property table ready
  266. _property_table.preWrite();
  267. // create the small block store, and the SBAT
  268. SmallBlockTableWriter sbtw =
  269. new SmallBlockTableWriter(bigBlockSize, _documents, _property_table.getRoot());
  270. // create the block allocation table
  271. BlockAllocationTableWriter bat =
  272. new BlockAllocationTableWriter(bigBlockSize);
  273. // create a list of BATManaged objects: the documents plus the
  274. // property table and the small block table
  275. List bm_objects = new ArrayList();
  276. bm_objects.addAll(_documents);
  277. bm_objects.add(_property_table);
  278. bm_objects.add(sbtw);
  279. bm_objects.add(sbtw.getSBAT());
  280. // walk the list, allocating space for each and assigning each
  281. // a starting block number
  282. Iterator iter = bm_objects.iterator();
  283. while (iter.hasNext())
  284. {
  285. BATManaged bmo = ( BATManaged ) iter.next();
  286. int block_count = bmo.countBlocks();
  287. if (block_count != 0)
  288. {
  289. bmo.setStartBlock(bat.allocateSpace(block_count));
  290. }
  291. else
  292. {
  293. // Either the BATManaged object is empty or its data
  294. // is composed of SmallBlocks; in either case,
  295. // allocating space in the BAT is inappropriate
  296. }
  297. }
  298. // allocate space for the block allocation table and take its
  299. // starting block
  300. int batStartBlock = bat.createBlocks();
  301. // get the extended block allocation table blocks
  302. HeaderBlockWriter header_block_writer = new HeaderBlockWriter(bigBlockSize);
  303. BATBlock[] xbat_blocks =
  304. header_block_writer.setBATBlocks(bat.countBlocks(),
  305. batStartBlock);
  306. // set the property table start block
  307. header_block_writer.setPropertyStart(_property_table.getStartBlock());
  308. // set the small block allocation table start block
  309. header_block_writer.setSBATStart(sbtw.getSBAT().getStartBlock());
  310. // set the small block allocation table block count
  311. header_block_writer.setSBATBlockCount(sbtw.getSBATBlockCount());
  312. // the header is now properly initialized. Make a list of
  313. // writers (the header block, followed by the documents, the
  314. // property table, the small block store, the small block
  315. // allocation table, the block allocation table, and the
  316. // extended block allocation table blocks)
  317. List writers = new ArrayList();
  318. writers.add(header_block_writer);
  319. writers.addAll(_documents);
  320. writers.add(_property_table);
  321. writers.add(sbtw);
  322. writers.add(sbtw.getSBAT());
  323. writers.add(bat);
  324. for (int j = 0; j < xbat_blocks.length; j++)
  325. {
  326. writers.add(xbat_blocks[ j ]);
  327. }
  328. // now, write everything out
  329. iter = writers.iterator();
  330. while (iter.hasNext())
  331. {
  332. BlockWritable writer = ( BlockWritable ) iter.next();
  333. writer.writeBlocks(stream);
  334. }
  335. }
  336. /**
  337. * read in a file and write it back out again
  338. *
  339. * @param args names of the files; arg[ 0 ] is the input file,
  340. * arg[ 1 ] is the output file
  341. *
  342. * @exception IOException
  343. */
  344. public static void main(String args[])
  345. throws IOException
  346. {
  347. if (args.length != 2)
  348. {
  349. System.err.println(
  350. "two arguments required: input filename and output filename");
  351. System.exit(1);
  352. }
  353. FileInputStream istream = new FileInputStream(args[ 0 ]);
  354. FileOutputStream ostream = new FileOutputStream(args[ 1 ]);
  355. new POIFSFileSystem(istream).writeFilesystem(ostream);
  356. istream.close();
  357. ostream.close();
  358. }
  359. /**
  360. * get the root entry
  361. *
  362. * @return the root entry
  363. */
  364. public DirectoryNode getRoot()
  365. {
  366. if (_root == null)
  367. {
  368. _root = new DirectoryNode(_property_table.getRoot(), this, null);
  369. }
  370. return _root;
  371. }
  372. /**
  373. * open a document in the root entry's list of entries
  374. *
  375. * @param documentName the name of the document to be opened
  376. *
  377. * @return a newly opened DocumentInputStream
  378. *
  379. * @exception IOException if the document does not exist or the
  380. * name is that of a DirectoryEntry
  381. */
  382. public DocumentInputStream createDocumentInputStream(
  383. final String documentName)
  384. throws IOException
  385. {
  386. return getRoot().createDocumentInputStream(documentName);
  387. }
  388. /**
  389. * add a new POIFSDocument
  390. *
  391. * @param document the POIFSDocument being added
  392. */
  393. void addDocument(final POIFSDocument document)
  394. {
  395. _documents.add(document);
  396. _property_table.addProperty(document.getDocumentProperty());
  397. }
  398. /**
  399. * add a new DirectoryProperty
  400. *
  401. * @param directory the DirectoryProperty being added
  402. */
  403. void addDirectory(final DirectoryProperty directory)
  404. {
  405. _property_table.addProperty(directory);
  406. }
  407. /**
  408. * remove an entry
  409. *
  410. * @param entry to be removed
  411. */
  412. void remove(EntryNode entry)
  413. {
  414. _property_table.removeProperty(entry.getProperty());
  415. if (entry.isDocumentEntry())
  416. {
  417. _documents.remove((( DocumentNode ) entry).getDocument());
  418. }
  419. }
  420. private void processProperties(final BlockList small_blocks,
  421. final BlockList big_blocks,
  422. final Iterator properties,
  423. final DirectoryNode dir,
  424. final int headerPropertiesStartAt)
  425. throws IOException
  426. {
  427. while (properties.hasNext())
  428. {
  429. Property property = ( Property ) properties.next();
  430. String name = property.getName();
  431. DirectoryNode parent = (dir == null)
  432. ? (( DirectoryNode ) getRoot())
  433. : dir;
  434. if (property.isDirectory())
  435. {
  436. DirectoryNode new_dir =
  437. ( DirectoryNode ) parent.createDirectory(name);
  438. new_dir.setStorageClsid( property.getStorageClsid() );
  439. processProperties(
  440. small_blocks, big_blocks,
  441. (( DirectoryProperty ) property).getChildren(),
  442. new_dir, headerPropertiesStartAt);
  443. }
  444. else
  445. {
  446. int startBlock = property.getStartBlock();
  447. int size = property.getSize();
  448. POIFSDocument document = null;
  449. if (property.shouldUseSmallBlocks())
  450. {
  451. document =
  452. new POIFSDocument(name,
  453. small_blocks.fetchBlocks(startBlock, headerPropertiesStartAt),
  454. size);
  455. }
  456. else
  457. {
  458. document =
  459. new POIFSDocument(name,
  460. big_blocks.fetchBlocks(startBlock, headerPropertiesStartAt),
  461. size);
  462. }
  463. parent.createDocument(document);
  464. }
  465. }
  466. }
  467. /* ********** START begin implementation of POIFSViewable ********** */
  468. /**
  469. * Get an array of objects, some of which may implement
  470. * POIFSViewable
  471. *
  472. * @return an array of Object; may not be null, but may be empty
  473. */
  474. public Object [] getViewableArray()
  475. {
  476. if (preferArray())
  477. {
  478. return (( POIFSViewable ) getRoot()).getViewableArray();
  479. }
  480. return new Object[ 0 ];
  481. }
  482. /**
  483. * Get an Iterator of objects, some of which may implement
  484. * POIFSViewable
  485. *
  486. * @return an Iterator; may not be null, but may have an empty
  487. * back end store
  488. */
  489. public Iterator getViewableIterator()
  490. {
  491. if (!preferArray())
  492. {
  493. return (( POIFSViewable ) getRoot()).getViewableIterator();
  494. }
  495. return Collections.EMPTY_LIST.iterator();
  496. }
  497. /**
  498. * Give viewers a hint as to whether to call getViewableArray or
  499. * getViewableIterator
  500. *
  501. * @return true if a viewer should call getViewableArray, false if
  502. * a viewer should call getViewableIterator
  503. */
  504. public boolean preferArray()
  505. {
  506. return (( POIFSViewable ) getRoot()).preferArray();
  507. }
  508. /**
  509. * Provides a short description of the object, to be used when a
  510. * POIFSViewable object has not provided its contents.
  511. *
  512. * @return short description
  513. */
  514. public String getShortDescription()
  515. {
  516. return "POIFS FileSystem";
  517. }
  518. /**
  519. * @return The Big Block size, normally 512 bytes, sometimes 4096 bytes
  520. */
  521. public int getBigBlockSize() {
  522. return bigBlockSize.getBigBlockSize();
  523. }
  524. /**
  525. * @return The Big Block size, normally 512 bytes, sometimes 4096 bytes
  526. */
  527. public POIFSBigBlockSize getBigBlockSizeDetails() {
  528. return bigBlockSize;
  529. }
  530. /* ********** END begin implementation of POIFSViewable ********** */
  531. } // end public class POIFSFileSystem