KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > poi > hpsf > basic > TestWrite


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

16         
17
18 package org.apache.poi.hpsf.basic;
19
20 import java.io.ByteArrayInputStream JavaDoc;
21 import java.io.ByteArrayOutputStream JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.FileFilter JavaDoc;
24 import java.io.FileInputStream JavaDoc;
25 import java.io.FileOutputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.io.OutputStream JavaDoc;
29 import java.io.PrintWriter JavaDoc;
30 import java.io.StringWriter JavaDoc;
31 import java.io.UnsupportedEncodingException JavaDoc;
32 import java.nio.charset.Charset JavaDoc;
33 import java.util.Date JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.Map JavaDoc;
36
37 import junit.framework.Assert;
38 import junit.framework.TestCase;
39
40 import org.apache.poi.hpsf.ClassID;
41 import org.apache.poi.hpsf.Constants;
42 import org.apache.poi.hpsf.HPSFRuntimeException;
43 import org.apache.poi.hpsf.IllegalPropertySetDataException;
44 import org.apache.poi.hpsf.MutableProperty;
45 import org.apache.poi.hpsf.MutablePropertySet;
46 import org.apache.poi.hpsf.MutableSection;
47 import org.apache.poi.hpsf.NoFormatIDException;
48 import org.apache.poi.hpsf.NoPropertySetStreamException;
49 import org.apache.poi.hpsf.PropertySet;
50 import org.apache.poi.hpsf.PropertySetFactory;
51 import org.apache.poi.hpsf.ReadingNotSupportedException;
52 import org.apache.poi.hpsf.Section;
53 import org.apache.poi.hpsf.SummaryInformation;
54 import org.apache.poi.hpsf.UnsupportedVariantTypeException;
55 import org.apache.poi.hpsf.Variant;
56 import org.apache.poi.hpsf.VariantSupport;
57 import org.apache.poi.hpsf.WritingNotSupportedException;
58 import org.apache.poi.hpsf.wellknown.PropertyIDMap;
59 import org.apache.poi.hpsf.wellknown.SectionIDMap;
60 import org.apache.poi.poifs.eventfilesystem.POIFSReader;
61 import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
62 import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
63 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
64 import org.apache.poi.util.LittleEndian;
65 import org.apache.poi.util.TempFile;
66
67
68
69 /**
70  * <p>Tests HPSF's writing functionality.</p>
71  *
72  * @author Rainer Klute (klute@rainer-klute.de)
73  * @since 2003-02-07
74  * @version $Id: TestWrite.java,v 1.20 2004/10/12 05:49:01 glens Exp $
75  */

