Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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