aboutsummaryrefslogtreecommitdiffstats
path: root/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java
blob: ce3cf6d34dbe2ddf9a52adf9499c8e94d66ccc57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
==================================================================== */

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 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;

/**
 * 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.
 */
@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;

    /**
     * This test methods reads all property set streams from all POI
     * filesystems in the "data" directory.
     */
    @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();
        }
    }
    
    /**
     * <p>Tests the simplified custom properties by reading them from the
     * available test files.</p>
     *
     * @throws Throwable if anything goes wrong.
     */
    @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.properties()) {
                assertNotNull(cp.getName());
                assertNotNull(cp.getValue());
            }
        } finally {
            poifs.close();
        }
    }

}