76 public class TestWrite extends TestCase
77 {
78
79     static final String JavaDoc POI_FS = "TestHPSFWritingFunctionality.doc";
80
81     static final int BYTE_ORDER = 0xfffe;
82     static final int FORMAT = 0x0000;
83     static final int OS_VERSION = 0x00020A04;
84     static final int[] SECTION_COUNT = {1, 2};
85     static final boolean[] IS_SUMMARY_INFORMATION = {true, false};
86     static final boolean[] IS_DOCUMENT_SUMMARY_INFORMATION = {false, true};
87
88     final String JavaDoc IMPROPER_DEFAULT_CHARSET_MESSAGE =
89         "Your default character set is " + getDefaultCharsetName() +
90         ". However, this testcase must be run in an environment " +
91         "with a default character set supporting at least " +
92         "8-bit-characters. You can achieve this by setting the " +
93         "LANG environment variable to a proper value, e.g. " +
94         "\"de_DE\".";
95
96     POIFile[] poiFiles;
97
98
99
100     /**
101      * <p>Constructor</p>
102      *
103      * @param name the test case's name
104      */

105     public TestWrite(final String JavaDoc name)
106     {
107         super(name);
108     }
109
110
111
112     /**
113      * @see TestCase#setUp()
114      */

115     public void setUp()
116     {
117         VariantSupport.setLogUnsupportedTypes(false);
118     }
119
120
121
122     /**
123      * <p>Writes an empty property set to a POIFS and reads it back
124      * in.</p>
125      *
126      * @exception IOException if an I/O exception occurs
127      * @exception UnsupportedVariantTypeException if HPSF does not yet support
128      * a variant type to be written
129      */

130     public void testNoFormatID()
131         throws IOException JavaDoc, UnsupportedVariantTypeException
132     {
133         final String JavaDoc dataDirName = System.getProperty("HPSF.testdata.path");
134         final File JavaDoc dataDir = new File JavaDoc(dataDirName);
135         final File JavaDoc filename = new File JavaDoc(dataDir, POI_FS);
136         filename.deleteOnExit();
137
138         /* Create a mutable property set with a section that does not have the
139          * formatID set: */

140         final OutputStream JavaDoc out = new FileOutputStream JavaDoc(filename);
141         final POIFSFileSystem poiFs = new POIFSFileSystem();
142         final MutablePropertySet ps = new MutablePropertySet();
143         ps.clearSections();
144         ps.addSection(new MutableSection());
145
146         /* Write it to a POIFS and the latter to disk: */
147         try
148         {
149             final ByteArrayOutputStream JavaDoc psStream = new ByteArrayOutputStream JavaDoc();
150             ps.write(psStream);
151             psStream.close();
152             final byte[] streamData = psStream.toByteArray();
153             poiFs.createDocument(new ByteArrayInputStream JavaDoc(streamData),
154                                  SummaryInformation.DEFAULT_STREAM_NAME);
155             poiFs.writeFilesystem(out);
156             out.close();
157             Assert.fail("Should have thrown a NoFormatIDException.");
158         }
159         catch (Exception JavaDoc ex)
160         {
161             Assert.assertTrue(ex instanceof NoFormatIDException);
162         }
163         finally
164         {
165             out.close();
166         }
167     }
168
169
170
171     /**
172      * <p>Writes an empty property set to a POIFS and reads it back
173      * in.</p>
174      *
175      * @exception IOException if an I/O exception occurs
176      * @exception UnsupportedVariantTypeException if HPSF does not yet support
177      * a variant type to be written
178      */

179     public void testWriteEmptyPropertySet()
180         throws IOException JavaDoc, UnsupportedVariantTypeException
181     {
182         final File JavaDoc dataDir =
183             new File JavaDoc(System.getProperty("HPSF.testdata.path"));
184         final File JavaDoc filename = new File JavaDoc(dataDir, POI_FS);
185         filename.deleteOnExit();
186
187         /* Create a mutable property set and write it to a POIFS: */
188         final OutputStream JavaDoc out = new FileOutputStream JavaDoc(filename);
189         final POIFSFileSystem poiFs = new POIFSFileSystem();
190         final MutablePropertySet ps = new MutablePropertySet();
191         final MutableSection s = (MutableSection) ps.getSections().get(0);
192         s.setFormatID(SectionIDMap.SUMMARY_INFORMATION_ID);
193
194         final ByteArrayOutputStream JavaDoc psStream = new ByteArrayOutputStream JavaDoc();
195         ps.write(psStream);
196         psStream.close();
197         final byte[] streamData = psStream.toByteArray();
198         poiFs.createDocument(new ByteArrayInputStream JavaDoc(streamData),
199                              SummaryInformation.DEFAULT_STREAM_NAME);
200         poiFs.writeFilesystem(out);
201         out.close();
202
203         /* Read the POIFS: */
204         final POIFSReader r = new POIFSReader();
205         r.registerListener(new MyPOIFSReaderListener(),
206                            SummaryInformation.DEFAULT_STREAM_NAME);
207         r.read(new FileInputStream JavaDoc(filename));
208     }
209
210
211
212     /**
213      * <p>Writes a simple property set with a SummaryInformation section to a
214      * POIFS and reads it back in.</p>
215      *
216      * @exception IOException if an I/O exception occurs
217      * @exception UnsupportedVariantTypeException if HPSF does not yet support
218      * a variant type to be written
219      */

220     public void testWriteSimplePropertySet()
221         throws IOException JavaDoc, UnsupportedVariantTypeException
222     {
223         final String JavaDoc AUTHOR = "Rainer Klute";
224         final String JavaDoc TITLE = "Test Document";
225         final File JavaDoc dataDir =
226             new File JavaDoc(System.getProperty("HPSF.testdata.path"));
227         final File JavaDoc filename = new File JavaDoc(dataDir, POI_FS);
228         filename.deleteOnExit();
229         final OutputStream JavaDoc out = new FileOutputStream JavaDoc(filename);
230         final POIFSFileSystem poiFs = new POIFSFileSystem();
231     
232         final MutablePropertySet ps = new MutablePropertySet();
233         final MutableSection si = new MutableSection();
234         si.setFormatID(SectionIDMap.SUMMARY_INFORMATION_ID);
235         ps.getSections().set(0, si);
236     
237         final MutableProperty p = new MutableProperty();
238         p.setID(PropertyIDMap.PID_AUTHOR);
239         p.setType(Variant.VT_LPWSTR);
240         p.setValue(AUTHOR);
241         si.setProperty(p);
242         si.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPSTR, TITLE);
243     
244         poiFs.createDocument(ps.toInputStream(),
245                              SummaryInformation.DEFAULT_STREAM_NAME);
246         poiFs.writeFilesystem(out);
247         out.close();
248     
249         /* Read the POIFS: */
250         final PropertySet[] psa = new PropertySet[1];
251         final POIFSReader r = new POIFSReader();
252         r.registerListener(new POIFSReaderListener()
253             {
254                 public void processPOIFSReaderEvent
255                     (final POIFSReaderEvent event)
256                 {
257                     try
258                     {
259                         psa[0] = PropertySetFactory.create(event.getStream());
260                     }
261                     catch (Exception JavaDoc ex)
262                     {
263                         fail(org.apache.poi.hpsf.Util.toString(ex));
264                     }
265                 }
266     
267             },
268             SummaryInformation.DEFAULT_STREAM_NAME);
269         r.read(new FileInputStream JavaDoc(filename));
270         Assert.assertNotNull(psa[0]);
271         Assert.assertTrue(psa[0].isSummaryInformation());
272
273         final Section s = (Section) (psa[0].getSections().get(0));
274         Object JavaDoc p1 = s.getProperty(PropertyIDMap.PID_AUTHOR);
275         Object JavaDoc p2 = s.getProperty(PropertyIDMap.PID_TITLE);
276         Assert.assertEquals(AUTHOR, p1);
277         Assert.assertEquals(TITLE, p2);
278     }
279
280
281
282     /**
283      * <p>Writes a simple property set with two sections to a POIFS and reads it
284      * back in.</p>
285      *
286      * @exception IOException if an I/O exception occurs
287      * @exception WritingNotSupportedException if HPSF does not yet support
288      * a variant type to be written
289      */

