KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > poi > poifs > eventfilesystem > POIFSReader


1
2 /* ====================================================================
3    Copyright 2002-2004 Apache Software Foundation
4
5    Licensed under the Apache License, Version 2.0 (the "License");
6    you may not use this file except in compliance with the License.
7    You may obtain a copy of the License at
8
9        http://www.apache.org/licenses/LICENSE-2.0
10
11    Unless required by applicable law or agreed to in writing, software
12    distributed under the License is distributed on an "AS IS" BASIS,
13    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14    See the License for the specific language governing permissions and
15    limitations under the License.
16 ==================================================================== */

17         
18
19 package org.apache.poi.poifs.eventfilesystem;
20
21 import java.io.*;
22
23 import java.util.*;
24
25 import org.apache.poi.poifs.filesystem.DocumentInputStream;
26 import org.apache.poi.poifs.filesystem.POIFSDocument;
27 import org.apache.poi.poifs.filesystem.POIFSDocumentPath;
28 import org.apache.poi.poifs.property.DirectoryProperty;
29 import org.apache.poi.poifs.property.Property;
30 import org.apache.poi.poifs.property.PropertyTable;
31 import org.apache.poi.poifs.storage.BlockAllocationTableReader;
32 import org.apache.poi.poifs.storage.BlockList;
33 import org.apache.poi.poifs.storage.HeaderBlockReader;
34 import org.apache.poi.poifs.storage.RawDataBlockList;
35 import org.apache.poi.poifs.storage.SmallBlockTableReader;
36
37 /**
38  * An event-driven reader for POIFS file systems. Users of this class
39  * first create an instance of it, then use the registerListener
40  * methods to register POIFSReaderListener instances for specific
41  * documents. Once all the listeners have been registered, the read()
42  * method is called, which results in the listeners being notified as
43  * their documents are read.
44  *
45  * @author Marc Johnson (mjohnson at apache dot org)
46  */

