Modified: poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java?rev=1793596&r1=1793595&r2=1793596&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java (original) +++ poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java Tue May 2 23:27:27 2017 @@ -17,135 +17,62 @@ package org.apache.poi.hpsf.basic; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Random; -import junit.framework.TestCase; - -import org.apache.poi.hpsf.*; +import org.apache.poi.hpsf.CustomProperties; +import org.apache.poi.hpsf.DocumentSummaryInformation; +import org.apache.poi.hpsf.HPSFException; +import org.apache.poi.hpsf.PropertySetFactory; +import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; /** * Basing on: src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java * This class tests reading and writing of meta data. No actual document is created. All information * is stored in a virtual document in a ByteArrayOutputStream - * @author Matthias G\u00fcnter */ -public final class TestMetaDataIPI extends TestCase{ +public final class TestMetaDataIPI { - private ByteArrayOutputStream bout; //our store - private POIFSFileSystem poifs; - private DirectoryEntry dir; + private POIFSFileSystem poifs ; private DocumentSummaryInformation dsi; private SummaryInformation si; - - + @After + public void tearDown() throws Exception { + poifs.close(); + } + /** * Setup is used to get the document ready. Gets the DocumentSummaryInformation and the * SummaryInformation to reasonable values */ - @Override + @Before public void setUp() throws Exception { - bout = new ByteArrayOutputStream(); - poifs = new POIFSFileSystem(); - dir = poifs.getRoot(); - dsi = null; - try { - DocumentEntry dsiEntry = (DocumentEntry) dir - .getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - DocumentInputStream dis = new DocumentInputStream(dsiEntry); - PropertySet ps = new PropertySet(dis); - dis.close(); - dsi = new DocumentSummaryInformation(ps); - - } catch (FileNotFoundException ex) { - /* - * There is no document summary information yet. We have to create a - * new one. - */ - dsi = PropertySetFactory.newDocumentSummaryInformation(); - assertNotNull(dsi); - } - assertNotNull(dsi); - try { - DocumentEntry dsiEntry = (DocumentEntry) dir - .getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - DocumentInputStream dis = new DocumentInputStream(dsiEntry); - PropertySet ps = new PropertySet(dis); - dis.close(); - si = new SummaryInformation(ps); - - } catch (FileNotFoundException ex) { - /* - * There is no document summary information yet. We have to create a - * new one. - */ - si = PropertySetFactory.newSummaryInformation(); - assertNotNull(si); - } - assertNotNull(dsi); - } - - /** - * Closes the ByteArrayOutputStream and reads it into a ByteArrayInputStream. - * When finished writing information this method is used in the tests to - * start reading from the created document and then the see if the results match. - */ - public void closeAndReOpen() throws IOException, HPSFException { - - dsi.write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME); - si.write(dir, SummaryInformation.DEFAULT_STREAM_NAME); - - si = null; - dsi = null; - poifs.writeFilesystem(bout); - bout.flush(); - - InputStream is = new ByteArrayInputStream(bout.toByteArray()); - assertNotNull(is); - POIFSFileSystem poifs = new POIFSFileSystem(is); - is.close(); - - assertNotNull(poifs); - /* Read the document summary information. */ - DirectoryEntry dir = poifs.getRoot(); - - DocumentEntry dsiEntry = (DocumentEntry) dir - .getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - DocumentInputStream dis = new DocumentInputStream(dsiEntry); - PropertySet ps = new PropertySet(dis); - dis.close(); - dsi = new DocumentSummaryInformation(ps); - - try { - dsiEntry = (DocumentEntry) dir - .getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - dis = new DocumentInputStream(dsiEntry); - ps = new PropertySet(dis); - dis.close(); - si = new SummaryInformation(ps); - - } catch (FileNotFoundException ex) { - /* - * There is no document summary information yet. We have to create a - * new one. - */ - si = PropertySetFactory.newSummaryInformation(); - assertNotNull(si); - } + poifs = new POIFSFileSystem(); + dsi = PropertySetFactory.newDocumentSummaryInformation(); + si = PropertySetFactory.newSummaryInformation(); + dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); + si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); } /** * Sets the most important information in DocumentSummaryInformation and Summary Information and rereads it */ + @Test public void testOne() throws Exception { // DocumentSummaryInformation @@ -201,9 +128,7 @@ public final class TestMetaDataIPI exten * serve as a container for custom properties. */ customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - fail(); - } + assertNotNull(customProperties); /* Insert some custom properties into the container. */ String a1 = (String) customProperties.get("Key1"); @@ -225,22 +150,9 @@ public final class TestMetaDataIPI exten } /** - * multiplies a string - * @param s Input String - * @return the multiplied String - */ - private static String elongate(String s) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < 10000; i++) { - sb.append(s); - sb.append(" "); - } - return sb.toString(); - } - - /** * Test very long input in each of the fields (approx 30-60KB each) */ + @Test public void testTwo() throws Exception { String company = elongate("company"); @@ -324,20 +236,9 @@ public final class TestMetaDataIPI exten /** - * adds strange characters to the string - * @param s Input String - * @return the multiplied String - */ - private static String strangize(String s) { - StringBuilder sb = strangizeInit(s); - - return sb.toString(); - } - - - /** * Tests with strange characters in keys and data (Umlaute etc.) */ + @Test public void testThree() throws Exception { String company = strangize("company"); @@ -423,50 +324,18 @@ public final class TestMetaDataIPI exten /** * Iterative testing: writing, reading etc. */ + @Test public void testFour() throws Exception { for (int i = 1; i < 100; i++) { - setUp(); - testThree(); + testThree(); + closeAndReOpen(); } } - - - /** - * adds strange characters to the string with the adding of unicode characters - * @param s Input String - * @return the multiplied String - */ - private static String strangizeU(String s) { - - StringBuilder sb = strangizeInit(s); - sb.append("\u00e4\u00f6\u00fc\uD840\uDC00"); - return sb.toString(); - } - - private static StringBuilder strangizeInit(String s) { - StringBuilder sb = new StringBuilder(); - String[] umlaute = { "\u00e4", "\u00fc", "\u00f6", "\u00dc", "$", "\u00d6", "\u00dc", - "\u00c9", "\u00d6", "@", "\u00e7", "&" }; - Random rand = new Random(0); // TODO - no Random - tests should be completely deterministic - for (int i = 0; i < 5; i++) { - sb.append(s); - sb.append(" "); - char j = (char) rand.nextInt(220); - j += 33; - // System.out.println(j); - sb.append(">"); - sb.append(Character.valueOf(j)); - sb.append("="); - sb.append(umlaute[rand.nextInt(umlaute.length)]); - sb.append("<"); - } - return sb; - } - /** * Unicode test */ + @Test public void testUnicode() throws Exception { String company = strangizeU("company"); String manager = strangizeU("manager"); @@ -490,11 +359,8 @@ public final class TestMetaDataIPI exten si.setComments(comments); si.setKeywords(keywords); si.setSubject(subject); - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - customProperties = new CustomProperties(); - } - + + CustomProperties customProperties = new CustomProperties(); /* Insert some custom properties into the container. */ customProperties.put(k1, p1); customProperties.put(k2, p2); @@ -529,9 +395,7 @@ public final class TestMetaDataIPI exten * serve as a container for custom properties. */ customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - fail(); - } + assertNotNull(customProperties); /* Insert some custom properties into the container. */ // System.out.println(k1); @@ -552,10 +416,11 @@ public final class TestMetaDataIPI exten * Iterative testing of the unicode test * */ + @Test public void testSix() throws Exception { for (int i = 1; i < 100; i++) { - setUp(); - testUnicode(); + testUnicode(); + closeAndReOpen(); } } @@ -563,6 +428,7 @@ public final class TestMetaDataIPI exten /** * Tests conversion in custom fields and errors */ + @Test public void testConvAndExistence() throws Exception { CustomProperties customProperties = dsi.getCustomProperties(); @@ -656,4 +522,86 @@ public final class TestMetaDataIPI exten assertTrue(customProperties.get("negdouble") instanceof Double); assertTrue(customProperties.get("date") instanceof Date); } + + + /** + * Closes the ByteArrayOutputStream and reads it into a ByteArrayInputStream. + * When finished writing information this method is used in the tests to + * start reading from the created document and then the see if the results match. + */ + private void closeAndReOpen() throws IOException, HPSFException { + dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); + si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + poifs.writeFilesystem(bout); + poifs.close(); + + InputStream is = new ByteArrayInputStream(bout.toByteArray()); + poifs = new POIFSFileSystem(is); + is.close(); + + /* Read the document summary information. */ + DirectoryEntry dir = poifs.getRoot(); + + dsi = (DocumentSummaryInformation)PropertySetFactory.create(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);; + si = (SummaryInformation)PropertySetFactory.create(dir, SummaryInformation.DEFAULT_STREAM_NAME);; + } + + /** + * multiplies a string + * @param s Input String + * @return the multiplied String + */ + private static String elongate(String s) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 10000; i++) { + sb.append(s); + sb.append(" "); + } + return sb.toString(); + } + + /** + * adds strange characters to the string + * @param s Input String + * @return the multiplied String + */ + private static String strangize(String s) { + StringBuilder sb = strangizeInit(s); + + return sb.toString(); + } + + /** + * adds strange characters to the string with the adding of unicode characters + * @param s Input String + * @return the multiplied String + */ + private static String strangizeU(String s) { + + StringBuilder sb = strangizeInit(s); + sb.append("\u00e4\u00f6\u00fc\uD840\uDC00"); + return sb.toString(); + } + + private static StringBuilder strangizeInit(String s) { + StringBuilder sb = new StringBuilder(); + String[] umlaute = { "\u00e4", "\u00fc", "\u00f6", "\u00dc", "$", "\u00d6", "\u00dc", + "\u00c9", "\u00d6", "@", "\u00e7", "&" }; + Random rand = new Random(0); // TODO - no Random - tests should be completely deterministic + for (int i = 0; i < 5; i++) { + sb.append(s); + sb.append(" "); + char j = (char) rand.nextInt(220); + j += 33; + // System.out.println(j); + sb.append(">"); + sb.append(Character.valueOf(j)); + sb.append("="); + sb.append(umlaute[rand.nextInt(umlaute.length)]); + sb.append("<"); + } + return sb; + } }
Modified: poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java?rev=1793596&r1=1793595&r2=1793596&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java (original) +++ poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java Tue May 2 23:27:27 2017 @@ -17,77 +17,214 @@ package org.apache.poi.hpsf.basic; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.InputStream; - -import junit.framework.TestCase; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.poi.POIDataSamples; +import org.apache.poi.hpsf.CustomProperties; +import org.apache.poi.hpsf.CustomProperty; +import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.HPSFException; +import org.apache.poi.hpsf.MarkUnsupportedException; +import org.apache.poi.hpsf.NoPropertySetStreamException; +import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.PropertySetFactory; +import org.apache.poi.poifs.filesystem.DirectoryEntry; +import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; /** - * <p>Tests some HPSF functionality by reading all property sets from all files + * Tests some HPSF functionality by reading all property sets from all files * in the "data" directory. If you want to ensure HPSF can deal with a certain - * OLE2 file, just add it to the "data" directory and run this test case.</p> + * OLE2 file, just add it to the "data" directory and run this test case. */ -public class TestReadAllFiles extends TestCase { - private static String[] excludes = new String[] {}; +@RunWith(Parameterized.class) +public class TestReadAllFiles { + private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); + + @Parameters(name="{index}: {0} using {1}") + public static Iterable<Object[]> files() { + final List<Object[]> files = new ArrayList<Object[]>(); + + _samples.getFile("").listFiles(new FileFilter() { + @Override + public boolean accept(final File f) { + if (f.getName().startsWith("Test")) { // && f.getName().equals("TestCorel.shw") + files.add(new Object[]{ f }); + } + return false; + } + }); + + return files; + } + + @Parameter(value=0) + public File file; /** - * <p>This test methods reads all property set streams from all POI - * filesystems in the "data" directory.</p> - * - * @throws IOException - * @throws HPSFException + * This test methods reads all property set streams from all POI + * filesystems in the "data" directory. */ - public void testReadAllFiles() throws IOException, HPSFException - { - POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - final File dataDir = _samples.getFile(""); - final File[] fileList = dataDir.listFiles(new FileFilter() - { - @Override - public boolean accept(final File f) - { - // exclude files that we know will fail - return f.isFile() && checkExclude(f); - } - }); - - for (final File f : fileList) { - /* Read the POI filesystem's property set streams: */ - final POIFile[] psf1 = Util.readPropertySets(f); - - for (int j = 0; j < psf1.length; j++) - { - final InputStream in = - new ByteArrayInputStream(psf1[j].getBytes()); - try { - PropertySetFactory.create(in); - } catch (Exception e) { - throw new IOException("While handling file: " + f + " at " + j, e); - } + @Test + public void read() throws IOException, NoPropertySetStreamException, MarkUnsupportedException { + /* Read the POI filesystem's property set streams: */ + for (POIFile pf : Util.readPropertySets(file)) { + final InputStream in = new ByteArrayInputStream(pf.getBytes()); + try { + PropertySetFactory.create(in); + } finally { + in.close(); } } } + + + /** + * This test method does a write and read back test with all POI + * filesystems in the "data" directory by performing the following + * actions for each file:<p> + * + * <ul> + * <li>Read its property set streams. + * <li>Create a new POI filesystem containing the origin file's property set streams. + * <li>Read the property set streams from the POI filesystem just created. + * <li>Compare each property set stream with the corresponding one from + * the origin file and check whether they are equal. + * </ul> + */ + @Test + public void recreate() throws IOException, HPSFException { + /* Read the POI filesystem's property set streams: */ + Map<String,PropertySet> psMap = new HashMap<String,PropertySet>(); + + /* Create a new POI filesystem containing the origin file's + * property set streams: */ + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + final POIFSFileSystem poiFs = new POIFSFileSystem(); + for (POIFile poifile : Util.readPropertySets(file)) { + final InputStream in = new ByteArrayInputStream(poifile.getBytes()); + final PropertySet psIn = PropertySetFactory.create(in); + psMap.put(poifile.getName(), psIn); + bos.reset(); + psIn.write(bos); + poiFs.createDocument(new ByteArrayInputStream(bos.toByteArray()), poifile.getName()); + } + /* Read the property set streams from the POI filesystem just + * created. */ + for (Map.Entry<String,PropertySet> me : psMap.entrySet()) { + final PropertySet ps1 = me.getValue(); + final PropertySet ps2 = PropertySetFactory.create(poiFs.getRoot(), me.getKey()); + assertNotNull(ps2); + + /* Compare the property set stream with the corresponding one + * from the origin file and check whether they are equal. */ + + // Because of missing 0-paddings in the original input files, the bytes might differ. + // This fixes the comparison + String ps1str = ps1.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)",""); + String ps2str = ps2.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)",""); + + assertEquals("Equality for file " + file.getName(), ps1str, ps2str); + } + poiFs.close(); + } + + /** + * <p>This test method checks whether DocumentSummary information streams + * can be read. This is done by opening all "Test*" files in the 'poifs' directrory + * pointed to by the "POI.testdata.path" system property, trying to extract + * the document summary information stream in the root directory and calling + * its get... methods.</p> + * @throws Exception + */ + @Test + public void readDocumentSummaryInformation() throws Exception { + /* Read a test document <em>doc</em> into a POI filesystem. */ + NPOIFSFileSystem poifs = new NPOIFSFileSystem(file, true); + try { + final DirectoryEntry dir = poifs.getRoot(); + /* + * If there is a document summry information stream, read it from + * the POI filesystem. + */ + if (dir.hasEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)) { + final DocumentSummaryInformation dsi = TestWriteWellKnown.getDocumentSummaryInformation(poifs); + + /* Execute the get... methods. */ + dsi.getByteCount(); + dsi.getByteOrder(); + dsi.getCategory(); + dsi.getCompany(); + dsi.getCustomProperties(); + // FIXME dsi.getDocparts(); + // FIXME dsi.getHeadingPair(); + dsi.getHiddenCount(); + dsi.getLineCount(); + dsi.getLinksDirty(); + dsi.getManager(); + dsi.getMMClipCount(); + dsi.getNoteCount(); + dsi.getParCount(); + dsi.getPresentationFormat(); + dsi.getScale(); + dsi.getSlideCount(); + } + } finally { + poifs.close(); + } + } + /** - * Returns true if the file should be checked, false if it should be excluded. + * <p>Tests the simplified custom properties by reading them from the + * available test files.</p> * - * @param f - * @return + * @throws Throwable if anything goes wrong. */ - public static boolean checkExclude(File f) { - for(String exclude : excludes) { - if(f.getAbsolutePath().endsWith(exclude)) { - return false; + @Test + public void readCustomPropertiesFromFiles() throws Exception { + /* Read a test document <em>doc</em> into a POI filesystem. */ + NPOIFSFileSystem poifs = new NPOIFSFileSystem(file); + try { + /* + * If there is a document summry information stream, read it from + * the POI filesystem, else create a new one. + */ + DocumentSummaryInformation dsi = TestWriteWellKnown.getDocumentSummaryInformation(poifs); + if (dsi == null) { + dsi = PropertySetFactory.newDocumentSummaryInformation(); + } + final CustomProperties cps = dsi.getCustomProperties(); + + if (cps == null) { + /* The document does not have custom properties. */ + return; } + + for (CustomProperty cp : cps.values()) { + cp.getName(); + cp.getValue(); + } + } finally { + poifs.close(); } - - return true; } + } Modified: poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java?rev=1793596&r1=1793595&r2=1793596&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java (original) +++ poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java Tue May 2 23:27:27 2017 @@ -18,6 +18,7 @@ package org.apache.poi.hpsf.basic; import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; @@ -27,7 +28,6 @@ import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; @@ -37,6 +37,7 @@ import java.io.UnsupportedEncodingExcept import java.nio.charset.Charset; import java.util.Date; import java.util.HashMap; +import java.util.List; import java.util.Locale; import java.util.Map; @@ -73,28 +74,29 @@ import org.apache.poi.poifs.filesystem.N import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.CodePageUtil; import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; +import org.apache.poi.util.LittleEndianConsts; import org.apache.poi.util.TempFile; -import org.junit.Before; +import org.junit.Assume; +import org.junit.BeforeClass; import org.junit.Test; /** - * <p>Tests HPSF's writing functionality.</p> + * Tests HPSF's writing functionality */ -public class TestWrite -{ +public class TestWrite { private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); + private static final int CODEPAGE_DEFAULT = -1; - static final String POI_FS = "TestHPSFWritingFunctionality.doc"; + private static final String POI_FS = "TestHPSFWritingFunctionality.doc"; - static final int BYTE_ORDER = 0xfffe; - static final int FORMAT = 0x0000; - static final int OS_VERSION = 0x00020A04; - static final int[] SECTION_COUNT = {1, 2}; - static final boolean[] IS_SUMMARY_INFORMATION = {true, false}; - static final boolean[] IS_DOCUMENT_SUMMARY_INFORMATION = {false, true}; + private static final int BYTE_ORDER = 0xfffe; + private static final int FORMAT = 0x0000; + private static final int OS_VERSION = 0x00020A04; + private static final int[] SECTION_COUNT = {1, 2}; + private static final boolean[] IS_SUMMARY_INFORMATION = {true, false}; + private static final boolean[] IS_DOCUMENT_SUMMARY_INFORMATION = {false, true}; - final String IMPROPER_DEFAULT_CHARSET_MESSAGE = + private static final String IMPROPER_DEFAULT_CHARSET_MESSAGE = "Your default character set is " + getDefaultCharsetName() + ". However, this testcase must be run in an environment " + "with a default character set supporting at least " + @@ -104,12 +106,11 @@ public class TestWrite POIFile[] poiFiles; - @Before - public void setUp() - { + @BeforeClass + public static void setUp() { VariantSupport.setLogUnsupportedTypes(false); } - + /** * <p>Writes an empty property set to a POIFS and reads it back * in.</p> @@ -117,8 +118,7 @@ public class TestWrite * @exception IOException if an I/O exception occurs */ @Test(expected=NoFormatIDException.class) - public void withoutAFormatID() throws Exception - { + public void withoutAFormatID() throws Exception { final File filename = TempFile.createTempFile(POI_FS, ".doc"); /* Create a mutable property set with a section that does not have the @@ -144,8 +144,6 @@ public class TestWrite } } - - /** * <p>Writes an empty property set to a POIFS and reads it back * in.</p> @@ -156,8 +154,7 @@ public class TestWrite */ @Test public void writeEmptyPropertySet() - throws IOException, UnsupportedVariantTypeException - { + throws IOException, UnsupportedVariantTypeException { final File dataDir = _samples.getFile(""); final File filename = new File(dataDir, POI_FS); filename.deleteOnExit(); @@ -203,8 +200,7 @@ public class TestWrite */ @Test public void writeSimplePropertySet() - throws IOException, UnsupportedVariantTypeException - { + throws IOException, UnsupportedVariantTypeException { final String AUTHOR = "Rainer Klute"; final String TITLE = "Test Document"; final File dataDir = _samples.getFile(""); @@ -235,24 +231,17 @@ public class TestWrite /* Read the POIFS: */ final PropertySet[] psa = new PropertySet[1]; final POIFSReader r = new POIFSReader(); - r.registerListener(new POIFSReaderListener() - { - @Override - public void processPOIFSReaderEvent - (final POIFSReaderEvent event) - { - try - { - psa[0] = PropertySetFactory.create(event.getStream()); - } - catch (Exception ex) - { - fail(org.apache.poi.hpsf.Util.toString(ex)); - } + r.registerListener(new POIFSReaderListener() { + @Override + public void processPOIFSReaderEvent(final POIFSReaderEvent event) { + try { + psa[0] = PropertySetFactory.create(event.getStream()); + } catch (Exception ex) { + fail(org.apache.poi.hpsf.Util.toString(ex)); } - - }, - SummaryInformation.DEFAULT_STREAM_NAME); + }}, + SummaryInformation.DEFAULT_STREAM_NAME + ); InputStream stream = new FileInputStream(filename); try { @@ -281,9 +270,7 @@ public class TestWrite * a variant type to be written */ @Test - public void writeTwoSections() - throws WritingNotSupportedException, IOException - { + public void writeTwoSections() throws WritingNotSupportedException, IOException { final String STREAM_NAME = "PropertySetStream"; final String SECTION1 = "Section 1"; final String SECTION2 = "Section 2"; @@ -318,18 +305,12 @@ public class TestWrite /* Read the POIFS: */ final PropertySet[] psa = new PropertySet[1]; final POIFSReader r = new POIFSReader(); - r.registerListener(new POIFSReaderListener() - { + r.registerListener(new POIFSReaderListener() { @Override - public void processPOIFSReaderEvent - (final POIFSReaderEvent event) - { - try - { + public void processPOIFSReaderEvent(final POIFSReaderEvent event) { + try { psa[0] = PropertySetFactory.create(event.getStream()); - } - catch (Exception ex) - { + } catch (Exception ex) { throw new RuntimeException(ex); } } @@ -353,17 +334,12 @@ public class TestWrite - static class MyPOIFSReaderListener implements POIFSReaderListener - { + static class MyPOIFSReaderListener implements POIFSReaderListener { @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - try - { + public void processPOIFSReaderEvent(final POIFSReaderEvent event) { + try { PropertySetFactory.create(event.getStream()); - } - catch (Exception ex) - { + } catch (Exception ex) { fail(org.apache.poi.hpsf.Util.toString(ex)); } } @@ -371,109 +347,52 @@ public class TestWrite - private static final int CODEPAGE_DEFAULT = -1; - private static final int CODEPAGE_1252 = 1252; - private static final int CODEPAGE_UTF8 = CodePageUtil.CP_UTF8; - private static final int CODEPAGE_UTF16 = CodePageUtil.CP_UTF16; - - - /** * <p>Writes and reads back various variant types and checks whether the * stuff that has been read back equals the stuff that was written.</p> + * @throws IOException + * @throws UnsupportedEncodingException + * @throws UnsupportedVariantTypeException + * @throws ReadingNotSupportedException */ @Test - public void variantTypes() - { - Throwable t = null; + public void variantTypes() throws Exception { final int codepage = CODEPAGE_DEFAULT; - if (!hasProperDefaultCharset()) - { - System.err.println(IMPROPER_DEFAULT_CHARSET_MESSAGE + - " This testcase is skipped."); - return; - } + Assume.assumeTrue(IMPROPER_DEFAULT_CHARSET_MESSAGE, hasProperDefaultCharset()); - try - { - check(Variant.VT_EMPTY, null, codepage); - check(Variant.VT_BOOL, Boolean.TRUE, codepage); - check(Variant.VT_BOOL, Boolean.FALSE, codepage); - check( Variant.VT_CF, new byte[] { 8, 0, 0, 0, 1, 0, 0, 0, 1, 2, 3, - 4 }, codepage ); - check(Variant.VT_I4, Integer.valueOf(27), codepage); - check(Variant.VT_I8, Long.valueOf(28), codepage); - check(Variant.VT_R8, new Double(29.0), codepage); - check(Variant.VT_I4, Integer.valueOf(-27), codepage); - check(Variant.VT_I8, Long.valueOf(-28), codepage); - check(Variant.VT_R8, new Double(-29.0), codepage); - check(Variant.VT_FILETIME, new Date(), codepage); - check(Variant.VT_I4, new Integer(Integer.MAX_VALUE), codepage); - check(Variant.VT_I4, new Integer(Integer.MIN_VALUE), codepage); - check(Variant.VT_I8, new Long(Long.MAX_VALUE), codepage); - check(Variant.VT_I8, new Long(Long.MIN_VALUE), codepage); - check(Variant.VT_R8, new Double(Double.MAX_VALUE), codepage); - check(Variant.VT_R8, new Double(Double.MIN_VALUE), codepage); - - check(Variant.VT_LPSTR, - "", codepage); - check(Variant.VT_LPSTR, - "\u00e4", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6\u00fc", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6\u00fc\u00df", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc", codepage); - - check(Variant.VT_LPWSTR, - "", codepage); - check(Variant.VT_LPWSTR, - "\u00e4", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6\u00fc", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6\u00fc\u00df", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc", codepage); - } - catch (Exception ex) - { - t = ex; - } - catch (Error ex) - { - t = ex; - } - if (t != null) - fail(org.apache.poi.hpsf.Util.toString(t)); + check(Variant.VT_EMPTY, null, codepage); + check(Variant.VT_BOOL, Boolean.TRUE, codepage); + check(Variant.VT_BOOL, Boolean.FALSE, codepage); + check( Variant.VT_CF, new byte[] { 8, 0, 0, 0, 1, 0, 0, 0, 1, 2, 3, 4 }, codepage ); + check(Variant.VT_I4, 27, codepage); + check(Variant.VT_I8, 28L, codepage); + check(Variant.VT_R8, 29.0d, codepage); + check(Variant.VT_I4, -27, codepage); + check(Variant.VT_I8, -28L, codepage); + check(Variant.VT_R8, -29.0d, codepage); + check(Variant.VT_FILETIME, new Date(), codepage); + check(Variant.VT_I4, Integer.MAX_VALUE, codepage); + check(Variant.VT_I4, Integer.MIN_VALUE, codepage); + check(Variant.VT_I8, Long.MAX_VALUE, codepage); + check(Variant.VT_I8, Long.MIN_VALUE, codepage); + check(Variant.VT_R8, Double.MAX_VALUE, codepage); + check(Variant.VT_R8, Double.MIN_VALUE, codepage); + checkString(Variant.VT_LPSTR, "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc", codepage); + checkString(Variant.VT_LPWSTR, "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc", codepage); } /** - * <p>Writes and reads back strings using several different codepages and + * Writes and reads back strings using several different codepages and * checks whether the stuff that has been read back equals the stuff that - * was written.</p> + * was written. */ @Test - public void codepages() + public void codepages() throws ReadingNotSupportedException, UnsupportedVariantTypeException, IOException { Throwable thr = null; - final int[] validCodepages = new int[] - {CODEPAGE_DEFAULT, CODEPAGE_UTF8, CODEPAGE_UTF16, CODEPAGE_1252}; + final int[] validCodepages = {CODEPAGE_DEFAULT, CodePageUtil.CP_UTF8, CodePageUtil.CP_UNICODE, CodePageUtil.CP_WINDOWS_1252}; for (final int cp : validCodepages) { if (cp == -1 && !hasProperDefaultCharset()) { @@ -482,65 +401,22 @@ public class TestWrite continue; } - final long t = cp == CODEPAGE_UTF16 ? Variant.VT_LPWSTR - : Variant.VT_LPSTR; - try - { - check(t, "", cp); - check(t, "\u00e4", cp); - check(t, "\u00e4\u00f6", cp); - check(t, "\u00e4\u00f6\u00fc", cp); - check(t, "\u00e4\u00f6\u00fc\u00c4", cp); - check(t, "\u00e4\u00f6\u00fc\u00c4\u00d6", cp); - check(t, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc", cp); - check(t, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp); - if (cp == CodePageUtil.CP_UTF16 || cp == CodePageUtil.CP_UTF8) - check(t, "\u79D1\u5B78", cp); - } - catch (Exception ex) - { - thr = ex; - } - catch (Error ex) - { - thr = ex; + final long t = (cp == CodePageUtil.CP_UNICODE) ? Variant.VT_LPWSTR : Variant.VT_LPSTR; + checkString(t, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp); + if (cp == CodePageUtil.CP_UTF16 || cp == CodePageUtil.CP_UTF8) { + check(t, "\u79D1\u5B78", cp); } - if (thr != null) - fail(org.apache.poi.hpsf.Util.toString(thr) + - " with codepage " + cp); } final int[] invalidCodepages = new int[] {0, 1, 2, 4711, 815}; for (int cp : invalidCodepages) { - final long type = cp == CODEPAGE_UTF16 ? Variant.VT_LPWSTR - : Variant.VT_LPSTR; - try - { - check(type, "", cp); - check(type, "\u00e4", cp); - check(type, "\u00e4\u00f6", cp); - check(type, "\u00e4\u00f6\u00fc", cp); - check(type, "\u00e4\u00f6\u00fc\u00c4", cp); - check(type, "\u00e4\u00f6\u00fc\u00c4\u00d6", cp); - check(type, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc", cp); - check(type, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp); - fail("UnsupportedEncodingException for codepage " + cp + - " expected."); - } - catch (UnsupportedEncodingException ex) - { + final long type = (cp == CodePageUtil.CP_UNICODE) ? Variant.VT_LPWSTR : Variant.VT_LPSTR; + try { + checkString(type, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp); + fail("UnsupportedEncodingException for codepage " + cp + " expected."); + } catch (UnsupportedEncodingException ex) { /* This is the expected behaviour. */ } - catch (Exception ex) - { - thr = ex; - } - catch (Error ex) - { - thr = ex; - } - if (thr != null) - fail(org.apache.poi.hpsf.Util.toString(thr)); } } @@ -548,12 +424,10 @@ public class TestWrite /** - * <p>Tests whether writing 8-bit characters to a Unicode property - * succeeds.</p> + * Tests whether writing 8-bit characters to a Unicode property succeeds. */ @Test - public void unicodeWrite8Bit() - { + public void unicodeWrite8Bit() throws WritingNotSupportedException, IOException, NoPropertySetStreamException { final String TITLE = "This is a sample title"; final MutablePropertySet mps = new MutablePropertySet(); final MutableSection ms = (MutableSection) mps.getSections().get(0); @@ -564,218 +438,57 @@ public class TestWrite p.setValue(TITLE); ms.setProperty(p); - Throwable t = null; - try - { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - mps.write(out); - out.close(); - byte[] bytes = out.toByteArray(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + mps.write(out); + out.close(); + byte[] bytes = out.toByteArray(); - PropertySet psr = new PropertySet(bytes); - assertTrue(psr.isSummaryInformation()); - Section sr = psr.getSections().get(0); - String title = (String) sr.getProperty(PropertyIDMap.PID_TITLE); - assertEquals(TITLE, title); - } - catch (WritingNotSupportedException e) - { - t = e; - } - catch (IOException e) - { - t = e; - } - catch (NoPropertySetStreamException e) - { - t = e; + PropertySet psr = new PropertySet(bytes); + assertTrue(psr.isSummaryInformation()); + Section sr = psr.getSections().get(0); + String title = (String) sr.getProperty(PropertyIDMap.PID_TITLE); + assertEquals(TITLE, title); + } + + private void checkString(final long variantType, final String value, final int codepage) + throws UnsupportedVariantTypeException, IOException, ReadingNotSupportedException, UnsupportedEncodingException { + for (int i=0; i<value.length(); i++) { + check(variantType, value.substring(0, i), codepage); } - if (t != null) - fail(t.getMessage()); } - - /** - * <p>Writes a property and reads it back in.</p> + * Writes a property and reads it back in. * * @param variantType The property's variant type. * @param value The property's value. * @param codepage The codepage to use for writing and reading. * @throws UnsupportedVariantTypeException if the variant is not supported. * @throws IOException if an I/O exception occurs. - * @throws ReadingNotSupportedException - * @throws UnsupportedEncodingException */ - private void check(final long variantType, final Object value, - final int codepage) - throws UnsupportedVariantTypeException, IOException, - ReadingNotSupportedException, UnsupportedEncodingException + private void check(final long variantType, final Object value, final int codepage) + throws UnsupportedVariantTypeException, IOException, ReadingNotSupportedException, UnsupportedEncodingException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); VariantSupport.write(out, variantType, value, codepage); out.close(); final byte[] b = out.toByteArray(); final Object objRead = - VariantSupport.read(b, 0, b.length + LittleEndian.INT_SIZE, - variantType, codepage); - if (objRead instanceof byte[]) - { - byte[] valueB = (byte[])value; - byte[] readB = (byte[])objRead; - if (valueB.length != readB.length) - fail("Byte arrays are different length - expected " + valueB.length + - " but found " + readB.length); - - final int diff = diff(valueB, readB); - if (diff >= 0) - fail("Byte arrays are different. First different byte is at " + - "index " + diff + "."); - } - else - if (value != null && !value.equals(objRead)) - { - fail("Expected: \"" + value + "\" but was: \"" + objRead + - "\". Codepage: " + codepage + - (codepage == -1 ? - " (" + System.getProperty("file.encoding") + ")." : ".")); - } - else - assertEquals(value, objRead); - } - - - - /** - * <p>Compares two byte arrays.</p> - * - * @param a The first byte array - * @param b The second byte array - * @return The index of the first byte that is different. If the byte arrays - * are equal, -1 is returned. - */ - private int diff(final byte[] a, final byte[] b) - { - final int min = Math.min(a.length, b.length); - for (int i = 0; i < min; i++) - if (a[i] != b[i]) - return i; - if (a.length != b.length) - return min; - return -1; - } - - - - /** - * <p>This test method does a write and read back test with all POI - * filesystems in the "data" directory by performing the following - * actions for each file:</p> - * - * <ul> - * - * <li><p>Read its property set streams.</p></li> - * - * <li><p>Create a new POI filesystem containing the origin file's - * property set streams.</p></li> - * - * <li><p>Read the property set streams from the POI filesystem just - * created.</p></li> - * - * <li><p>Compare each property set stream with the corresponding one from - * the origin file and check whether they are equal.</p></li> - * - * </ul> - * @throws IOException - */ - @Test - public void recreate() throws IOException - { - final File dataDir = _samples.getFile(""); - final File[] fileList = dataDir.listFiles(new FileFilter() - { - @Override - public boolean accept(final File f) - { - return f.getName().startsWith("Test") && TestReadAllFiles.checkExclude(f); - } - }); - for (final File file : fileList) { - try { - testRecreate(file); - } catch (Exception e) { - throw new IOException("While handling file " + file, e); - } - } - } - - - - /** - * <p>Performs the check described in {@link #recreate()} for a single - * POI filesystem.</p> - * - * @param f the POI filesystem to check - * @throws IOException - * @throws HPSFException - */ - private void testRecreate(final File f) throws IOException, HPSFException - { - /* Read the POI filesystem's property set streams: */ - final POIFile[] psf1 = Util.readPropertySets(f); - - /* Create a new POI filesystem containing the origin file's - * property set streams: */ - final File copy = TempFile.createTempFile(f.getName(), ""); - copy.deleteOnExit(); - final OutputStream out = new FileOutputStream(copy); - final POIFSFileSystem poiFs = new POIFSFileSystem(); - for (POIFile file : psf1) { - final InputStream in = - new ByteArrayInputStream(file.getBytes()); - final PropertySet psIn = PropertySetFactory.create(in); - final MutablePropertySet psOut = new MutablePropertySet(psIn); - final ByteArrayOutputStream psStream = - new ByteArrayOutputStream(); - psOut.write(psStream); - psStream.close(); - final byte[] streamData = psStream.toByteArray(); - poiFs.createDocument(new ByteArrayInputStream(streamData), - file.getName()); - poiFs.writeFilesystem(out); - } - poiFs.close(); - out.close(); - - - /* Read the property set streams from the POI filesystem just - * created. */ - final POIFile[] psf2 = Util.readPropertySets(copy); - for (int i = 0; i < psf2.length; i++) - { - final byte[] bytes1 = psf1[i].getBytes(); - final byte[] bytes2 = psf2[i].getBytes(); - final InputStream in1 = new ByteArrayInputStream(bytes1); - final InputStream in2 = new ByteArrayInputStream(bytes2); - final PropertySet ps1 = PropertySetFactory.create(in1); - final PropertySet ps2 = PropertySetFactory.create(in2); - - /* Compare the property set stream with the corresponding one - * from the origin file and check whether they are equal. */ - assertEquals("Equality for file " + f.getName(), ps1, ps2); + VariantSupport.read(b, 0, b.length + LittleEndianConsts.INT_SIZE, variantType, codepage); + if (objRead instanceof byte[]) { + assertArrayEquals((byte[])value, (byte[])objRead); + } else if (value != null && !value.equals(objRead)) { + assertEquals(value, objRead); } } - - /** * <p>Tests writing and reading back a proper dictionary.</p> * @throws IOException * @throws HPSFException */ @Test - public void dictionary() throws IOException, HPSFException - { + public void dictionary() throws IOException, HPSFException { final File copy = TempFile.createTempFile("Test-HPSF", "ole2"); copy.deleteOnExit(); @@ -791,17 +504,16 @@ public class TestWrite s.setDictionary(m); s.setFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID[0]); int codepage = CodePageUtil.CP_UNICODE; - s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, - Integer.valueOf(codepage)); + s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, codepage); poiFs.createDocument(ps1.toInputStream(), "Test"); poiFs.writeFilesystem(out); poiFs.close(); out.close(); /* Read back: */ - final POIFile[] psf = Util.readPropertySets(copy); - assertEquals(1, psf.length); - final byte[] bytes = psf[0].getBytes(); + final List<POIFile> psf = Util.readPropertySets(copy); + assertEquals(1, psf.size()); + final byte[] bytes = psf.get(0).getBytes(); final InputStream in = new ByteArrayInputStream(bytes); final PropertySet ps2 = PropertySetFactory.create(in); @@ -1039,8 +751,7 @@ public class TestWrite * @throws HPSFException */ @Test(expected=IllegalPropertySetDataException.class) - public void dictionaryWithInvalidCodepage() throws IOException, HPSFException - { + public void dictionaryWithInvalidCodepage() throws IOException, HPSFException { final File copy = TempFile.createTempFile("Test-HPSF", "ole2"); copy.deleteOnExit(); @@ -1069,22 +780,17 @@ public class TestWrite } } - - /** * <p>Returns the display name of the default character set.</p> * * @return the display name of the default character set. */ - private String getDefaultCharsetName() - { + private static String getDefaultCharsetName() { final String charSetName = System.getProperty("file.encoding"); final Charset charSet = Charset.forName(charSetName); return charSet.displayName(Locale.ROOT); } - - /** * <p>In order to execute tests with characters beyond US-ASCII, this * method checks whether the application is runing in an environment @@ -1093,8 +799,7 @@ public class TestWrite * @return <code>true</code> if the default character set is 16-bit-capable, * else <code>false</code>. */ - private boolean hasProperDefaultCharset() - { + private boolean hasProperDefaultCharset() { final String charSetName = System.getProperty("file.encoding"); final Charset charSet = Charset.forName(charSetName); return charSet.newEncoder().canEncode('\u00e4'); Modified: poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java?rev=1793596&r1=1793595&r2=1793596&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java (original) +++ poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java Tue May 2 23:27:27 2017 @@ -24,9 +24,7 @@ import static org.junit.Assert.assertNul import static org.junit.Assert.assertTrue; import java.io.File; -import java.io.FileFilter; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -51,7 +49,6 @@ import org.apache.poi.hpsf.Variant; import org.apache.poi.hpsf.VariantSupport; import org.apache.poi.hpsf.WritingNotSupportedException; import org.apache.poi.hpsf.wellknown.SectionIDMap; -import org.apache.poi.poifs.filesystem.DirectoryEntry; import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.poi.util.IOUtils; @@ -73,70 +70,6 @@ public class TestWriteWellKnown { VariantSupport.setLogUnsupportedTypes(false); } - /** - * <p>This test method checks whether DocumentSummary information streams - * can be read. This is done by opening all "Test*" files in the 'poifs' directrory - * pointed to by the "POI.testdata.path" system property, trying to extract - * the document summary information stream in the root directory and calling - * its get... methods.</p> - */ - @Test - public void testReadDocumentSummaryInformation() - throws FileNotFoundException, IOException, - NoPropertySetStreamException, MarkUnsupportedException, - UnexpectedPropertySetTypeException - { - POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - final File dataDir = _samples.getFile(""); - final File[] docs = dataDir.listFiles(new FileFilter() - { - @Override - public boolean accept(final File file) - { - return file.isFile() && file.getName().startsWith("Test") && TestReadAllFiles.checkExclude(file); - } - }); - - for (final File doc : docs) { - NPOIFSFileSystem poifs = null; - try { - /* Read a test document <em>doc</em> into a POI filesystem. */ - poifs = new NPOIFSFileSystem(doc, true); - final DirectoryEntry dir = poifs.getRoot(); - /* - * If there is a document summry information stream, read it from - * the POI filesystem. - */ - if (dir.hasEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)) { - final DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); - - /* Execute the get... methods. */ - dsi.getByteCount(); - dsi.getByteOrder(); - dsi.getCategory(); - dsi.getCompany(); - dsi.getCustomProperties(); - // FIXME dsi.getDocparts(); - // FIXME dsi.getHeadingPair(); - dsi.getHiddenCount(); - dsi.getLineCount(); - dsi.getLinksDirty(); - dsi.getManager(); - dsi.getMMClipCount(); - dsi.getNoteCount(); - dsi.getParCount(); - dsi.getPresentationFormat(); - dsi.getScale(); - dsi.getSlideCount(); - } - } catch (Exception e) { - throw new IOException("While handling file " + doc, e); - } finally { - if (poifs != null) poifs.close(); - } - } - } - static final String P_APPLICATION_NAME = "ApplicationName"; static final String P_AUTHOR = "Author"; static final int P_CHAR_COUNT = 4712; @@ -483,15 +416,12 @@ public class TestWriteWellKnown { dsi.removeScale(); dsi.removeSlideCount(); - /* - * <li><p>Write the summary information stream and the document summary - * information stream to the POI filesystem. */ + // Write the summary information stream and the document summary + // information stream to the POI filesystem. si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - /* - * <li><p>Write the POI filesystem to a (temporary) file <em>doc3</em> - * and close the latter. */ + // Write the POI filesystem to a (temporary) file doc3 and close the latter. FileOutputStream out = new FileOutputStream(fileOut); poifs.writeFilesystem(out); out.close(); @@ -501,9 +431,9 @@ public class TestWriteWellKnown { } /* - * Open <em>doc3</em> for reading and check summary information + * Open {@code doc3} for reading and check summary information * and document summary information. All properties removed before must not - * be found in the property streams of <em>doc3</em>. + * be found in the property streams of {@code doc3}. */ private static CustomProperties write3rdFile(File fileIn, File fileOut) throws Exception { NPOIFSFileSystem poifs = new NPOIFSFileSystem(fileIn, false); @@ -571,7 +501,12 @@ public class TestWriteWellKnown { return si; } - private static DocumentSummaryInformation getDocumentSummaryInformation(NPOIFSFileSystem poifs) throws Exception { + static DocumentSummaryInformation getDocumentSummaryInformation(NPOIFSFileSystem poifs) + throws IOException, NoPropertySetStreamException, UnexpectedPropertySetTypeException, MarkUnsupportedException { + if (!poifs.getRoot().hasEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)) { + return null; + } + DocumentInputStream dis = poifs.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME); PropertySet ps = new PropertySet(dis); DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps); @@ -579,83 +514,8 @@ public class TestWriteWellKnown { return dsi; } - - - /** - * <p>Tests the simplified custom properties by reading them from the - * available test files.</p> - * - * @throws Throwable if anything goes wrong. - */ - @Test - public void testReadCustomPropertiesFromFiles() throws Throwable - { - final AllDataFilesTester.TestTask task = new AllDataFilesTester.TestTask() - { - @Override - public void runTest(final File file) throws FileNotFoundException, - IOException, NoPropertySetStreamException, - MarkUnsupportedException, - UnexpectedPropertySetTypeException - { - /* Read a test document <em>doc</em> into a POI filesystem. */ - NPOIFSFileSystem poifs = null; - try { - poifs = new NPOIFSFileSystem(file); - final DirectoryEntry dir = poifs.getRoot(); - /* - * If there is a document summry information stream, read it from - * the POI filesystem, else create a new one. - */ - DocumentSummaryInformation dsi; - if (dir.hasEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)) { - final DocumentInputStream dis = poifs.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - final PropertySet ps = new PropertySet(dis); - dsi = new DocumentSummaryInformation(ps); - dis.close(); - } else { - dsi = PropertySetFactory.newDocumentSummaryInformation(); - } - final CustomProperties cps = dsi.getCustomProperties(); - - if (cps == null) - /* The document does not have custom properties. */ - return; - - for (CustomProperty cp : cps.values()) { - cp.getName(); - cp.getValue(); - } - } finally { - if (poifs != null) poifs.close(); - } - } - }; - - POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - final File dataDir = _samples.getFile(""); - final File[] docs = dataDir.listFiles(new FileFilter() - { - @Override - public boolean accept(final File file) - { - return file.isFile() && file.getName().startsWith("Test") && TestReadAllFiles.checkExclude(file); - } - }); - - for (File doc : docs) { - try { - task.runTest(doc); - } catch (Exception e) { - throw new IOException("While handling file " + doc, e); - } - } - } - - - /** - * <p>Tests basic custom property features.</p> + * Tests basic custom property features. */ @Test public void testCustomerProperties() @@ -693,8 +553,8 @@ public class TestWriteWellKnown { /** - * <p>Tests reading custom properties from a section including reading - * custom properties which are not pure.</p> + * Tests reading custom properties from a section including reading + * custom properties which are not pure. */ @Test public void testGetCustomerProperties() Modified: poi/trunk/src/testcases/org/apache/poi/hpsf/basic/Util.java URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/hpsf/basic/Util.java?rev=1793596&r1=1793595&r2=1793596&view=diff ============================================================================== --- poi/trunk/src/testcases/org/apache/poi/hpsf/basic/Util.java (original) +++ poi/trunk/src/testcases/org/apache/poi/hpsf/basic/Util.java Tue May 2 23:27:27 2017 @@ -19,13 +19,11 @@ package org.apache.poi.hpsf.basic; import java.io.ByteArrayOutputStream; -import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; @@ -36,6 +34,7 @@ import org.apache.poi.hpsf.PropertySet; import org.apache.poi.poifs.eventfilesystem.POIFSReader; import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; +import org.apache.poi.util.IOUtils; @@ -45,42 +44,6 @@ import org.apache.poi.poifs.eventfilesys final class Util { /** - * <p>Reads bytes from an input stream and writes them to an - * output stream until end of file is encountered.</p> - * - * @param in the input stream to read from - * - * @param out the output stream to write to - * - * @exception IOException if an I/O exception occurs - */ - public static void copy(final InputStream in, final OutputStream out) - throws IOException - { - final int BUF_SIZE = 1000; - byte[] b = new byte[BUF_SIZE]; - int read; - boolean eof = false; - while (!eof) - { - try - { - read = in.read(b, 0, BUF_SIZE); - if (read > 0) - out.write(b, 0, read); - else - eof = true; - } - catch (EOFException ex) - { - eof = true; - } - } - } - - - - /** * <p>Reads all files from a POI filesystem and returns them as an * array of {@link POIFile} instances. This method loads all files * into memory and thus does not cope well with large POI @@ -143,7 +106,7 @@ final class Util { final InputStream in = event.getStream(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); - Util.copy(in, out); + IOUtils.copy(in, out); out.close(); f.setBytes(out.toByteArray()); files.add(f); @@ -192,34 +155,33 @@ final class Util { * * @exception IOException if an I/O exception occurs */ - public static POIFile[] readPropertySets(final File poiFs) - throws FileNotFoundException, IOException - { + public static List<POIFile> readPropertySets(final File poiFs) + throws FileNotFoundException, IOException { + FileInputStream stream = new FileInputStream(poiFs); + try { + return readPropertySets(stream); + } finally { + stream.close(); + } + } + + public static List<POIFile> readPropertySets(final InputStream poiFs) + throws FileNotFoundException, IOException { final List<POIFile> files = new ArrayList<POIFile>(7); final POIFSReader r = new POIFSReader(); - POIFSReaderListener pfl = new POIFSReaderListener() - { + POIFSReaderListener pfl = new POIFSReaderListener() { @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - try - { + public void processPOIFSReaderEvent(final POIFSReaderEvent event) { + try { final POIFile f = new POIFile(); f.setName(event.getName()); f.setPath(event.getPath()); final InputStream in = event.getStream(); - if (PropertySet.isPropertySetStream(in)) - { - final ByteArrayOutputStream out = - new ByteArrayOutputStream(); - Util.copy(in, out); - out.close(); - f.setBytes(out.toByteArray()); + if (PropertySet.isPropertySetStream(in)) { + f.setBytes(IOUtils.toByteArray(in)); files.add(f); } - } - catch (Exception ex) - { + } catch (Exception ex) { throw new RuntimeException(ex); } } @@ -229,17 +191,9 @@ final class Util { r.registerListener(pfl); /* Read the POI filesystem. */ - FileInputStream stream = new FileInputStream(poiFs); - try { - r.read(stream); - } finally { - stream.close(); - } + r.read(poiFs); - POIFile[] result = new POIFile[files.size()]; - for (int i = 0; i < result.length; i++) - result[i] = files.get(i); - return result; + return files; } Added: poi/trunk/test-data/hpsf/TestInvertedClassID.doc URL: http://svn.apache.org/viewvc/poi/trunk/test-data/hpsf/TestInvertedClassID.doc?rev=1793596&view=auto ============================================================================== Binary file - no diff available. Propchange: poi/trunk/test-data/hpsf/TestInvertedClassID.doc ------------------------------------------------------------------------------ svn:mime-type = application/msword Added: poi/trunk/test-data/hpsf/TestVisio43688.vsd URL: http://svn.apache.org/viewvc/poi/trunk/test-data/hpsf/TestVisio43688.vsd?rev=1793596&view=auto ============================================================================== Binary file - no diff available. Propchange: poi/trunk/test-data/hpsf/TestVisio43688.vsd ------------------------------------------------------------------------------ svn:mime-type = application/vnd.visio --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