290     public void testWriteTwoSections()
291         throws WritingNotSupportedException, IOException JavaDoc
292     {
293         final String JavaDoc STREAM_NAME = "PropertySetStream";
294         final String JavaDoc SECTION1 = "Section 1";
295         final String JavaDoc SECTION2 = "Section 2";
296
297         final File JavaDoc dataDir =
298             new File JavaDoc(System.getProperty("HPSF.testdata.path"));
299         final File JavaDoc filename = new File JavaDoc(dataDir, POI_FS);
300         filename.deleteOnExit();
301         final OutputStream JavaDoc out = new FileOutputStream JavaDoc(filename);
302
303         final POIFSFileSystem poiFs = new POIFSFileSystem();
304         final MutablePropertySet ps = new MutablePropertySet();
305         ps.clearSections();
306
307         final ClassID formatID = new ClassID();
308         formatID.setBytes(new byte[]{0, 1, 2, 3, 4, 5, 6, 7,
309                                      8, 9, 10, 11, 12, 13, 14, 15});
310         final MutableSection s1 = new MutableSection();
311         s1.setFormatID(formatID);
312         s1.setProperty(2, SECTION1);
313         ps.addSection(s1);
314
315         final MutableSection s2 = new MutableSection();
316         s2.setFormatID(formatID);
317         s2.setProperty(2, SECTION2);
318         ps.addSection(s2);
319
320         poiFs.createDocument(ps.toInputStream(), STREAM_NAME);
321         poiFs.writeFilesystem(out);
322         out.close();
323
324         /* Read the POIFS: */
325         final PropertySet[] psa = new PropertySet[1];
326         final POIFSReader r = new POIFSReader();
327         r.registerListener(new POIFSReaderListener()
328             {
329                 public void processPOIFSReaderEvent
330                     (final POIFSReaderEvent event)
331                 {
332                     try
333                     {
334                         psa[0] = PropertySetFactory.create(event.getStream());
335                     }
336                     catch (Exception JavaDoc ex)
337                     {
338                         ex.printStackTrace();
339                         throw new RuntimeException JavaDoc(ex.toString());
340                         /* FIXME (2): Replace the previous line by the following
341                          * one once we no longer need JDK 1.3 compatibility. */

342                         // throw new RuntimeException(ex);
343
}
344                 }
345             },
346             STREAM_NAME);
347         r.read(new FileInputStream JavaDoc(filename));
348         Assert.assertNotNull(psa[0]);
349         Section s = (Section) (psa[0].getSections().get(0));
350         assertEquals(s.getFormatID(), formatID);
351         Object JavaDoc p = s.getProperty(2);
352         Assert.assertEquals(SECTION1, p);
353         s = (Section) (psa[0].getSections().get(1));
354         p = s.getProperty(2);
355         Assert.assertEquals(SECTION2, p);
356     }
357
358
359
360     static class MyPOIFSReaderListener implements POIFSReaderListener
361     {
362         public void processPOIFSReaderEvent(final POIFSReaderEvent event)
363         {
364             try
365             {
366                 PropertySetFactory.create(event.getStream());
367             }
368             catch (Exception JavaDoc ex)
369             {
370                 fail(org.apache.poi.hpsf.Util.toString(ex));
371             }
372         }
373     }
374
375
376
377     private static final int CODEPAGE_DEFAULT = -1;
378     private static final int CODEPAGE_1252 = 1252;
379     private static final int CODEPAGE_UTF8 = Constants.CP_UTF8;
380     private static final int CODEPAGE_UTF16 = Constants.CP_UTF16;
381
382
383
384     /**
385      * <p>Writes and reads back various variant types and checks whether the
386      * stuff that has been read back equals the stuff that was written.</p>
387      */