47
48 public class POIFSReader
49 {
50     private POIFSReaderRegistry registry;
51     private boolean registryClosed;
52
53     /**
54      * Create a POIFSReader
55      */

56
57     public POIFSReader()
58     {
59         registry = new POIFSReaderRegistry();
60         registryClosed = false;
61     }
62
63     /**
64      * Read from an InputStream and process the documents we get
65      *
66      * @param stream the InputStream from which to read the data
67      *
68      * @exception IOException on errors reading, or on invalid data
69      */

70
71     public void read(final InputStream stream)
72         throws IOException
73     {
74         registryClosed = true;
75
76         // read the header block from the stream
77
HeaderBlockReader header_block_reader = new HeaderBlockReader(stream);
78
79         // read the rest of the stream into blocks
80
RawDataBlockList data_blocks = new RawDataBlockList(stream);
81
82         // set up the block allocation table (necessary for the
83
// data_blocks to be manageable
84
new BlockAllocationTableReader(header_block_reader.getBATCount(),
85                                        header_block_reader.getBATArray(),
86                                        header_block_reader.getXBATCount(),
87                                        header_block_reader.getXBATIndex(),
88                                        data_blocks);
89
90         // get property table from the document
91
PropertyTable properties =
92             new PropertyTable(header_block_reader.getPropertyStart(),
93                               data_blocks);
94
95         // process documents
96
processProperties(SmallBlockTableReader
97             .getSmallDocumentBlocks(data_blocks, properties
98                 .getRoot(), header_block_reader
99                     .getSBATStart()), data_blocks, properties.getRoot()
100                         .getChildren(), new POIFSDocumentPath());
101     }
102
103     /**
104      * Register a POIFSReaderListener for all documents
105      *
106      * @param listener the listener to be registered
107      *
108      * @exception NullPointerException if listener is null
109      * @exception IllegalStateException if read() has already been
110      * called
111      */

112
113     public void registerListener(final POIFSReaderListener listener)
114     {
115         if (listener == null)
116         {
117             throw new NullPointerException JavaDoc();
118         }
119         if (registryClosed)
120         {
121             throw new IllegalStateException JavaDoc();
122         }
123         registry.registerListener(listener);
124     }
125
126     /**
127      * Register a POIFSReaderListener for a document in the root
128      * directory
129      *
130      * @param listener the listener to be registered
131      * @param name the document name
132      *
133      * @exception NullPointerException if listener is null or name is
134      * null or empty
135      * @exception IllegalStateException if read() has already been
136      * called
137      */

138
139     public void registerListener(final POIFSReaderListener listener,
140                                  final String JavaDoc name)
141     {
142         registerListener(listener, null, name);
143     }
144
145     /**
146      * Register a POIFSReaderListener for a document in the specified
147      * directory
148      *
149      * @param listener the listener to be registered
150      * @param path the document path; if null, the root directory is
151      * assumed
152      * @param name the document name
153      *
154      * @exception NullPointerException if listener is null or name is
155      * null or empty
156      * @exception IllegalStateException if read() has already been
157      * called
158      */

159
160     public void registerListener(final POIFSReaderListener listener,
161                                  final POIFSDocumentPath path,
162                                  final String JavaDoc name)
163     {
164         if ((listener == null) || (name == null) || (name.length() == 0))
165         {
166             throw new NullPointerException JavaDoc();
167         }
168         if (registryClosed)
169         {
170             throw new IllegalStateException JavaDoc();
171         }
172         registry.registerListener(listener,
173                                   (path == null) ? new POIFSDocumentPath()
174                                                  : path, name);
175     }
176
177     /**
178      * read in files
179      *
180      * @param args names of the files
181      *
182      * @exception IOException
183      */

184
185     public static void main(String JavaDoc args[])
186         throws IOException
187     {
188         if (args.length == 0)
189         {
190             System.err
191                 .println("at least one argument required: input filename(s)");
192             System.exit(1);
193         }
194
195         // register for all
196
for (int j = 0; j < args.length; j++)
197         {
198             POIFSReader reader = new POIFSReader();
199             POIFSReaderListener listener = new SampleListener();
200
201             reader.registerListener(listener);
202             System.out.println("reading " + args[ j ]);
203             FileInputStream istream = new FileInputStream(args[ j ]);
204
205             reader.read(istream);
206             istream.close();
207         }
208     }
209
210     private void processProperties(final BlockList small_blocks,
211                                    final BlockList big_blocks,
212                                    final Iterator properties,
213                                    final POIFSDocumentPath path)
214         throws IOException
215     {
216         while (properties.hasNext())
217         {
218             Property property = ( Property ) properties.next();
219             String JavaDoc name = property.getName();
220
221             if (property.isDirectory())
222             {
223                 POIFSDocumentPath new_path = new POIFSDocumentPath(path,
224                                                  new String JavaDoc[]
225                 {
226                     name
227                 });
228
229                 processProperties(
230                     small_blocks, big_blocks,
231                     (( DirectoryProperty ) property).getChildren(), new_path);
232             }
233             else
234             {
235                 int startBlock = property.getStartBlock();
236                 Iterator listeners = registry.getListeners(path, name);
237
238                 if (listeners.hasNext())
239                 {
240                     int size = property.getSize();
241                     POIFSDocument document = null;
242
243                     if (property.shouldUseSmallBlocks())
244                     {
245                         document =
246                             new POIFSDocument(name, small_blocks
247                                 .fetchBlocks(startBlock), size);
248                     }
249                     else
250                     {
251                         document =
252                             new POIFSDocument(name, big_blocks
253                                 .fetchBlocks(startBlock), size);
254                     }
255                     while (listeners.hasNext())
256                     {
257                         POIFSReaderListener listener =
258                             ( POIFSReaderListener ) listeners.next();
259
260                         listener.processPOIFSReaderEvent(
261                             new POIFSReaderEvent(
262                                 new DocumentInputStream(document), path,
263                                 name));
264                     }
265                 }
266                 else
267                 {
268
269                     // consume the document's data and discard it
270
if (property.shouldUseSmallBlocks())
271                     {
272                         small_blocks.fetchBlocks(startBlock);
273                     }
274                     else
275                     {
276                         big_blocks.fetchBlocks(startBlock);
277                     }
278                 }
279             }
280         }
281     }
282
283     private static class SampleListener
284         implements POIFSReaderListener
285     {
286
287         /**
288          * Constructor SampleListener
289          */

290
291         SampleListener()
292         {
293         }
294
295         /**
296          * Method processPOIFSReaderEvent
297          *
298          * @param event
299          */

300
301         public void processPOIFSReaderEvent(final POIFSReaderEvent event)
302         {
303             DocumentInputStream istream = event.getStream();
304             POIFSDocumentPath path = event.getPath();
305             String JavaDoc name = event.getName();
306
307             try
308             {
309                 byte[] data = new byte[ istream.available() ];
310
311                 istream.read(data);
312                 int pathLength = path.length();
313
314                 for (int k = 0; k < pathLength; k++)
315                 {
316                     System.out.print("/" + path.getComponent(k));
317                 }
318                 System.out.println("/" + name + ": " + data.length
319                                    + " bytes read");
320             }
321             catch (IOException ignored)
322             {
323             }
324         }
325     } // end private class SampleListener
326
} // end public class POIFSReader
327

328
Popular Tags