388     public void testVariantTypes()
389     {
390         Throwable JavaDoc t = null;
391         final int codepage = CODEPAGE_DEFAULT;
392         if (!hasProperDefaultCharset())
393         {
394             System.err.println(IMPROPER_DEFAULT_CHARSET_MESSAGE +
395                 " This testcase is skipped.");
396             return;
397         }
398
399         try
400         {
401             check(Variant.VT_EMPTY, null, codepage);
402             check(Variant.VT_BOOL, new Boolean JavaDoc(true), codepage);
403             check(Variant.VT_BOOL, new Boolean JavaDoc(false), codepage);
404             check(Variant.VT_CF, new byte[]{0}, codepage);
405             check(Variant.VT_CF, new byte[]{0, 1}, codepage);
406             check(Variant.VT_CF, new byte[]{0, 1, 2}, codepage);
407             check(Variant.VT_CF, new byte[]{0, 1, 2, 3}, codepage);
408             check(Variant.VT_CF, new byte[]{0, 1, 2, 3, 4}, codepage);
409             check(Variant.VT_CF, new byte[]{0, 1, 2, 3, 4, 5}, codepage);
410             check(Variant.VT_CF, new byte[]{0, 1, 2, 3, 4, 5, 6}, codepage);
411             check(Variant.VT_CF, new byte[]{0, 1, 2, 3, 4, 5, 6, 7}, codepage);
412             check(Variant.VT_I2, new Integer JavaDoc(27), codepage);
413             check(Variant.VT_I4, new Long JavaDoc(28), codepage);
414             check(Variant.VT_FILETIME, new Date JavaDoc(), codepage);
415
416             check(Variant.VT_LPSTR,
417                   "", codepage);
418             check(Variant.VT_LPSTR,
419                   "\u00e4", codepage);
420             check(Variant.VT_LPSTR,
421                   "\u00e4\u00f6", codepage);
422             check(Variant.VT_LPSTR,
423                   "\u00e4\u00f6\u00fc", codepage);
424             check(Variant.VT_LPSTR,
425                   "\u00e4\u00f6\u00fc\u00df", codepage);
426             check(Variant.VT_LPSTR,
427                   "\u00e4\u00f6\u00fc\u00df\u00c4", codepage);
428             check(Variant.VT_LPSTR,
429                   "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6", codepage);
430             check(Variant.VT_LPSTR,
431                   "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc", codepage);
432
433             check(Variant.VT_LPWSTR,
434                   "", codepage);
435             check(Variant.VT_LPWSTR,
436                   "\u00e4", codepage);
437             check(Variant.VT_LPWSTR,
438                   "\u00e4\u00f6", codepage);
439             check(Variant.VT_LPWSTR,
440                   "\u00e4\u00f6\u00fc", codepage);
441             check(Variant.VT_LPWSTR,
442                   "\u00e4\u00f6\u00fc\u00df", codepage);
443             check(Variant.VT_LPWSTR,
444                   "\u00e4\u00f6\u00fc\u00df\u00c4", codepage);
445             check(Variant.VT_LPWSTR,
446                   "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6", codepage);
447             check(Variant.VT_LPWSTR,
448                   "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc", codepage);
449         }
450         catch (Exception JavaDoc ex)
451         {
452             t = ex;
453         }
454         catch (Error JavaDoc ex)
455         {
456             t = ex;
457         }
458         if (t != null)
459             fail(org.apache.poi.hpsf.Util.toString(t));
460     }
461
462
463
464     /**
465      * <p>Writes and reads back strings using several different codepages and
466      * checks whether the stuff that has been read back equals the stuff that
467      * was written.</p>
468      */

469     public void testCodepages()
470     {
471         Throwable JavaDoc thr = null;
472         final int[] validCodepages = new int[]
473             {CODEPAGE_DEFAULT, CODEPAGE_UTF8, CODEPAGE_UTF16, CODEPAGE_1252};
474         for (int i = 0; i < validCodepages.length; i++)
475         {
476             final int cp = validCodepages[i];
477             if (cp == -1 && !hasProperDefaultCharset())
478             {
479                 System.err.println(IMPROPER_DEFAULT_CHARSET_MESSAGE +
480                      " This testcase is skipped for the default codepage.");
481                 continue;
482             }
483
484             final long t = cp == CODEPAGE_UTF16 ? Variant.VT_LPWSTR
485                                                 : Variant.VT_LPSTR;
486             try
487             {
488                 check(t, "", cp);
489                 check(t, "\u00e4", cp);
490                 check(t, "\u00e4\u00f6", cp);
491                 check(t, "\u00e4\u00f6\u00fc", cp);
492                 check(t, "\u00e4\u00f6\u00fc\u00c4", cp);
493                 check(t, "\u00e4\u00f6\u00fc\u00c4\u00d6", cp);
494                 check(t, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc", cp);
495                 check(t, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp);
496                 if (cp == Constants.CP_UTF16 || cp == Constants.CP_UTF8)
497                     check(t, "\u79D1\u5B78", cp);
498             }
499             catch (Exception JavaDoc ex)
500             {
501                 thr = ex;
502             }
503             catch (Error JavaDoc ex)
504             {
505                 thr = ex;
506             }
507             if (thr != null)
508                 fail(org.apache.poi.hpsf.Util.toString(thr) +
509                      " with codepage " + cp);
510         }
511
512         final int[] invalidCodepages = new int[] {0, 1, 2, 4711, 815};
513         for (int i = 0; i < invalidCodepages.length; i++)
514         {
515             int cp = invalidCodepages[i];
516             final long type = cp == CODEPAGE_UTF16 ? Variant.VT_LPWSTR
517                                                    : Variant.VT_LPSTR;
518             try
519             {
520                 check(type, "", cp);
521                 check(type, "\u00e4", cp);
522                 check(type, "\u00e4\u00f6", cp);
523                 check(type, "\u00e4\u00f6\u00fc", cp);
524                 check(type, "\u00e4\u00f6\u00fc\u00c4", cp);
525                 check(type, "\u00e4\u00f6\u00fc\u00c4\u00d6", cp);
526                 check(type, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc", cp);
527                 check(type, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp);
528                 fail("UnsupportedEncodingException for codepage " + cp +
529                      " expected.");
530             }
531             catch (UnsupportedEncodingException JavaDoc ex)
532             {
533                 /* This is the expected behaviour. */
534             }
535             catch (Exception JavaDoc ex)
536             {
537                 thr = ex;
538             }
539             catch (Error JavaDoc ex)
540             {
541                 thr = ex;
542             }
543             if (thr != null)
544                 fail(org.apache.poi.hpsf.Util.toString(thr));
545         }
546
547     }
548
549
550
551     /**
552      * <p>Tests whether writing 8-bit characters to a Unicode property
553      * succeeds.</p>
554      */

555     public void testUnicodeWrite8Bit()
556     {
557         final String JavaDoc TITLE = "This is a sample title";
558         final MutablePropertySet mps = new MutablePropertySet();
559         final MutableSection ms = (MutableSection) mps.getSections().get(0);
560         ms.setFormatID(SectionIDMap.SUMMARY_INFORMATION_ID);
561         final MutableProperty p = new MutableProperty();
562         p.setID(PropertyIDMap.PID_TITLE);
563         p.setType(Variant.VT_LPSTR);
564         p.setValue(TITLE);
565         ms.setProperty(p);
566
567         Throwable JavaDoc t = null;
568         try
569         {
570             ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc();
571             mps.write(out);
572             out.close();
573             byte[] bytes = out.toByteArray();
574
575             PropertySet psr = new PropertySet(bytes);
576             assertTrue(psr.isSummaryInformation());
577             Section sr = (Section) psr.getSections().get(0);
578             String JavaDoc title = (String JavaDoc) sr.getProperty(PropertyIDMap.PID_TITLE);
579             assertEquals(TITLE, title);
580         }
581         catch (WritingNotSupportedException e)
582         {
583             t = e;
584         }
585         catch (IOException JavaDoc e)
586         {
587             t = e;
588         }
589         catch (NoPropertySetStreamException e)
590         {
591             t = e;
592         }
593         if (t != null)
594             fail(t.getMessage());
595     }
596
597
598
599     /**
600      * <p>Writes a property and reads it back in.</p>
601      *
602      * @param variantType The property's variant type.
603      * @param value The property's value.
604      * @throws UnsupportedVariantTypeException if the variant is not supported.
605      * @throws IOException if an I/O exception occurs.
606      */

607     private void check(final long variantType, final Object JavaDoc value,
608                        final int codepage)
609         throws UnsupportedVariantTypeException, IOException JavaDoc,
610                ReadingNotSupportedException, UnsupportedEncodingException JavaDoc
611     {
612         final ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc();
613         VariantSupport.write(out, variantType, value, codepage);
614         out.close();
615         final byte[] b = out.toByteArray();
616         final Object JavaDoc objRead =
617             VariantSupport.read(b, 0, b.length + LittleEndian.INT_SIZE,
618                                 variantType, codepage);
619         if (objRead instanceof byte[])
620         {
621             final int diff = diff((byte[]) value, (byte[]) objRead);
622             if (diff >= 0)
623                 fail("Byte arrays are different. First different byte is at " +
624                      "index " + diff + ".");
625         }
626         else
627             if (value != null && !value.equals(objRead))
628             {
629                 fail("Expected: \"" + value + "\" but was: \"" + objRead +
630                      "\". Codepage: " + codepage +
631                      (codepage == -1 ?
632                       " (" + System.getProperty("file.encoding") + ")." : "."));
633             }
634             else
635                 assertEquals(value, objRead);
636     }
637
638
639
640     /**
641      * <p>Compares two byte arrays.</p>
642      *
643      * @param a The first byte array
644      * @param b The second byte array
645      * @return The index of the first byte that is different. If the byte arrays
646      * are equal, -1 is returned.
647      */

648     private int diff(final byte[] a, final byte[] b)
649     {
650         final int min = Math.min(a.length, b.length);
651         for (int i = 0; i < min; i++)
652             if (a[i] != b[i])
653                 return i;
654         if (a.length != b.length)
655             return min;
656         return -1;
657     }
658
659
660
661     /**
662      * <p>This test method does a write and read back test with all POI
663      * filesystems in the "data" directory by performing the following
664      * actions for each file:</p>
665      *
666      * <ul>
667      *
668      * <li><p>Read its property set streams.</p></li>
669      *
670      * <li><p>Create a new POI filesystem containing the origin file's
671      * property set streams.</p></li>
672      *
673      * <li><p>Read the property set streams from the POI filesystem just
674      * created.</p></li>
675      *
676      * <li><p>Compare each property set stream with the corresponding one from
677      * the origin file and check whether they are equal.</p></li>
678      *
679      * </ul>
680      */

681     public void testRecreate()
682     {
683         final File JavaDoc dataDir =
684             new File JavaDoc(System.getProperty("HPSF.testdata.path"));
685         final File JavaDoc[] fileList = dataDir.listFiles(new FileFilter JavaDoc()
686             {
687                 public boolean accept(final File JavaDoc f)
688                 {
689                     return f.getName().startsWith("Test");
690                 }
691             });
692         for (int i = 0; i < fileList.length; i++)
693             testRecreate(fileList[i]);
694     }
695
696
697
698     /**
699      * <p>Performs the check described in {@link #testRecreate()} for a single
700      * POI filesystem.</p>
701      *
702      * @param f the POI filesystem to check
703      */

704     private void testRecreate(final File JavaDoc f)
705     {
706         System.out.println("Recreating file \"" + f + "\"");
707         try
708         {
709             /* Read the POI filesystem's property set streams: */
710             final POIFile[] psf1 = Util.readPropertySets(f);
711
712             /* Create a new POI filesystem containing the origin file's
713              * property set streams: */

714             final File JavaDoc copy = TempFile.createTempFile(f.getName(), "");
715             copy.deleteOnExit();
716             final OutputStream JavaDoc out = new FileOutputStream JavaDoc(copy);
717             final POIFSFileSystem poiFs = new POIFSFileSystem();
718             for (int i = 0; i < psf1.length; i++)
719             {
720                 final InputStream JavaDoc in =
721                     new ByteArrayInputStream JavaDoc(psf1[i].getBytes());
722                 final PropertySet psIn = PropertySetFactory.create(in);
723                 final MutablePropertySet psOut = new MutablePropertySet(psIn);
724                 final ByteArrayOutputStream JavaDoc psStream =
725                     new ByteArrayOutputStream JavaDoc();
726                 psOut.write(psStream);
727                 psStream.close();
728                 final byte[] streamData = psStream.toByteArray();
729                 poiFs.createDocument(new ByteArrayInputStream JavaDoc(streamData),
730                                      psf1[i].getName());
731                 poiFs.writeFilesystem(out);
732             }
733             out.close();
734
735
736             /* Read the property set streams from the POI filesystem just
737              * created. */

738             final POIFile[] psf2 = Util.readPropertySets(copy);
739             for (int i = 0; i < psf2.length; i++)
740             {
741                 final byte[] bytes1 = psf1[i].getBytes();
742                 final byte[] bytes2 = psf2[i].getBytes();
743                 final InputStream JavaDoc in1 = new ByteArrayInputStream JavaDoc(bytes1);
744                 final InputStream JavaDoc in2 = new ByteArrayInputStream JavaDoc(bytes2);
745                 final PropertySet ps1 = PropertySetFactory.create(in1);
746                 final PropertySet ps2 = PropertySetFactory.create(in2);
747             
748                 /* Compare the property set stream with the corresponding one
749                  * from the origin file and check whether they are equal. */

750                 assertEquals("Equality for file " + f.getName(), ps1, ps2);
751             }
752         }
753         catch (Exception JavaDoc ex)
754         {
755             handle(ex);
756         }
757     }
758
759
760
761     /**
762      * <p>Tests writing and reading back a proper dictionary.</p>
763      */

764     public void testDictionary()
765     {
766         try
767         {
768             final File JavaDoc copy = TempFile.createTempFile("Test-HPSF", "ole2");
769             copy.deleteOnExit();
770
771             /* Write: */
772             final OutputStream JavaDoc out = new FileOutputStream JavaDoc(copy);
773             final POIFSFileSystem poiFs = new POIFSFileSystem();
774             final MutablePropertySet ps1 = new MutablePropertySet();
775             final MutableSection s = (MutableSection) ps1.getSections().get(0);
776             final Map JavaDoc m = new HashMap JavaDoc(3, 1.0f);
777             m.put(new Long JavaDoc(1), "String 1");
778             m.put(new Long JavaDoc(2), "String 2");
779             m.put(new Long JavaDoc(3), "String 3");
780             s.setDictionary(m);
781             s.setFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID);
782             int codepage = Constants.CP_UNICODE;
783             s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
784                           new Integer JavaDoc(codepage));
785             poiFs.createDocument(ps1.toInputStream(), "Test");
786             poiFs.writeFilesystem(out);
787             out.close();
788
789             /* Read back: */
790             final POIFile[] psf = Util.readPropertySets(copy);
791             Assert.assertEquals(1, psf.length);
792             final byte[] bytes = psf[0].getBytes();
793             final InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(bytes);
794             final PropertySet ps2 = PropertySetFactory.create(in);
795
796             /* Check if the result is a DocumentSummaryInformation stream, as
797              * specified. */

798             assertTrue(ps2.isDocumentSummaryInformation());
799
800             /* Compare the property set stream with the corresponding one
801              * from the origin file and check whether they are equal. */

802             assertEquals(ps1, ps2);
803         }
804         catch (Exception JavaDoc ex)
805         {
806             handle(ex);
807         }
808     }
809
810
811
812     /**
813      * <p>Tests writing and reading back a proper dictionary with an invalid
814      * codepage. (HPSF writes Unicode dictionaries only.)</p>
815      */

816     public void testDictionaryWithInvalidCodepage()
817     {
818         try
819         {
820             final File JavaDoc copy = TempFile.createTempFile("Test-HPSF", "ole2");
821             copy.deleteOnExit();
822
823             /* Write: */
824             final OutputStream JavaDoc out = new FileOutputStream JavaDoc(copy);
825             final POIFSFileSystem poiFs = new POIFSFileSystem();
826             final MutablePropertySet ps1 = new MutablePropertySet();
827             final MutableSection s = (MutableSection) ps1.getSections().get(0);
828             final Map JavaDoc m = new HashMap JavaDoc(3, 1.0f);
829             m.put(new Long JavaDoc(1), "String 1");
830             m.put(new Long JavaDoc(2), "String 2");
831             m.put(new Long JavaDoc(3), "String 3");
832             s.setDictionary(m);
833             s.setFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID);
834             int codepage = 12345;
835             s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
836                           new Integer JavaDoc(codepage));
837             poiFs.createDocument(ps1.toInputStream(), "Test");
838             poiFs.writeFilesystem(out);
839             out.close();
840             fail("This testcase did not detect the invalid codepage value.");
841         }
842         catch (IllegalPropertySetDataException ex)
843         {
844             assertTrue(true);
845         }
846         catch (Exception JavaDoc ex)
847         {
848             handle(ex);
849         }
850     }
851
852
853
854     /**
855      * <p>Handles unexpected exceptions in testcases.</p>
856      *
857      * @param ex The exception that has been thrown.
858      */

859     private void handle(final Exception JavaDoc ex)
860     {
861         final StringWriter JavaDoc sw = new StringWriter JavaDoc();
862         final PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw);
863         Throwable JavaDoc t = ex;
864         while (t != null)
865         {
866             t.printStackTrace(pw);
867             if (t instanceof HPSFRuntimeException)
868                 t = ((HPSFRuntimeException) t).getReason();
869             else
870                 t = null;
871             if (t != null)
872                 pw.println("Caused by:");
873         }
874         pw.close();
875         try
876         {
877             sw.close();
878         }
879         catch (IOException JavaDoc ex2)
880         {
881             ex.printStackTrace();
882         }
883         fail(sw.toString());
884     }
885
886
887
888     /**
889      * <p>Returns the display name of the default character set.</p>
890      *
891      * @return the display name of the default character set.
892      */

893     private String JavaDoc getDefaultCharsetName()
894     {
895         final String JavaDoc charSetName = System.getProperty("file.encoding");
896         final Charset JavaDoc charSet = Charset.forName(charSetName);
897         return charSet.displayName();
898     }
899
900
901
902     /**
903      * <p>In order to execute tests with characters beyond US-ASCII, this
904      * method checks whether the application has is runing in an environment
905      * where the default character set is 16-bit-capable.</p>
906      */

907     private boolean hasProperDefaultCharset()
908     {
909         final String JavaDoc charSetName = System.getProperty("file.encoding");
910         final Charset JavaDoc charSet = Charset.forName(charSetName);
911         return charSet.newEncoder().canEncode('\u00e4');
912     }
913
914
915
916     /**
917      * <p>Runs the test cases stand-alone.</p>
918      */

919     public static void main(final String JavaDoc[] args) throws Throwable JavaDoc
920     {
921         System.setProperty("HPSF.testdata.path",
922                            "./src/testcases/org/apache/poi/hpsf/data");
923         junit.textui.TestRunner.run(TestWrite.class);
924     }
925
926 }
927
Popular Tags