fix eclipse warnings - close resources

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1779869 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2017-01-23 00:31:27 +00:00
parent c48a0cf334
commit 4a5f7765bb
13 changed files with 746 additions and 589 deletions

View File

@ -16,28 +16,38 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.xdgf.extractor; package org.apache.poi.xdgf.extractor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xdgf.usermodel.XmlVisioDocument; import org.apache.poi.xdgf.usermodel.XmlVisioDocument;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import junit.framework.TestCase; public class TestXDGFVisioExtractor {
public class TestXDGFVisioExtractor extends TestCase { private static final POIDataSamples SAMPLES = POIDataSamples.getDiagramInstance();
private POIDataSamples diagrams;
private OPCPackage pkg; private OPCPackage pkg;
private XmlVisioDocument xml; private XmlVisioDocument xml;
@Override @Before
protected void setUp() throws Exception { public void setUp() throws Exception {
diagrams = POIDataSamples.getDiagramInstance(); pkg = OPCPackage.open(SAMPLES.openResourceAsStream("test_text_extraction.vsdx"));
pkg = OPCPackage.open(diagrams.openResourceAsStream("test_text_extraction.vsdx"));
xml = new XmlVisioDocument(pkg); xml = new XmlVisioDocument(pkg);
} }
@After
public void closeResoures() throws IOException {
xml.close();
pkg.close();
}
@Test
public void testGetSimpleText() throws IOException { public void testGetSimpleText() throws IOException {
new XDGFVisioExtractor(xml).close(); new XDGFVisioExtractor(xml).close();
new XDGFVisioExtractor(pkg).close(); new XDGFVisioExtractor(pkg).close();
@ -46,10 +56,8 @@ public class TestXDGFVisioExtractor extends TestCase {
extractor.getText(); extractor.getText();
String text = extractor.getText(); String text = extractor.getText();
assertTrue(text.length() > 0); String expected = "Text here\nText there\nText, text, everywhere!\nRouter here\n";
assertEquals(expected, text);
assertEquals("Text here\nText there\nText, text, everywhere!\nRouter here\n",
text);
extractor.close(); extractor.close();
} }
@ -57,13 +65,13 @@ public class TestXDGFVisioExtractor extends TestCase {
//the point of this is to trigger the addition of //the point of this is to trigger the addition of
//some common visio classes -- ConnectsType //some common visio classes -- ConnectsType
public void testVisioConnects() throws Exception { public void testVisioConnects() throws IOException {
InputStream is = SAMPLES.openResourceAsStream("60489.vsdx");
XmlVisioDocument document = XmlVisioDocument document = new XmlVisioDocument(is);
new XmlVisioDocument(diagrams. is.close();
openResourceAsStream("60489.vsdx"));
XDGFVisioExtractor extractor = new XDGFVisioExtractor(document); XDGFVisioExtractor extractor = new XDGFVisioExtractor(document);
String text = extractor.getText(); String text = extractor.getText();
assertTrue(text.indexOf("Arrears") > -1); assertTrue(text.indexOf("Arrears") > -1);
extractor.close();
} }
} }

View File

@ -19,73 +19,41 @@ package org.apache.poi.hslf.record;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import junit.framework.TestCase;
import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.junit.BeforeClass;
import org.junit.Test;
/** /**
* Tests that {@link ExOleObjStg} works properly * Tests that {@link ExOleObjStg} works properly
*
* @author Yegor Kozlov
*/ */
public final class TestExOleObjStg extends TestCase { public final class TestExOleObjStg {
// From a real file (embedded SWF control) // From a real file (embedded SWF control)
/* // <ExOleObjStg info="16" type="4113" size="347" offset="4322" header="10 00 11 10 5B 01 00 00 ">....
<ExOleObjStg info="16" type="4113" size="347" offset="4322" header="10 00 11 10 5B 01 00 00 "> private static byte[] data;
00 0E 00 00 78 9C BB 70 5E F0 C1 C2 8D 52 0F 19 D0 80 1D 03 33 C3 BF FF 9C
0C 6C 48 62 8C 40 CC 04 E3 08 30 30 B0 40 C5 FE FD FF FF 1F 24 C4 0C C4 FF @BeforeClass
47 C1 90 02 41 0C F9 40 58 C2 A0 C0 E0 CA 90 07 A4 8B 18 2A D1 93 02 5E 20 public static void init() throws IOException {
C6 C0 0A 8F 73 50 5A C8 BB 5D 73 29 77 DD 79 C1 69 3B 5C 5C 83 43 50 D5 06 data = org.apache.poi.poifs.storage.RawDataUtil.decompress(
BC 48 2F 2B 66 38 C9 C8 0E 64 3B 30 42 C4 9C 81 B6 83 EC 4D 05 93 C5 24 D9 "H4sIAAAAAAAAAAFjAZz+EAAREFsBAAAADgAAeJy7cF7wwcKNUg8Z0IAdAzPDv/+cDGxIYoxAzATjCDAwsEDF/"+
0D 02 42 0C 4C 8C C8 FE 21 56 9F 02 23 C9 56 E1 04 E4 D8 4F 4D 40 89 FD A0 "v3//x8kxAzE/0fBkAJBDPlAWMKgwODKkAekixgq0ZMCXiDGwAqPc1BayLtdcyl33XnBaTtcXINDUNUGvEgvK2"+
BC FB 17 4B BA F8 07 C5 A3 60 78 03 7A E6 FF 09 67 59 1B 41 F9 9F 95 61 34 "Y4ycgOZDswQsScgbaD7E0Fk8Uk2Q0CQgxMjMj+IVafAiPJVuEE5NhPTUCJ/aC8+xdLuvgHxaNgeAN65v8JZ1k"+
FF 53 13 50 62 3F 4C 1F AC 1C 18 CD F7 23 0B C0 DA 74 A0 B6 1B A8 3D 37 1A "bQfmflWE0/1MTUGI/TB+sHBjN9yMLwNp0oLYbqD03GvcjC6SHpoUKABtkbzghmAPawudgkAGSaQw5DGUMBUAy"+
F7 23 0B A4 87 A6 85 0A 00 1B 64 6F 38 21 98 03 DA C2 E7 60 90 01 92 69 0C "EVgvpAJrBz1gGV0OFCdOBR+QDGfIBJbtKcByvhzI4wbj//85GLiALA+gXDpDBlgtqKfhwxACl4e4AuYaYHeDI"+
39 0C 65 0C 05 40 32 11 58 2F A4 02 6B 07 3D 60 19 5D 0E 14 27 4E 05 1F 90 "RioEmSKI9C2HLhZyKqQ9fBilHXcwN4KN1wdM1Q1iJcINZGDgQfsJxC/GOib4Q8AvWU91AJ49g1jAQAA"
0C 67 C8 04 96 ED 29 C0 72 BE 1C C8 E3 06 E3 FF FF 39 18 B8 80 2C 0F A0 5C );
3A 43 06 58 2D A8 A7 E1 C3 10 02 97 87 B8 02 E6 1A 60 77 83 21 18 A8 12 64 }
8A 23 D0 B6 1C B8 59 C8 AA 90 F5 F0 62 94 75 DC C0 DE 0A 37 5C 1D 33 54 35
88 97 08 35 91 83 81 07 EC 27 10 BF 18 E8 9B E1 0F 00 BD 65 3D D4
</ExOleObjStg>
*/
private final byte[] data = new byte[] {
0x10, 0x00, 0x11, 0x10, 0x5B, 0x01, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0x78, (byte)0x9C, (byte)0xBB, 0x70,
0x5E, (byte)0xF0, (byte)0xC1, (byte)0xC2, (byte)0x8D, 0x52, 0x0F, 0x19, (byte)0xD0, (byte)0x80, 0x1D, 0x03,
0x33, (byte)0xC3, (byte)0xBF, (byte)0xFF, (byte)0x9C, 0x0C, 0x6C, 0x48, 0x62, (byte)0x8C, 0x40, (byte)0xCC,
0x04, (byte)0xE3, 0x08, 0x30, 0x30, (byte)0xB0, 0x40, (byte)0xC5, (byte)0xFE, (byte)0xFD, (byte)0xFF, (byte)0xFF,
0x1F, 0x24, (byte)0xC4, (byte)0x0C, (byte)0xC4, (byte)0xFF, 0x47, (byte)0xC1, (byte)0x90, 0x02, 0x41, 0x0C,
(byte)0xF9, 0x40, 0x58, (byte)0xC2, (byte)0xA0, (byte)0xC0, (byte)0xE0, (byte)0xCA, (byte)0x90, 0x07, (byte)0xA4,
(byte)0x8B, 0x18, 0x2A, (byte)0xD1, (byte)0x93, 0x02, 0x5E, 0x20, (byte)0xC6, (byte)0xC0, 0x0A, (byte)0x8F,
0x73, 0x50, 0x5A, (byte)0xC8, (byte)0xBB, 0x5D, 0x73, 0x29, 0x77, (byte)0xDD, 0x79, (byte)0xC1, 0x69, 0x3B,
0x5C, 0x5C, (byte)0x83, 0x43, 0x50, (byte)0xD5, 0x06, (byte)0xBC, 0x48, 0x2F, 0x2B, 0x66, 0x38, (byte)0xC9,
(byte)0xC8, 0x0E, 0x64, 0x3B, 0x30, 0x42, (byte)0xC4, (byte)0x9C, (byte)0x81, (byte)0xB6, (byte)0x83, (byte)0xEC,
0x4D, 0x05, (byte)0x93, (byte)0xC5, 0x24, (byte)0xD9, 0x0D, 0x02, 0x42, 0x0C, 0x4C, (byte)0x8C, (byte)0xC8,
(byte)0xFE, 0x21, 0x56, (byte)0x9F, 0x02, 0x23, (byte)0xC9, 0x56, (byte)0xE1, 0x04, (byte)0xE4, (byte)0xD8,
0x4F, 0x4D, 0x40, (byte)0x89, (byte)0xFD, (byte)0xA0, (byte)0xBC, (byte)0xFB, 0x17, 0x4B, (byte)0xBA, (byte)0xF8,
0x07, (byte)0xC5, (byte)0xA3, 0x60, 0x78, 0x03, 0x7A, (byte)0xE6, (byte)0xFF, 0x09, 0x67, 0x59, 0x1B, 0x41,
(byte)0xF9, (byte)0x9F, (byte)0x95, 0x61, 0x34, (byte)0xFF, 0x53, 0x13, 0x50, 0x62, 0x3F, 0x4C, 0x1F, (byte)0xAC,
0x1C, 0x18, (byte)0xCD, (byte)0xF7, 0x23, 0x0B, (byte)0xC0, (byte)0xDA, 0x74, (byte)0xA0, (byte)0xB6, 0x1B,
(byte)0xA8, 0x3D, 0x37, 0x1A, (byte)0xF7, 0x23, 0x0B, (byte)0xA4, (byte)0x87, (byte)0xA6, (byte)0x85, 0x0A,
0x00, 0x1B, 0x64, 0x6F, 0x38, 0x21, (byte)0x98, 0x03, (byte)0xDA, (byte)0xC2, (byte)0xE7, 0x60, (byte)0x90,
0x01, (byte)0x92, 0x69, 0x0C, 0x39, 0x0C, 0x65, 0x0C, 0x05, 0x40, 0x32, 0x11, 0x58, 0x2F, (byte)0xA4, 0x02,
0x6B, 0x07, 0x3D, 0x60, 0x19, 0x5D, 0x0E, 0x14, 0x27, 0x4E, 0x05, 0x1F, (byte)0x90, 0x0C, 0x67, (byte)0xC8,
0x04, (byte)0x96, (byte)0xED, 0x29, (byte)0xC0, 0x72, (byte)0xBE, 0x1C, (byte)0xC8, (byte)0xE3, 0x06, (byte)0xE3,
(byte)0xFF, (byte)0xFF, 0x39, 0x18, (byte)0xB8, (byte)0x80, 0x2C, 0x0F, (byte)0xA0, 0x5C, 0x3A, 0x43, 0x06, 0x58,
0x2D, (byte)0xA8, (byte)0xA7, (byte)0xE1, (byte)0xC3, 0x10, 0x02, (byte)0x97, (byte)0x87, (byte)0xB8, 0x02,
(byte)0xE6, 0x1A, 0x60, 0x77, (byte)0x83, 0x21, 0x18, (byte)0xA8, 0x12, 0x64, (byte)0x8A, 0x23, (byte)0xD0,
(byte)0xB6, 0x1C, (byte)0xB8, 0x59, (byte)0xC8, (byte)0xAA, (byte)0x90, (byte)0xF5, (byte)0xF0, 0x62, (byte)0x94,
0x75, (byte)0xDC, (byte)0xC0, (byte)0xDE, 0x0A, 0x37, 0x5C, 0x1D, 0x33, 0x54, 0x35, (byte)0x88, (byte)0x97, 0x08,
0x35, (byte)0x91, (byte)0x83, (byte)0x81, 0x07, (byte)0xEC, 0x27, 0x10, (byte)0xBF, 0x18, (byte)0xE8, (byte)0x9B,
(byte)0xE1, 0x0F, 0x00, (byte)0xBD, 0x65, 0x3D, (byte)0xD4
};
@Test
public void testRead() throws Exception { public void testRead() throws Exception {
ExOleObjStg record = new ExOleObjStg(data, 0, data.length); ExOleObjStg record = new ExOleObjStg(data, 0, data.length);
assertEquals(RecordTypes.ExOleObjStg.typeID, record.getRecordType()); assertEquals(RecordTypes.ExOleObjStg.typeID, record.getRecordType());
@ -99,8 +67,10 @@ public final class TestExOleObjStg extends TestCase {
DocumentEntry doc = (DocumentEntry)fs.getRoot().getEntry("Contents"); DocumentEntry doc = (DocumentEntry)fs.getRoot().getEntry("Contents");
assertNotNull(doc); assertNotNull(doc);
assertTrue("Fetched the Contents stream containing OLE properties", true); assertTrue("Fetched the Contents stream containing OLE properties", true);
fs.close();
} }
@Test
public void testWrite() throws Exception { public void testWrite() throws Exception {
ExOleObjStg record = new ExOleObjStg(data, 0, data.length); ExOleObjStg record = new ExOleObjStg(data, 0, data.length);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
@ -110,6 +80,7 @@ public final class TestExOleObjStg extends TestCase {
assertArrayEquals(data, b); assertArrayEquals(data, b);
} }
@Test
public void testNewRecord() throws Exception { public void testNewRecord() throws Exception {
ExOleObjStg src = new ExOleObjStg(data, 0, data.length); ExOleObjStg src = new ExOleObjStg(data, 0, data.length);
byte[] oledata = readAll(src.getData()); byte[] oledata = readAll(src.getData());

View File

@ -18,23 +18,54 @@
package org.apache.poi.hslf.record; package org.apache.poi.hslf.record;
import junit.framework.TestCase; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/** /**
* Tests that the helper methods on RecordContainer work properly * Tests that the helper methods on RecordContainer work properly
*
* @author Nick Burch (nick at torchbox dot com)
*/ */
public final class TestRecordContainer extends TestCase { public final class TestRecordContainer {
private HSLFSlideShowImpl hss;
private RecordContainer recordContainer; private RecordContainer recordContainer;
private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
@Before
public void setUp() throws IOException {
// Find a real RecordContainer record
InputStream is = slTests.openResourceAsStream("basic_test_ppt_file.ppt");
hss = new HSLFSlideShowImpl(is);
is.close();
Record[] r = hss.getRecords();
for (Record rec : r) {
if(rec instanceof RecordContainer) {
recordContainer = (RecordContainer)rec;
return;
}
}
}
@After
public void closeResources() throws IOException {
hss.close();
}
@Test
public void testIsAnAtom() { public void testIsAnAtom() {
assertFalse( recordContainer.isAnAtom() ); assertFalse( recordContainer.isAnAtom() );
} }
@Test
public void testAppendChildRecord() { public void testAppendChildRecord() {
// Grab records for testing with // Grab records for testing with
Record r = recordContainer.getChildRecords()[0]; Record r = recordContainer.getChildRecords()[0];
@ -68,6 +99,7 @@ public final class TestRecordContainer extends TestCase {
assertEquals(r, nrs[3]); assertEquals(r, nrs[3]);
} }
@Test
public void testAddChildAfter() { public void testAddChildAfter() {
// Working with new StyleTextPropAtom // Working with new StyleTextPropAtom
Record newRecord = new StyleTextPropAtom(0); Record newRecord = new StyleTextPropAtom(0);
@ -97,6 +129,7 @@ public final class TestRecordContainer extends TestCase {
assertEquals(newRecord, ncr[cr.length]); assertEquals(newRecord, ncr[cr.length]);
} }
@Test
public void testAddChildBefore() { public void testAddChildBefore() {
// Working with new StyleTextPropAtom // Working with new StyleTextPropAtom
Record newRecord = new StyleTextPropAtom(0); Record newRecord = new StyleTextPropAtom(0);
@ -137,27 +170,11 @@ public final class TestRecordContainer extends TestCase {
assertEquals(before, ncr[1]); assertEquals(before, ncr[1]);
} }
@Test
public void testRemove() { public void testRemove() {
Record[] ch = recordContainer.getChildRecords(); Record[] ch = recordContainer.getChildRecords();
Record removeRecord = recordContainer.removeChild(ch[0]); Record removeRecord = recordContainer.removeChild(ch[0]);
assertSame(ch[0], removeRecord); assertSame(ch[0], removeRecord);
assertEquals(ch.length-1, recordContainer.getChildRecords().length); assertEquals(ch.length-1, recordContainer.getChildRecords().length);
} }
@Override
protected void setUp() throws Exception {
super.setUp();
// Find a real RecordContainer record
POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
HSLFSlideShowImpl hss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt"));
Record[] r = hss.getRecords();
for (Record rec : r) {
if(rec instanceof RecordContainer) {
recordContainer = (RecordContainer)rec;
return;
}
}
}
} }

View File

@ -349,8 +349,10 @@ public final class TestWordExtractor {
// Open directly // Open directly
for(DirectoryNode dir : files) { for(DirectoryNode dir : files) {
@SuppressWarnings("resource")
WordExtractor extractor = new WordExtractor(dir); WordExtractor extractor = new WordExtractor(dir);
assertEqualsTrim(p_text1_block, extractor.getText()); assertEqualsTrim(p_text1_block, extractor.getText());
// extractor.close();
} }
// Open via a HWPFDocument // Open via a HWPFDocument

View File

@ -17,32 +17,39 @@
package org.apache.poi.hwpf.extractor; package org.apache.poi.hwpf.extractor;
import junit.framework.TestCase; import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.junit.Test;
/** /**
* Tests for bugs with the WordExtractor * Tests for bugs with the WordExtractor
*
* @author Nick Burch (nick at torchbox dot com)
*/ */
public final class TestWordExtractorBugs extends TestCase { public final class TestWordExtractorBugs {
private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance();
public void testProblemMetadata() throws Exception { @Test
WordExtractor extractor = public void testProblemMetadata() throws IOException {
new WordExtractor(POIDataSamples.getDocumentInstance().openResourceAsStream("ProblemExtracting.doc")); InputStream is = SAMPLES.openResourceAsStream("ProblemExtracting.doc");
WordExtractor extractor = new WordExtractor(is);
is.close();
// Check it gives text without error // Check it gives text without error
extractor.getText(); extractor.getText();
extractor.getParagraphText(); extractor.getParagraphText();
extractor.getTextFromPieces(); extractor.getTextFromPieces();
extractor.close();
} }
@Test
public void testBug50688() throws Exception { public void testBug50688() throws Exception {
WordExtractor extractor = InputStream is = SAMPLES.openResourceAsStream("parentinvguid.doc");
new WordExtractor(POIDataSamples.getDocumentInstance().openResourceAsStream("parentinvguid.doc")); WordExtractor extractor = new WordExtractor(is);
is.close();
// Check it gives text without error // Check it gives text without error
extractor.getText(); extractor.getText();
extractor.close();
} }
} }

View File

@ -16,7 +16,19 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.hwpf.usermodel; package org.apache.poi.hwpf.usermodel;
import junit.framework.TestCase; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFDocument;
@ -36,23 +48,16 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils; import org.apache.poi.util.IOUtils;
import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger; import org.apache.poi.util.POILogger;
import org.junit.Test;
import java.io.ByteArrayOutputStream; import junit.framework.TestCase;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/** /**
* Test different problems reported in the Apache Bugzilla * Test different problems reported in the Apache Bugzilla
* against HWPF * against HWPF
*/ */
public class TestBugs extends TestCase public class TestBugs{
{ private static final POILogger logger = POILogFactory.getLogger(TestBugs.class);
private static final POILogger logger = POILogFactory
.getLogger(TestBugs.class);
public static void assertEqualsIgnoreNewline(String expected, String actual ) public static void assertEqualsIgnoreNewline(String expected, String actual )
{ {
@ -98,15 +103,6 @@ public class TestBugs extends TestCase
} }
} }
private static void fixed(String bugzillaId )
{
throw new Error(
"Bug "
+ bugzillaId
+ " seems to be fixed. "
+ "Please resolve the issue in Bugzilla and remove fail() from the test");
}
private String getText(String samplefile) throws IOException { private String getText(String samplefile) throws IOException {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile(samplefile); HWPFDocument doc = HWPFTestDataSamples.openSampleFile(samplefile);
WordExtractor extractor = new WordExtractor(doc); WordExtractor extractor = new WordExtractor(doc);
@ -114,6 +110,7 @@ public class TestBugs extends TestCase
return extractor.getText(); return extractor.getText();
} finally { } finally {
extractor.close(); extractor.close();
doc.close();
} }
} }
@ -124,12 +121,14 @@ public class TestBugs extends TestCase
return extractor.getText(); return extractor.getText();
} finally { } finally {
extractor.close(); extractor.close();
doc.close();
} }
} }
/** /**
* Bug 33519 - HWPF fails to read a file * Bug 33519 - HWPF fails to read a file
*/ */
@Test
public void test33519() throws IOException public void test33519() throws IOException
{ {
assertNotNull(getText("Bug33519.doc")); assertNotNull(getText("Bug33519.doc"));
@ -138,6 +137,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 34898 - WordExtractor doesn't read the whole string from the file * Bug 34898 - WordExtractor doesn't read the whole string from the file
*/ */
@Test
public void test34898() throws IOException public void test34898() throws IOException
{ {
assertEqualsIgnoreNewline("\u30c7\u30a3\u30ec\u30af\u30c8\u30ea", getText("Bug34898.doc").trim()); assertEqualsIgnoreNewline("\u30c7\u30a3\u30ec\u30af\u30c8\u30ea", getText("Bug34898.doc").trim());
@ -146,8 +146,8 @@ public class TestBugs extends TestCase
/** /**
* [RESOLVED INVALID] 41898 - Word 2003 pictures cannot be extracted * [RESOLVED INVALID] 41898 - Word 2003 pictures cannot be extracted
*/ */
public void test41898() @Test
{ public void test41898() throws IOException {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug41898.doc"); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug41898.doc");
List<Picture> pics = doc.getPicturesTable().getAllPictures(); List<Picture> pics = doc.getPicturesTable().getAllPictures();
@ -173,12 +173,14 @@ public class TestBugs extends TestCase
OfficeDrawing officeDrawing = officeDrawings.iterator().next(); OfficeDrawing officeDrawing = officeDrawings.iterator().next();
assertNotNull(officeDrawing); assertNotNull(officeDrawing);
assertEquals(1044, officeDrawing.getShapeId()); assertEquals(1044, officeDrawing.getShapeId());
doc.close();
} }
/** /**
* Bug 44331 - HWPFDocument.write destroys fields * Bug 44331 - HWPFDocument.write destroys fields
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test
public void test44431() throws IOException public void test44431() throws IOException
{ {
HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("Bug44431.doc"); HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("Bug44431.doc");
@ -200,12 +202,14 @@ public class TestBugs extends TestCase
} }
} finally { } finally {
extractor1.close(); extractor1.close();
doc1.close();
} }
} }
/** /**
* Bug 44331 - HWPFDocument.write destroys fields * Bug 44331 - HWPFDocument.write destroys fields
*/ */
@Test
public void test44431_2() throws IOException public void test44431_2() throws IOException
{ {
assertEqualsIgnoreNewline("File name=FieldsTest.doc\n" + assertEqualsIgnoreNewline("File name=FieldsTest.doc\n" +
@ -233,6 +237,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 45473 - HWPF cannot read file after save * Bug 45473 - HWPF cannot read file after save
*/ */
@Test
public void test45473() throws IOException public void test45473() throws IOException
{ {
// Fetch the current text // Fetch the current text
@ -243,6 +248,7 @@ public class TestBugs extends TestCase
text1 = wordExtractor.getText().trim(); text1 = wordExtractor.getText().trim();
} finally { } finally {
wordExtractor.close(); wordExtractor.close();
doc1.close();
} }
// Re-load, then re-save and re-check // Re-load, then re-save and re-check
@ -254,6 +260,7 @@ public class TestBugs extends TestCase
text2 = wordExtractor2.getText().trim(); text2 = wordExtractor2.getText().trim();
} finally { } finally {
wordExtractor2.close(); wordExtractor2.close();
doc1.close();
} }
// the text in the saved document has some differences in line // the text in the saved document has some differences in line
@ -264,8 +271,8 @@ public class TestBugs extends TestCase
/** /**
* Bug 46220 - images are not properly extracted * Bug 46220 - images are not properly extracted
*/ */
public void test46220() @Test
{ public void test46220() throws IOException {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug46220.doc"); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug46220.doc");
// reference checksums as in Bugzilla // reference checksums as in Bugzilla
String[] md5 = { "851be142bce6d01848e730cb6903f39e", String[] md5 = { "851be142bce6d01848e730cb6903f39e",
@ -281,12 +288,14 @@ public class TestBugs extends TestCase
// use Apache Commons Codec utils to compute md5 // use Apache Commons Codec utils to compute md5
assertEqualsIgnoreNewline(md5[i], DigestUtils.md5Hex(data)); assertEqualsIgnoreNewline(md5[i], DigestUtils.md5Hex(data));
} }
doc.close();
} }
/** /**
* [RESOLVED FIXED] Bug 46817 - Regression: Text from some table cells * [RESOLVED FIXED] Bug 46817 - Regression: Text from some table cells
* missing * missing
*/ */
@Test
public void test46817() throws IOException public void test46817() throws IOException
{ {
String text = getText("Bug46817.doc").trim(); String text = getText("Bug46817.doc").trim();
@ -299,9 +308,9 @@ public class TestBugs extends TestCase
/** /**
* [FAILING] Bug 47286 - Word documents saves in wrong format if source * [FAILING] Bug 47286 - Word documents saves in wrong format if source
* contains form elements * contains form elements
*
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test
public void test47286() throws IOException public void test47286() throws IOException
{ {
// Fetch the current text // Fetch the current text
@ -312,6 +321,7 @@ public class TestBugs extends TestCase
text1 = wordExtractor.getText().trim(); text1 = wordExtractor.getText().trim();
} finally { } finally {
wordExtractor.close(); wordExtractor.close();
doc1.close();
} }
// Re-load, then re-save and re-check // Re-load, then re-save and re-check
@ -323,6 +333,7 @@ public class TestBugs extends TestCase
text2 = wordExtractor2.getText().trim(); text2 = wordExtractor2.getText().trim();
} finally { } finally {
wordExtractor2.close(); wordExtractor2.close();
doc1.close();
} }
// the text in the saved document has some differences in line // the text in the saved document has some differences in line
@ -345,6 +356,7 @@ public class TestBugs extends TestCase
* [RESOLVED FIXED] Bug 47287 - StringIndexOutOfBoundsException in * [RESOLVED FIXED] Bug 47287 - StringIndexOutOfBoundsException in
* CharacterRun.replaceText() * CharacterRun.replaceText()
*/ */
@Test
public void test47287() public void test47287()
{ {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug47287.doc"); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug47287.doc");
@ -420,6 +432,7 @@ public class TestBugs extends TestCase
* [RESOLVED FIXED] Bug 47731 - Word Extractor considers text copied from * [RESOLVED FIXED] Bug 47731 - Word Extractor considers text copied from
* some website as an embedded object * some website as an embedded object
*/ */
@Test
public void test47731() throws Exception public void test47731() throws Exception
{ {
String foundText = getText("Bug47731.doc"); String foundText = getText("Bug47731.doc");
@ -431,6 +444,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 4774 - text extracted by WordExtractor is broken * Bug 4774 - text extracted by WordExtractor is broken
*/ */
@Test
public void test47742() throws Exception public void test47742() throws Exception
{ {
// (1) extract text from MS Word document via POI // (1) extract text from MS Word document via POI
@ -454,6 +468,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 47958 - Exception during Escher walk of pictures * Bug 47958 - Exception during Escher walk of pictures
*/ */
@Test
public void test47958() public void test47958()
{ {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug47958.doc"); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug47958.doc");
@ -464,6 +479,7 @@ public class TestBugs extends TestCase
* [RESOLVED FIXED] Bug 48065 - Problems with save output of HWPF (losing * [RESOLVED FIXED] Bug 48065 - Problems with save output of HWPF (losing
* formatting) * formatting)
*/ */
@Test
public void test48065() public void test48065()
{ {
HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("Bug48065.doc"); HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("Bug48065.doc");
@ -479,6 +495,7 @@ public class TestBugs extends TestCase
assertTableStructures(expected, actual); assertTableStructures(expected, actual);
} }
@Test
public void test49933() throws IOException public void test49933() throws IOException
{ {
String text = getTextOldFile("Bug49933.doc"); String text = getTextOldFile("Bug49933.doc");
@ -489,6 +506,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 50936 - Exception parsing MS Word 8.0 file * Bug 50936 - Exception parsing MS Word 8.0 file
*/ */
@Test
public void test50936_1() public void test50936_1()
{ {
HWPFDocument hwpfDocument = HWPFTestDataSamples HWPFDocument hwpfDocument = HWPFTestDataSamples
@ -499,6 +517,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 50936 - Exception parsing MS Word 8.0 file * Bug 50936 - Exception parsing MS Word 8.0 file
*/ */
@Test
public void test50936_2() public void test50936_2()
{ {
HWPFDocument hwpfDocument = HWPFTestDataSamples HWPFDocument hwpfDocument = HWPFTestDataSamples
@ -509,6 +528,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 50936 - Exception parsing MS Word 8.0 file * Bug 50936 - Exception parsing MS Word 8.0 file
*/ */
@Test
public void test50936_3() public void test50936_3()
{ {
HWPFDocument hwpfDocument = HWPFTestDataSamples HWPFDocument hwpfDocument = HWPFTestDataSamples
@ -519,21 +539,16 @@ public class TestBugs extends TestCase
/** /**
* [FAILING] Bug 50955 - error while retrieving the text file * [FAILING] Bug 50955 - error while retrieving the text file
*/ */
public void test50955() throws IOException @Test(expected=IllegalStateException.class)
{ public void test50955() throws IOException {
try { getTextOldFile("Bug50955.doc");
getTextOldFile("Bug50955.doc");
fixed("50955");
} catch (IllegalStateException e) {
// expected here
}
} }
/** /**
* [RESOLVED FIXED] Bug 51604 - replace text fails for doc (poi 3.8 beta * [RESOLVED FIXED] Bug 51604 - replace text fails for doc (poi 3.8 beta
* release from download site ) * release from download site )
*/ */
@Test
public void test51604() public void test51604()
{ {
HWPFDocument document = HWPFTestDataSamples HWPFDocument document = HWPFTestDataSamples
@ -563,6 +578,7 @@ public class TestBugs extends TestCase
* [RESOLVED FIXED] Bug 51604 - replace text fails for doc (poi 3.8 beta * [RESOLVED FIXED] Bug 51604 - replace text fails for doc (poi 3.8 beta
* release from download site ) * release from download site )
*/ */
@Test
public void test51604p2() throws Exception public void test51604p2() throws Exception
{ {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug51604.doc"); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug51604.doc");
@ -596,8 +612,9 @@ public class TestBugs extends TestCase
{ {
CharacterRun charRun = paragraph.getCharacterRun(j); CharacterRun charRun = paragraph.getCharacterRun(j);
String text = charRun.text(); String text = charRun.text();
if (text.contains("Header" ) ) if (text.contains("Header" ) ) {
charRun.replaceText(text, "added"); charRun.replaceText(text, "added");
}
} }
} }
} }
@ -606,6 +623,7 @@ public class TestBugs extends TestCase
* [RESOLVED FIXED] Bug 51604 - replace text fails for doc (poi 3.8 beta * [RESOLVED FIXED] Bug 51604 - replace text fails for doc (poi 3.8 beta
* release from download site ) * release from download site )
*/ */
@Test
public void test51604p3() throws Exception public void test51604p3() throws Exception
{ {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug51604.doc"); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug51604.doc");
@ -639,6 +657,7 @@ public class TestBugs extends TestCase
* [RESOLVED FIXED] Bug 51671 - HWPFDocument.write based on NPOIFSFileSystem * [RESOLVED FIXED] Bug 51671 - HWPFDocument.write based on NPOIFSFileSystem
* throws a NullPointerException * throws a NullPointerException
*/ */
@Test
public void test51671() throws Exception public void test51671() throws Exception
{ {
InputStream is = POIDataSamples.getDocumentInstance() InputStream is = POIDataSamples.getDocumentInstance()
@ -648,6 +667,7 @@ public class TestBugs extends TestCase
HWPFDocument hwpfDocument = new HWPFDocument( HWPFDocument hwpfDocument = new HWPFDocument(
npoifsFileSystem.getRoot()); npoifsFileSystem.getRoot());
hwpfDocument.write(new ByteArrayOutputStream()); hwpfDocument.write(new ByteArrayOutputStream());
hwpfDocument.close();
} finally { } finally {
npoifsFileSystem.close(); npoifsFileSystem.close();
} }
@ -657,6 +677,7 @@ public class TestBugs extends TestCase
* Bug 51678 - Extracting text from Bug51524.zip is slow Bug 51524 - * Bug 51678 - Extracting text from Bug51524.zip is slow Bug 51524 -
* PapBinTable constructor is slow * PapBinTable constructor is slow
*/ */
@Test
public void test51678And51524() throws IOException public void test51678And51524() throws IOException
{ {
// YK: the test will run only if the poi.test.remote system property is // YK: the test will run only if the poi.test.remote system property is
@ -681,6 +702,7 @@ public class TestBugs extends TestCase
* [FIXED] Bug 51902 - Picture.fillRawImageContent - * [FIXED] Bug 51902 - Picture.fillRawImageContent -
* ArrayIndexOutOfBoundsException * ArrayIndexOutOfBoundsException
*/ */
@Test
public void testBug51890() public void testBug51890()
{ {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug51890.doc"); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug51890.doc");
@ -697,6 +719,7 @@ public class TestBugs extends TestCase
* [RESOLVED FIXED] Bug 51834 - Opening and Writing .doc file results in * [RESOLVED FIXED] Bug 51834 - Opening and Writing .doc file results in
* corrupt document * corrupt document
*/ */
@Test
public void testBug51834() throws Exception public void testBug51834() throws Exception
{ {
/* /*
@ -711,6 +734,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 51944 - PAPFormattedDiskPage.getPAPX - IndexOutOfBounds * Bug 51944 - PAPFormattedDiskPage.getPAPX - IndexOutOfBounds
*/ */
@Test
public void testBug51944() throws Exception public void testBug51944() throws Exception
{ {
HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug51944.doc"); HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug51944.doc");
@ -721,6 +745,7 @@ public class TestBugs extends TestCase
* Bug 52032 - [BUG] & [partial-PATCH] HWPF - ArrayIndexOutofBoundsException * Bug 52032 - [BUG] & [partial-PATCH] HWPF - ArrayIndexOutofBoundsException
* with no stack trace (broken after revision 1178063) * with no stack trace (broken after revision 1178063)
*/ */
@Test
public void testBug52032_1() throws Exception public void testBug52032_1() throws Exception
{ {
assertNotNull(getText("Bug52032_1.doc")); assertNotNull(getText("Bug52032_1.doc"));
@ -730,6 +755,7 @@ public class TestBugs extends TestCase
* Bug 52032 - [BUG] & [partial-PATCH] HWPF - ArrayIndexOutofBoundsException * Bug 52032 - [BUG] & [partial-PATCH] HWPF - ArrayIndexOutofBoundsException
* with no stack trace (broken after revision 1178063) * with no stack trace (broken after revision 1178063)
*/ */
@Test
public void testBug52032_2() throws Exception public void testBug52032_2() throws Exception
{ {
assertNotNull(getText("Bug52032_2.doc")); assertNotNull(getText("Bug52032_2.doc"));
@ -739,6 +765,7 @@ public class TestBugs extends TestCase
* Bug 52032 - [BUG] & [partial-PATCH] HWPF - ArrayIndexOutofBoundsException * Bug 52032 - [BUG] & [partial-PATCH] HWPF - ArrayIndexOutofBoundsException
* with no stack trace (broken after revision 1178063) * with no stack trace (broken after revision 1178063)
*/ */
@Test
public void testBug52032_3() throws Exception public void testBug52032_3() throws Exception
{ {
assertNotNull(getText("Bug52032_3.doc")); assertNotNull(getText("Bug52032_3.doc"));
@ -747,6 +774,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document * Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document
*/ */
@Test
public void testBug53380_1() throws Exception public void testBug53380_1() throws Exception
{ {
assertNotNull(getText("Bug53380_1.doc")); assertNotNull(getText("Bug53380_1.doc"));
@ -755,6 +783,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document * Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document
*/ */
@Test
public void testBug53380_2() throws Exception public void testBug53380_2() throws Exception
{ {
assertNotNull(getText("Bug53380_2.doc")); assertNotNull(getText("Bug53380_2.doc"));
@ -763,6 +792,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document * Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document
*/ */
@Test
public void testBug53380_3() throws Exception public void testBug53380_3() throws Exception
{ {
assertNotNull(getText("Bug53380_3.doc")); assertNotNull(getText("Bug53380_3.doc"));
@ -771,6 +801,7 @@ public class TestBugs extends TestCase
/** /**
* Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document * Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document
*/ */
@Test
public void testBug53380_4() throws Exception public void testBug53380_4() throws Exception
{ {
assertNotNull(getText("Bug53380_4.doc")); assertNotNull(getText("Bug53380_4.doc"));
@ -782,6 +813,7 @@ public class TestBugs extends TestCase
* *
* Disabled pending a fix for the bug * Disabled pending a fix for the bug
*/ */
@Test
public void test56880() throws Exception { public void test56880() throws Exception {
HWPFDocument doc = HWPFDocument doc =
HWPFTestDataSamples.openSampleFile("56880.doc"); HWPFTestDataSamples.openSampleFile("56880.doc");
@ -802,6 +834,7 @@ public class TestBugs extends TestCase
private int section2BottomMargin = 1440; private int section2BottomMargin = 1440;
private final int section2NumColumns = 3; private final int section2NumColumns = 3;
@Test
@SuppressWarnings("SuspiciousNameCombination") @SuppressWarnings("SuspiciousNameCombination")
public void testHWPFSections() { public void testHWPFSections() {
HWPFDocument document = HWPFTestDataSamples.openSampleFile("Bug53453Section.doc"); HWPFDocument document = HWPFTestDataSamples.openSampleFile("Bug53453Section.doc");
@ -875,19 +908,16 @@ public class TestBugs extends TestCase
assertNotNull(hwpfDocument); assertNotNull(hwpfDocument);
} }
@Test(expected=ArrayIndexOutOfBoundsException.class)
public void test57603SevenRowTable() throws Exception { public void test57603SevenRowTable() throws Exception {
try { HWPFDocument hwpfDocument = HWPFTestDataSamples.openSampleFile("57603-seven_columns.doc");
HWPFDocument hwpfDocument = HWPFTestDataSamples.openSampleFile("57603-seven_columns.doc"); HWPFDocument hwpfDocument2 = HWPFTestDataSamples.writeOutAndReadBack(hwpfDocument);
HWPFDocument hwpfDocument2 = HWPFTestDataSamples.writeOutAndReadBack(hwpfDocument); assertNotNull(hwpfDocument2);
assertNotNull(hwpfDocument2); hwpfDocument2.close();
hwpfDocument2.close(); hwpfDocument.close();
hwpfDocument.close();
fixed("57603");
} catch (ArrayIndexOutOfBoundsException e) {
// expected until this bug is fixed
}
} }
@Test(expected=ArrayIndexOutOfBoundsException.class)
public void test57843() throws IOException { public void test57843() throws IOException {
File f = POIDataSamples.getDocumentInstance().getFile("57843.doc"); File f = POIDataSamples.getDocumentInstance().getFile("57843.doc");
POIFSFileSystem fs = new POIFSFileSystem(f, true); POIFSFileSystem fs = new POIFSFileSystem(f, true);
@ -895,9 +925,6 @@ public class TestBugs extends TestCase
HWPFOldDocument doc = new HWPFOldDocument(fs); HWPFOldDocument doc = new HWPFOldDocument(fs);
assertNotNull(doc); assertNotNull(doc);
doc.close(); doc.close();
fixed("57843");
} catch (ArrayIndexOutOfBoundsException e) {
// expected until this bug is fixed
} finally { } finally {
fs.close(); fs.close();
} }

View File

@ -17,22 +17,27 @@
package org.apache.poi.hwpf.usermodel; package org.apache.poi.hwpf.usermodel;
import java.util.List; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import junit.framework.TestCase; import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.SEPX; import org.apache.poi.hwpf.model.SEPX;
import org.junit.Test;
/** /**
* Tests for Range which aren't around deletion, insertion, text replacement or * Tests for Range which aren't around deletion, insertion, text replacement or
* textual contents * textual contents
*/ */
public final class TestRange extends TestCase public final class TestRange {
{ private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance();
public void testFieldStripping()
{ @Test
public void testFieldStripping() {
String exp = "This is some text."; String exp = "This is some text.";
String single = "This is some \u0013Blah!\u0015text."; String single = "This is some \u0013Blah!\u0015text.";
@ -57,10 +62,11 @@ public final class TestRange extends TestCase
assertEquals( odd2, Range.stripFields( odd2 ) ); assertEquals( odd2, Range.stripFields( odd2 ) );
} }
public void testBug46817() throws Exception @Test
{ public void testBug46817() throws IOException {
HWPFDocument hwpfDocument = new HWPFDocument( POIDataSamples InputStream is = SAMPLES.openResourceAsStream( "Bug46817.doc" );
.getDocumentInstance().openResourceAsStream( "Bug46817.doc" ) ); HWPFDocument hwpfDocument = new HWPFDocument( is );
is.close();
final List<SEPX> sections = hwpfDocument.getSectionTable() final List<SEPX> sections = hwpfDocument.getSectionTable()
.getSections(); .getSections();
@ -85,5 +91,6 @@ public final class TestRange extends TestCase
Paragraph lastInMainSection = section.getParagraph( section Paragraph lastInMainSection = section.getParagraph( section
.numParagraphs() - 1); .numParagraphs() - 1);
assertTrue( lastInMainSection.getEndOffset() <= 766 ); assertTrue( lastInMainSection.getEndOffset() <= 766 );
hwpfDocument.close();
} }
} }

View File

@ -16,16 +16,23 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.hwpf.usermodel; package org.apache.poi.hwpf.usermodel;
import junit.framework.TestCase; import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFDocument;
import org.junit.Test;
public class TestTableRow extends TestCase public class TestTableRow {
{ private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance();
public void testInnerTableCellsDetection() throws Exception
{ @Test
HWPFDocument hwpfDocument = new HWPFDocument( POIDataSamples public void testInnerTableCellsDetection() throws IOException {
.getDocumentInstance().openResourceAsStream( "innertable.doc" ) ); InputStream is = SAMPLES.openResourceAsStream( "innertable.doc" );
HWPFDocument hwpfDocument = new HWPFDocument( is );
is.close();
hwpfDocument.getRange(); hwpfDocument.getRange();
Range documentRange = hwpfDocument.getRange(); Range documentRange = hwpfDocument.getRange();
@ -36,12 +43,14 @@ public class TestTableRow extends TestCase
TableRow tableRow = innerTable.getRow( 0 ); TableRow tableRow = innerTable.getRow( 0 );
assertEquals( 2, tableRow.numCells() ); assertEquals( 2, tableRow.numCells() );
hwpfDocument.close();
} }
public void testOuterTableCellsDetection() throws Exception @Test
{ public void testOuterTableCellsDetection() throws IOException {
HWPFDocument hwpfDocument = new HWPFDocument( POIDataSamples InputStream is = SAMPLES.openResourceAsStream( "innertable.doc" );
.getDocumentInstance().openResourceAsStream( "innertable.doc" ) ); HWPFDocument hwpfDocument = new HWPFDocument( is );
is.close();
hwpfDocument.getRange(); hwpfDocument.getRange();
Range documentRange = hwpfDocument.getRange(); Range documentRange = hwpfDocument.getRange();
@ -53,6 +62,8 @@ public class TestTableRow extends TestCase
assertEquals( 3, outerTable.getRow( 0 ).numCells() ); assertEquals( 3, outerTable.getRow( 0 ).numCells() );
assertEquals( 3, outerTable.getRow( 1 ).numCells() ); assertEquals( 3, outerTable.getRow( 1 ).numCells() );
assertEquals( 3, outerTable.getRow( 2 ).numCells() ); assertEquals( 3, outerTable.getRow( 2 ).numCells() );
hwpfDocument.close();
} }
} }

View File

@ -17,29 +17,28 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Date; import java.util.Date;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.HSSFFormulaParser; import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.formula.ptg.NamePtg;
import org.apache.poi.hssf.util.CellReference; import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.util.TempFile;
import org.apache.poi.ss.formula.FormulaType; import org.apache.poi.ss.formula.FormulaType;
import org.apache.poi.ss.formula.ptg.NamePtg;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Name; import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.util.TempFile;
import org.junit.Test;
/** public final class TestFormulas {
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Avik Sengupta
*/
public final class TestFormulas extends TestCase {
private static HSSFWorkbook openSample(String sampleFileName) { private static HSSFWorkbook openSample(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
@ -48,10 +47,11 @@ public final class TestFormulas extends TestCase {
/** /**
* Add 1+1 -- WHoohoo! * Add 1+1 -- WHoohoo!
*/ */
public void testBasicAddIntegers() { @Test
public void testBasicAddIntegers() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb1.createSheet();
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
@ -60,78 +60,90 @@ public final class TestFormulas extends TestCase {
c = r.createCell(1); c = r.createCell(1);
c.setCellFormula(1 + "+" + 1); c.setCellFormula(1 + "+" + 1);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
s = wb.getSheetAt(0); wb1.close();
s = wb2.getSheetAt(0);
r = s.getRow(1); r = s.getRow(1);
c = r.getCell(1); c = r.getCell(1);
assertTrue("Formula is as expected",("1+1".equals(c.getCellFormula()))); assertTrue("Formula is as expected",("1+1".equals(c.getCellFormula())));
wb2.close();
} }
/** /**
* Add various integers * Add various integers
*/ */
public void testAddIntegers() { @Test
public void testAddIntegers() throws IOException {
binomialOperator("+"); binomialOperator("+");
} }
/** /**
* Multiply various integers * Multiply various integers
*/ */
public void testMultplyIntegers() { @Test
public void testMultplyIntegers() throws IOException {
binomialOperator("*"); binomialOperator("*");
} }
/** /**
* Subtract various integers * Subtract various integers
*/ */
public void testSubtractIntegers() { @Test
public void testSubtractIntegers() throws IOException {
binomialOperator("-"); binomialOperator("-");
} }
/** /**
* Subtract various integers * Subtract various integers
*/ */
public void testDivideIntegers() { @Test
public void testDivideIntegers() throws IOException {
binomialOperator("/"); binomialOperator("/");
} }
/** /**
* Exponentialize various integers; * Exponentialize various integers;
*/ */
public void testPowerIntegers() { @Test
public void testPowerIntegers() throws IOException {
binomialOperator("^"); binomialOperator("^");
} }
/** /**
* Concatenate two numbers 1&2 = 12 * Concatenate two numbers 1&2 = 12
*/ */
public void testConcatIntegers() { @Test
public void testConcatIntegers() throws IOException {
binomialOperator("&"); binomialOperator("&");
} }
/** /**
* tests 1*2+3*4 * tests 1*2+3*4
*/ */
public void testOrderOfOperationsMultiply() { @Test
public void testOrderOfOperationsMultiply() throws IOException {
orderTest("1*2+3*4"); orderTest("1*2+3*4");
} }
/** /**
* tests 1*2+3^4 * tests 1*2+3^4
*/ */
public void testOrderOfOperationsPower() { @Test
public void testOrderOfOperationsPower() throws IOException {
orderTest("1*2+3^4"); orderTest("1*2+3^4");
} }
/** /**
* Tests that parenthesis are obeyed * Tests that parenthesis are obeyed
*/ */
public void testParenthesis() { @Test
public void testParenthesis() throws IOException {
orderTest("(1*3)+2+(1+2)*(3^4)^5"); orderTest("(1*3)+2+(1+2)*(3^4)^5");
} }
public void testReferencesOpr() { @Test
public void testReferencesOpr() throws IOException {
String[] operation = new String[] { String[] operation = new String[] {
"+", "-", "*", "/", "^", "&" "+", "-", "*", "/", "^", "&"
}; };
@ -144,14 +156,15 @@ public final class TestFormulas extends TestCase {
* Tests creating a file with floating point in a formula. * Tests creating a file with floating point in a formula.
* *
*/ */
public void testFloat() { @Test
public void testFloat() throws IOException {
floatTest("*"); floatTest("*");
floatTest("/"); floatTest("/");
} }
private static void floatTest(String operator) { private static void floatTest(String operator) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb1.createSheet();
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
@ -177,9 +190,11 @@ public final class TestFormulas extends TestCase {
c = r.createCell(0); c = r.createCell(0);
c.setCellFormula("" + Float.MAX_VALUE + operator + Float.MAX_VALUE); c.setCellFormula("" + Float.MAX_VALUE + operator + Float.MAX_VALUE);
} }
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
floatVerify(operator, wb); floatVerify(operator, wb2);
wb2.close();
} }
private static void floatVerify(String operator, HSSFWorkbook wb) { private static void floatVerify(String operator, HSSFWorkbook wb) {
@ -202,25 +217,29 @@ public final class TestFormulas extends TestCase {
} }
} }
public void testAreaSum() { @Test
public void testAreaSum() throws IOException {
areaFunctionTest("SUM"); areaFunctionTest("SUM");
} }
public void testAreaAverage() { @Test
public void testAreaAverage() throws IOException {
areaFunctionTest("AVERAGE"); areaFunctionTest("AVERAGE");
} }
public void testRefArraySum() { @Test
public void testRefArraySum() throws IOException {
refArrayFunctionTest("SUM"); refArrayFunctionTest("SUM");
} }
public void testAreaArraySum() { @Test
public void testAreaArraySum() throws IOException {
refAreaArrayFunctionTest("SUM"); refAreaArrayFunctionTest("SUM");
} }
private static void operationRefTest(String operator) { private static void operationRefTest(String operator) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb1.createSheet();
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
@ -277,8 +296,10 @@ public final class TestFormulas extends TestCase {
c.setCellFormula("" + "B1" + operator + "IV255"); c.setCellFormula("" + "B1" + operator + "IV255");
} }
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
operationalRefVerify(operator, wb); wb1.close();
operationalRefVerify(operator, wb2);
wb2.close();
} }
/** /**
@ -352,9 +373,9 @@ public final class TestFormulas extends TestCase {
/** /**
* tests order wrting out == order writing in for a given formula * tests order wrting out == order writing in for a given formula
*/ */
private static void orderTest(String formula) { private static void orderTest(String formula) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb1.createSheet();
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
@ -363,15 +384,15 @@ public final class TestFormulas extends TestCase {
c = r.createCell(1); c = r.createCell(1);
c.setCellFormula(formula); c.setCellFormula(formula);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
s = wb.getSheetAt(0); wb1.close();
s = wb2.getSheetAt(0);
//get our minimum values //get our minimum values
r = s.getRow(0); r = s.getRow(0);
c = r.getCell(1); c = r.getCell(1);
assertTrue("minval Formula is as expected", assertTrue("minval Formula is as expected", formula.equals(c.getCellFormula()));
formula.equals(c.getCellFormula()) wb2.close();
);
} }
/** /**
@ -379,9 +400,9 @@ public final class TestFormulas extends TestCase {
* huge set of x operator y formulas. Next we call binomialVerify and verify * huge set of x operator y formulas. Next we call binomialVerify and verify
* that they are all how we expect. * that they are all how we expect.
*/ */
private static void binomialOperator(String operator) { private static void binomialOperator(String operator) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb1.createSheet();
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
@ -407,8 +428,10 @@ public final class TestFormulas extends TestCase {
c = r.createCell(0); c = r.createCell(0);
c.setCellFormula("" + Short.MAX_VALUE + operator + Short.MAX_VALUE); c.setCellFormula("" + Short.MAX_VALUE + operator + Short.MAX_VALUE);
} }
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
binomialVerify(operator, wb); wb1.close();
binomialVerify(operator, wb2);
wb2.close();
} }
/** /**
@ -454,10 +477,10 @@ public final class TestFormulas extends TestCase {
/** /**
* Writes a function then tests to see if its correct * Writes a function then tests to see if its correct
*/ */
public static void areaFunctionTest(String function) { public static void areaFunctionTest(String function) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb1.createSheet();
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
@ -467,23 +490,25 @@ public final class TestFormulas extends TestCase {
c = r.createCell(0); c = r.createCell(0);
c.setCellFormula(function+"(A2:A3)"); c.setCellFormula(function+"(A2:A3)");
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
s = wb.getSheetAt(0); wb1.close();
s = wb2.getSheetAt(0);
r = s.getRow(0); r = s.getRow(0);
c = r.getCell(0); c = r.getCell(0);
assertTrue("function ="+function+"(A2:A3)", assertTrue("function ="+function+"(A2:A3)",
( (function+"(A2:A3)").equals((function+"(A2:A3)")) ) ( (function+"(A2:A3)").equals((function+"(A2:A3)")) )
); );
wb2.close();
} }
/** /**
* Writes a function then tests to see if its correct * Writes a function then tests to see if its correct
*/ */
public void refArrayFunctionTest(String function) { public void refArrayFunctionTest(String function) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb1.createSheet();
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
@ -493,14 +518,16 @@ public final class TestFormulas extends TestCase {
c = r.createCell(0); c = r.createCell(0);
c.setCellFormula(function+"(A2,A3)"); c.setCellFormula(function+"(A2,A3)");
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
s = wb.getSheetAt(0); wb1.close();
s = wb2.getSheetAt(0);
r = s.getRow(0); r = s.getRow(0);
c = r.getCell(0); c = r.getCell(0);
assertTrue("function ="+function+"(A2,A3)", assertTrue("function ="+function+"(A2,A3)",
( (function+"(A2,A3)").equals(c.getCellFormula()) ) ( (function+"(A2,A3)").equals(c.getCellFormula()) )
); );
wb2.close();
} }
@ -508,10 +535,10 @@ public final class TestFormulas extends TestCase {
* Writes a function then tests to see if its correct * Writes a function then tests to see if its correct
* *
*/ */
public void refAreaArrayFunctionTest(String function) { public void refAreaArrayFunctionTest(String function) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb1.createSheet();
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
@ -523,8 +550,9 @@ public final class TestFormulas extends TestCase {
c=r.createCell(1); c=r.createCell(1);
c.setCellFormula(function+"($A$2:$A4,B$2:B4)"); c.setCellFormula(function+"($A$2:$A4,B$2:B4)");
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
s = wb.getSheetAt(0); wb1.close();
s = wb2.getSheetAt(0);
r = s.getRow(0); r = s.getRow(0);
c = r.getCell(0); c = r.getCell(0);
@ -536,13 +564,14 @@ public final class TestFormulas extends TestCase {
assertTrue("function ="+function+"($A$2:$A4,B$2:B4)", assertTrue("function ="+function+"($A$2:$A4,B$2:B4)",
( (function+"($A$2:$A4,B$2:B4)").equals(c.getCellFormula()) ) ( (function+"($A$2:$A4,B$2:B4)").equals(c.getCellFormula()) )
); );
wb2.close();
} }
@Test
public void testAbsRefs() { public void testAbsRefs() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb1.createSheet();
HSSFRow r; HSSFRow r;
HSSFCell c; HSSFCell c;
@ -558,8 +587,9 @@ public final class TestFormulas extends TestCase {
c=r.createCell(4); c=r.createCell(4);
c.setCellFormula("SUM($A$3,$A$2)"); c.setCellFormula("SUM($A$3,$A$2)");
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
s = wb.getSheetAt(0); wb1.close();
s = wb2.getSheetAt(0);
r = s.getRow(0); r = s.getRow(0);
c = r.getCell(0); c = r.getCell(0);
assertTrue("A3+A2", ("A3+A2").equals(c.getCellFormula())); assertTrue("A3+A2", ("A3+A2").equals(c.getCellFormula()));
@ -571,34 +601,39 @@ public final class TestFormulas extends TestCase {
assertTrue("$A$3+$A$2", ("$A$3+$A$2").equals(c.getCellFormula())); assertTrue("$A$3+$A$2", ("$A$3+$A$2").equals(c.getCellFormula()));
c = r.getCell(4); c = r.getCell(4);
assertTrue("SUM($A$3,$A$2)", ("SUM($A$3,$A$2)").equals(c.getCellFormula())); assertTrue("SUM($A$3,$A$2)", ("SUM($A$3,$A$2)").equals(c.getCellFormula()));
wb2.close();
} }
public void testSheetFunctions() { @Test
HSSFWorkbook wb = new HSSFWorkbook(); public void testSheetFunctions() throws IOException {
HSSFSheet s = wb.createSheet("A"); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb1.createSheet("A");
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
r = s.createRow(0); r = s.createRow(0);
c = r.createCell(0);c.setCellValue(1); c = r.createCell(0);c.setCellValue(1);
c = r.createCell(1);c.setCellValue(2); c = r.createCell(1);c.setCellValue(2);
s = wb.createSheet("B"); s = wb1.createSheet("B");
r = s.createRow(0); r = s.createRow(0);
c=r.createCell(0); c.setCellFormula("AVERAGE(A!A1:B1)"); c=r.createCell(0); c.setCellFormula("AVERAGE(A!A1:B1)");
c=r.createCell(1); c.setCellFormula("A!A1+A!B1"); c=r.createCell(1); c.setCellFormula("A!A1+A!B1");
c=r.createCell(2); c.setCellFormula("A!$A$1+A!$B1"); c=r.createCell(2); c.setCellFormula("A!$A$1+A!$B1");
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
s = wb.getSheet("B"); s = wb2.getSheet("B");
r = s.getRow(0); r = s.getRow(0);
c = r.getCell(0); c = r.getCell(0);
assertTrue("expected: AVERAGE(A!A1:B1) got: "+c.getCellFormula(), ("AVERAGE(A!A1:B1)").equals(c.getCellFormula())); assertTrue("expected: AVERAGE(A!A1:B1) got: "+c.getCellFormula(), ("AVERAGE(A!A1:B1)").equals(c.getCellFormula()));
c = r.getCell(1); c = r.getCell(1);
assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula())); assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula()));
wb2.close();
} }
public void testRVAoperands() throws Exception { @Test
public void testRVAoperands() throws IOException {
File file = TempFile.createTempFile("testFormulaRVA",".xls"); File file = TempFile.createTempFile("testFormulaRVA",".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -634,9 +669,11 @@ public final class TestFormulas extends TestCase {
wb.write(out); wb.write(out);
out.close(); out.close();
assertTrue("file exists",file.exists()); assertTrue("file exists",file.exists());
wb.close();
} }
public void testStringFormulas() { @Test
public void testStringFormulas() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("A"); HSSFSheet s = wb.createSheet("A");
HSSFRow r = null; HSSFRow r = null;
@ -646,32 +683,38 @@ public final class TestFormulas extends TestCase {
c=r.createCell(2); c.setCellFormula("LOWER(\"ABC\")"); c=r.createCell(2); c.setCellFormula("LOWER(\"ABC\")");
c=r.createCell(3); c.setCellFormula("CONCATENATE(\" my \",\" name \")"); c=r.createCell(3); c.setCellFormula("CONCATENATE(\" my \",\" name \")");
HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFTestDataSamples.writeOutAndReadBack(wb).close();
wb.close();
wb = openSample("StringFormulas.xls"); wb = openSample("StringFormulas.xls");
s = wb.getSheetAt(0); s = wb.getSheetAt(0);
r = s.getRow(0); r = s.getRow(0);
c = r.getCell(0); c = r.getCell(0);
assertEquals("UPPER(\"xyz\")", c.getCellFormula()); assertEquals("UPPER(\"xyz\")", c.getCellFormula());
wb.close();
} }
public void testLogicalFormulas() { @Test
public void testLogicalFormulas() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("A"); HSSFSheet s = wb1.createSheet("A");
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
r = s.createRow(0); r = s.createRow(0);
c=r.createCell(1); c.setCellFormula("IF(A1<A2,B1,B2)"); c=r.createCell(1); c.setCellFormula("IF(A1<A2,B1,B2)");
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
s = wb.getSheetAt(0); wb1.close();
s = wb2.getSheetAt(0);
r = s.getRow(0); r = s.getRow(0);
c = r.getCell(1); c = r.getCell(1);
assertEquals("Formula in cell 1 ","IF(A1<A2,B1,B2)",c.getCellFormula()); assertEquals("Formula in cell 1 ","IF(A1<A2,B1,B2)",c.getCellFormula());
wb2.close();
} }
public void testDateFormulas() { @Test
public void testDateFormulas() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("testSheet1"); HSSFSheet s = wb.createSheet("testSheet1");
HSSFRow r = null; HSSFRow r = null;
@ -695,13 +738,14 @@ public final class TestFormulas extends TestCase {
c.setCellStyle(cellStyle); c.setCellStyle(cellStyle);
} }
HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFTestDataSamples.writeOutAndReadBack(wb).close();
wb.close();
} }
@Test
public void testIfFormulas() { public void testIfFormulas() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("testSheet1"); HSSFSheet s = wb1.createSheet("testSheet1");
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
r = s.createRow(0); r = s.createRow(0);
@ -710,33 +754,37 @@ public final class TestFormulas extends TestCase {
c=r.createCell(3); c.setCellFormula("MAX(A1:B1)"); c=r.createCell(3); c.setCellFormula("MAX(A1:B1)");
c=r.createCell(4); c.setCellFormula("IF(A1=D1,\"A1\",\"B1\")"); c=r.createCell(4); c.setCellFormula("IF(A1=D1,\"A1\",\"B1\")");
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
s = wb.getSheetAt(0); wb1.close();
s = wb2.getSheetAt(0);
r = s.getRow(0); r = s.getRow(0);
c = r.getCell(4); c = r.getCell(4);
assertTrue("expected: IF(A1=D1,\"A1\",\"B1\") got "+c.getCellFormula(), ("IF(A1=D1,\"A1\",\"B1\")").equals(c.getCellFormula())); assertTrue("expected: IF(A1=D1,\"A1\",\"B1\") got "+c.getCellFormula(), ("IF(A1=D1,\"A1\",\"B1\")").equals(c.getCellFormula()));
wb2.close();
wb = openSample("IfFormulaTest.xls"); wb1 = openSample("IfFormulaTest.xls");
s = wb.getSheetAt(0); s = wb1.getSheetAt(0);
r = s.getRow(3); r = s.getRow(3);
c = r.getCell(0); c = r.getCell(0);
assertTrue("expected: IF(A3=A1,\"A1\",\"A2\") got "+c.getCellFormula(), ("IF(A3=A1,\"A1\",\"A2\")").equals(c.getCellFormula())); assertTrue("expected: IF(A3=A1,\"A1\",\"A2\") got "+c.getCellFormula(), ("IF(A3=A1,\"A1\",\"A2\")").equals(c.getCellFormula()));
//c = r.getCell((short)1); //c = r.getCell((short)1);
//assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula())); //assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula()));
wb1.close();
wb = new HSSFWorkbook(); wb1 = new HSSFWorkbook();
s = wb.createSheet("testSheet1"); s = wb1.createSheet("testSheet1");
r = null; r = null;
c = null; c = null;
r = s.createRow(0); r = s.createRow(0);
c=r.createCell(0); c.setCellFormula("IF(1=1,0,1)"); c=r.createCell(0); c.setCellFormula("IF(1=1,0,1)");
HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFTestDataSamples.writeOutAndReadBack(wb1).close();
wb1.close();
wb = new HSSFWorkbook(); wb1 = new HSSFWorkbook();
s = wb.createSheet("testSheet1"); s = wb1.createSheet("testSheet1");
r = null; r = null;
c = null; c = null;
r = s.createRow(0); r = s.createRow(0);
@ -758,10 +806,12 @@ public final class TestFormulas extends TestCase {
formulaCell.setCellFormula("IF(A1=B1,AVERAGE(A1:B1),AVERAGE(A2:B2))"); formulaCell.setCellFormula("IF(A1=B1,AVERAGE(A1:B1),AVERAGE(A2:B2))");
HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFTestDataSamples.writeOutAndReadBack(wb1).close();
wb1.close();
} }
public void testSumIf() { @Test
public void testSumIf() throws IOException {
String function ="SUMIF(A1:A5,\">4000\",B1:B5)"; String function ="SUMIF(A1:A5,\">4000\",B1:B5)";
HSSFWorkbook wb = openSample("sumifformula.xls"); HSSFWorkbook wb = openSample("sumifformula.xls");
@ -799,10 +849,12 @@ public final class TestFormulas extends TestCase {
r = s.getRow(0); r = s.getRow(0);
c=r.createCell(2); c.setCellFormula(function); c=r.createCell(2); c.setCellFormula(function);
HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFTestDataSamples.writeOutAndReadBack(wb).close();
wb.close();
} }
public void testSquareMacro() { @Test
public void testSquareMacro() throws IOException {
HSSFWorkbook w = openSample("SquareMacro.xls"); HSSFWorkbook w = openSample("SquareMacro.xls");
HSSFSheet s0 = w.getSheetAt(0); HSSFSheet s0 = w.getSheetAt(0);
@ -839,15 +891,20 @@ public final class TestFormulas extends TestCase {
HSSFCell d2 = r[1].getCell(3); HSSFCell d2 = r[1].getCell(3);
assertEquals("square(two())", d2.getCellFormula()); assertEquals("square(two())", d2.getCellFormula());
assertEquals(4d, d2.getNumericCellValue(), 1e-9); assertEquals(4d, d2.getNumericCellValue(), 1e-9);
w.close();
} }
public void testStringFormulaRead() { @Test
public void testStringFormulaRead() throws IOException {
HSSFWorkbook w = openSample("StringFormulas.xls"); HSSFWorkbook w = openSample("StringFormulas.xls");
HSSFCell c = w.getSheetAt(0).getRow(0).getCell(0); HSSFCell c = w.getSheetAt(0).getRow(0).getCell(0);
assertEquals("String Cell value","XYZ",c.getRichStringCellValue().getString()); assertEquals("String Cell value","XYZ",c.getRichStringCellValue().getString());
w.close();
} }
/** test for bug 34021*/ /** test for bug 34021*/
@Test
public void testComplexSheetRefs () throws IOException { public void testComplexSheetRefs () throws IOException {
HSSFWorkbook sb = new HSSFWorkbook(); HSSFWorkbook sb = new HSSFWorkbook();
try { try {
@ -868,7 +925,8 @@ public final class TestFormulas extends TestCase {
} }
/** Unknown Ptg 3C*/ /** Unknown Ptg 3C*/
public void test27272_1() throws Exception { @Test
public void test27272_1() throws IOException {
HSSFWorkbook wb = openSample("27272_1.xls"); HSSFWorkbook wb = openSample("27272_1.xls");
wb.getSheetAt(0); wb.getSheetAt(0);
assertEquals("Reference for named range ", "Compliance!#REF!",wb.getNameAt(0).getRefersToFormula()); assertEquals("Reference for named range ", "Compliance!#REF!",wb.getNameAt(0).getRefersToFormula());
@ -879,10 +937,11 @@ public final class TestFormulas extends TestCase {
} finally { } finally {
stream.close(); stream.close();
} }
System.out.println("Open "+outF.getAbsolutePath()+" in Excel"); wb.close();
} }
/** Unknown Ptg 3D*/ /** Unknown Ptg 3D*/
public void test27272_2() throws Exception { @Test
public void test27272_2() throws IOException {
HSSFWorkbook wb = openSample("27272_2.xls"); HSSFWorkbook wb = openSample("27272_2.xls");
assertEquals("Reference for named range ", "LOAD.POD_HISTORIES!#REF!",wb.getNameAt(0).getRefersToFormula()); assertEquals("Reference for named range ", "LOAD.POD_HISTORIES!#REF!",wb.getNameAt(0).getRefersToFormula());
File outF = TempFile.createTempFile("bug27272_2",".xls"); File outF = TempFile.createTempFile("bug27272_2",".xls");
@ -892,11 +951,11 @@ public final class TestFormulas extends TestCase {
} finally { } finally {
stream.close(); stream.close();
} }
System.out.println("Open "+outF.getAbsolutePath()+" in Excel"); wb.close();
} }
/** MissingArgPtg /** MissingArgPtg */
* @throws IOException */ @Test
public void testMissingArgPtg() throws IOException { public void testMissingArgPtg() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
try { try {
@ -907,19 +966,22 @@ public final class TestFormulas extends TestCase {
} }
} }
public void testSharedFormula() { @Test
public void testSharedFormula() throws IOException {
HSSFWorkbook wb = openSample("SharedFormulaTest.xls"); HSSFWorkbook wb = openSample("SharedFormulaTest.xls");
assertEquals("A$1*2", wb.getSheetAt(0).getRow(1).getCell(1).toString()); assertEquals("A$1*2", wb.getSheetAt(0).getRow(1).getCell(1).toString());
assertEquals("$A11*2", wb.getSheetAt(0).getRow(11).getCell(1).toString()); assertEquals("$A11*2", wb.getSheetAt(0).getRow(11).getCell(1).toString());
assertEquals("DZ2*2", wb.getSheetAt(0).getRow(1).getCell(128).toString()); assertEquals("DZ2*2", wb.getSheetAt(0).getRow(1).getCell(128).toString());
assertEquals("B32770*2", wb.getSheetAt(0).getRow(32768).getCell(1).toString()); assertEquals("B32770*2", wb.getSheetAt(0).getRow(32768).getCell(1).toString());
wb.close();
} }
/** /**
* Test creation / evaluation of formulas with sheet-level names * Test creation / evaluation of formulas with sheet-level names
*/ */
public void testSheetLevelFormulas(){ @Test
public void testSheetLevelFormulas() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFRow row; HSSFRow row;
@ -961,13 +1023,14 @@ public final class TestFormulas extends TestCase {
assertEquals(5.0, evaluator.evaluate(sh2.getRow(0).getCell(1)).getNumberValue(), 0.0); assertEquals(5.0, evaluator.evaluate(sh2.getRow(0).getCell(1)).getNumberValue(), 0.0);
assertEquals(15.0, evaluator.evaluate(sh2.getRow(0).getCell(2)).getNumberValue(), 0.0); assertEquals(15.0, evaluator.evaluate(sh2.getRow(0).getCell(2)).getNumberValue(), 0.0);
wb.close();
} }
/** /**
* Verify that FormulaParser handles defined names beginning with underscores, * Verify that FormulaParser handles defined names beginning with underscores,
* see Bug #49640 * see Bug #49640
* @throws IOException
*/ */
@Test
public void testFormulasWithUnderscore() throws IOException{ public void testFormulasWithUnderscore() throws IOException{
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
try { try {

View File

@ -17,29 +17,30 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.InputStream; import java.io.InputStream;
import junit.framework.TestCase;
import org.apache.poi.hpsf.PropertySetFactory; import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.junit.Test;
/** /**
* Old-style setting of POIFS properties doesn't work with POI 3.0.2 * Old-style setting of POIFS properties doesn't work with POI 3.0.2
*
* @author Yegor Kozlov
*/ */
public class TestPOIFSProperties extends TestCase{ public class TestPOIFSProperties {
private static final String title = "Testing POIFS properties"; private static final String title = "Testing POIFS properties";
@Test
public void testFail() throws Exception { public void testFail() throws Exception {
InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls"); InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls");
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFWorkbook wb = new HSSFWorkbook(fs);
@ -55,17 +56,21 @@ public class TestPOIFSProperties extends TestCase{
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
wb.write(out); wb.write(out);
out.close(); out.close();
wb.close();
POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())); POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()));
SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
//failing assertion //failing assertion
assertEquals(title, summary2.getTitle()); assertEquals(title, summary2.getTitle());
fs2.close();
} }
@Test
public void testOK() throws Exception { public void testOK() throws Exception {
InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls"); InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls");
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
//set POIFS properties before constructing HSSFWorkbook //set POIFS properties before constructing HSSFWorkbook
SummaryInformation summary1 = (SummaryInformation)PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); SummaryInformation summary1 = (SummaryInformation)PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
@ -79,11 +84,12 @@ public class TestPOIFSProperties extends TestCase{
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
wb.write(out); wb.write(out);
out.close(); out.close();
wb.close();
//read the property //read the property
POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())); POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()));
SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
assertEquals(title, summary2.getTitle()); assertEquals(title, summary2.getTitle());
fs2.close();
} }
} }

View File

@ -21,11 +21,12 @@ import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.io.IOException;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
import org.apache.poi.util.HexRead; import org.apache.poi.util.HexRead;
import org.junit.After; import org.junit.After;
@ -33,7 +34,7 @@ import org.junit.Test;
public class TestXorEncryption { public class TestXorEncryption {
private static HSSFTestDataSamples samples = new HSSFTestDataSamples(); private static final HSSFTestDataSamples samples = new HSSFTestDataSamples();
// to not affect other tests running in the same JVM // to not affect other tests running in the same JVM
@After @After
@ -42,7 +43,7 @@ public class TestXorEncryption {
} }
@Test @Test
public void testXorEncryption() throws Exception { public void testXorEncryption() throws IOException {
// Xor-Password: abc // Xor-Password: abc
// 2.5.343 XORObfuscation // 2.5.343 XORObfuscation
// key = 20810 // key = 20810
@ -59,7 +60,7 @@ public class TestXorEncryption {
@SuppressWarnings("static-access") @SuppressWarnings("static-access")
@Test @Test
public void testUserFile() throws Exception { public void testUserFile() throws IOException {
Biff8EncryptionKey.setCurrentUserPassword("abc"); Biff8EncryptionKey.setCurrentUserPassword("abc");
NPOIFSFileSystem fs = new NPOIFSFileSystem(samples.getSampleFile("xor-encryption-abc.xls"), true); NPOIFSFileSystem fs = new NPOIFSFileSystem(samples.getSampleFile("xor-encryption-abc.xls"), true);
HSSFWorkbook hwb = new HSSFWorkbook(fs.getRoot(), true); HSSFWorkbook hwb = new HSSFWorkbook(fs.getRoot(), true);
@ -68,7 +69,7 @@ public class TestXorEncryption {
assertEquals(1.0, sh.getRow(0).getCell(0).getNumericCellValue(), 0.0); assertEquals(1.0, sh.getRow(0).getCell(0).getNumericCellValue(), 0.0);
assertEquals(2.0, sh.getRow(1).getCell(0).getNumericCellValue(), 0.0); assertEquals(2.0, sh.getRow(1).getCell(0).getNumericCellValue(), 0.0);
assertEquals(3.0, sh.getRow(2).getCell(0).getNumericCellValue(), 0.0); assertEquals(3.0, sh.getRow(2).getCell(0).getNumericCellValue(), 0.0);
hwb.close();
fs.close(); fs.close();
} }
} }

View File

@ -17,19 +17,24 @@
package org.apache.poi.poifs.filesystem; package org.apache.poi.poifs.filesystem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import org.junit.Test;
public class TestEntryUtils extends TestCase { public class TestEntryUtils {
private final byte[] dataSmallA = new byte[] { 12, 42, 11, -12, -121 }; private static final byte[] dataSmallA = new byte[] { 12, 42, 11, -12, -121 };
private final byte[] dataSmallB = new byte[] { 11, 73, 21, -92, -103 }; private static final byte[] dataSmallB = new byte[] { 11, 73, 21, -92, -103 };
public void testCopyRecursively() throws Exception { @Test
public void testCopyRecursively() throws IOException {
POIFSFileSystem fsD = new POIFSFileSystem(); POIFSFileSystem fsD = new POIFSFileSystem();
POIFSFileSystem fs = new POIFSFileSystem(); POIFSFileSystem fs = new POIFSFileSystem();
DirectoryEntry dirA = fs.createDirectory("DirA"); DirectoryEntry dirA = fs.createDirectory("DirA");
@ -56,6 +61,8 @@ public class TestEntryUtils extends TestCase {
assertNotNull(fsD.getRoot().getEntry("EntryRoot")); assertNotNull(fsD.getRoot().getEntry("EntryRoot"));
assertNotNull(fsD.getRoot().getEntry("EntryA1")); assertNotNull(fsD.getRoot().getEntry("EntryA1"));
assertNotNull(fsD.getRoot().getEntry("EntryA2")); assertNotNull(fsD.getRoot().getEntry("EntryA2"));
fsD.close();
// Copy directories // Copy directories
fsD = new POIFSFileSystem(); fsD = new POIFSFileSystem();
@ -72,6 +79,7 @@ public class TestEntryUtils extends TestCase {
assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount()); assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount());
assertNotNull(fsD.getRoot().getEntry("DirA")); assertNotNull(fsD.getRoot().getEntry("DirA"));
assertEquals(2, ((DirectoryEntry)fsD.getRoot().getEntry("DirA")).getEntryCount()); assertEquals(2, ((DirectoryEntry)fsD.getRoot().getEntry("DirA")).getEntryCount());
fsD.close();
// Copy the whole lot // Copy the whole lot
fsD = new POIFSFileSystem(); fsD = new POIFSFileSystem();
@ -84,9 +92,12 @@ public class TestEntryUtils extends TestCase {
assertNotNull(fsD.getRoot().getEntry(entryR.getName())); assertNotNull(fsD.getRoot().getEntry(entryR.getName()));
assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount()); assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount());
assertEquals(2, ((DirectoryEntry)fsD.getRoot().getEntry("DirA")).getEntryCount()); assertEquals(2, ((DirectoryEntry)fsD.getRoot().getEntry("DirA")).getEntryCount());
fsD.close();
fs.close();
} }
public void testAreDocumentsIdentical() throws Exception { @Test
public void testAreDocumentsIdentical() throws IOException {
POIFSFileSystem fs = new POIFSFileSystem(); POIFSFileSystem fs = new POIFSFileSystem();
DirectoryEntry dirA = fs.createDirectory("DirA"); DirectoryEntry dirA = fs.createDirectory("DirA");
DirectoryEntry dirB = fs.createDirectory("DirB"); DirectoryEntry dirB = fs.createDirectory("DirB");
@ -112,6 +123,7 @@ public class TestEntryUtils extends TestCase {
// Can work with NPOIFS + POIFS // Can work with NPOIFS + POIFS
ByteArrayOutputStream tmpO = new ByteArrayOutputStream(); ByteArrayOutputStream tmpO = new ByteArrayOutputStream();
fs.writeFilesystem(tmpO); fs.writeFilesystem(tmpO);
ByteArrayInputStream tmpI = new ByteArrayInputStream(tmpO.toByteArray()); ByteArrayInputStream tmpI = new ByteArrayInputStream(tmpO.toByteArray());
NPOIFSFileSystem nfs = new NPOIFSFileSystem(tmpI); NPOIFSFileSystem nfs = new NPOIFSFileSystem(tmpI);
@ -129,9 +141,12 @@ public class TestEntryUtils extends TestCase {
assertEquals(true, EntryUtils.areDocumentsIdentical(eNA1, entryA1)); assertEquals(true, EntryUtils.areDocumentsIdentical(eNA1, entryA1));
assertEquals(true, EntryUtils.areDocumentsIdentical(eNA1, entryB1)); assertEquals(true, EntryUtils.areDocumentsIdentical(eNA1, entryB1));
nfs.close();
fs.close();
} }
public void testAreDirectoriesIdentical() throws Exception { @Test
public void testAreDirectoriesIdentical() throws IOException {
POIFSFileSystem fs = new POIFSFileSystem(); POIFSFileSystem fs = new POIFSFileSystem();
DirectoryEntry dirA = fs.createDirectory("DirA"); DirectoryEntry dirA = fs.createDirectory("DirA");
DirectoryEntry dirB = fs.createDirectory("DirB"); DirectoryEntry dirB = fs.createDirectory("DirB");
@ -187,5 +202,7 @@ public class TestEntryUtils extends TestCase {
dirBI.createDocument("IgnZZ", new ByteArrayInputStream(dataSmallA)); dirBI.createDocument("IgnZZ", new ByteArrayInputStream(dataSmallA));
assertEquals(true, EntryUtils.areDirectoriesIdentical(fdA, fdB)); assertEquals(true, EntryUtils.areDirectoriesIdentical(fdA, fdB));
fs.close();
} }
} }

View File

@ -24,7 +24,12 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.*; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.Iterator; import java.util.Iterator;
@ -53,7 +58,7 @@ public final class TestNPOIFSFileSystem {
* Returns test files with 512 byte and 4k block sizes, loaded * Returns test files with 512 byte and 4k block sizes, loaded
* both from InputStreams and Files * both from InputStreams and Files
*/ */
protected NPOIFSFileSystem[] get512and4kFileAndInput() throws Exception { protected NPOIFSFileSystem[] get512and4kFileAndInput() throws IOException {
NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi")); NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
NPOIFSFileSystem fsC = new NPOIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); NPOIFSFileSystem fsC = new NPOIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
@ -82,8 +87,9 @@ public final class TestNPOIFSFileSystem {
assertEquals(doc.getSize(), inp.read(contents)); assertEquals(doc.getSize(), inp.read(contents));
inp.close(); inp.close();
if (expected != null) if (expected != null) {
assertThat(expected, equalTo(contents)); assertThat(expected, equalTo(contents));
}
} }
protected static HeaderBlock writeOutAndReadHeader(NPOIFSFileSystem fs) throws IOException { protected static HeaderBlock writeOutAndReadHeader(NPOIFSFileSystem fs) throws IOException {
@ -97,7 +103,6 @@ public final class TestNPOIFSFileSystem {
protected static NPOIFSFileSystem writeOutAndReadBack(NPOIFSFileSystem original) throws IOException { protected static NPOIFSFileSystem writeOutAndReadBack(NPOIFSFileSystem original) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
original.writeFilesystem(baos); original.writeFilesystem(baos);
original.close();
return new NPOIFSFileSystem(new ByteArrayInputStream(baos.toByteArray())); return new NPOIFSFileSystem(new ByteArrayInputStream(baos.toByteArray()));
} }
@ -109,12 +114,11 @@ public final class TestNPOIFSFileSystem {
} finally { } finally {
fout.close(); fout.close();
} }
original.close();
return new NPOIFSFileSystem(file, false); return new NPOIFSFileSystem(file, false);
} }
@Test @Test
public void basicOpen() throws Exception { public void basicOpen() throws IOException {
NPOIFSFileSystem fsA, fsB; NPOIFSFileSystem fsA, fsB;
// With a simple 512 block file // With a simple 512 block file
@ -137,7 +141,7 @@ public final class TestNPOIFSFileSystem {
} }
@Test @Test
public void propertiesAndFatOnRead() throws Exception { public void propertiesAndFatOnRead() throws IOException {
NPOIFSFileSystem fsA, fsB; NPOIFSFileSystem fsA, fsB;
// With a simple 512 block file // With a simple 512 block file
@ -280,7 +284,7 @@ public final class TestNPOIFSFileSystem {
* out what the next one is * out what the next one is
*/ */
@Test @Test
public void nextBlock() throws Exception { public void nextBlock() throws IOException {
NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi")); NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
for(NPOIFSFileSystem fs : new NPOIFSFileSystem[] {fsA,fsB}) { for(NPOIFSFileSystem fs : new NPOIFSFileSystem[] {fsA,fsB}) {
@ -342,7 +346,7 @@ public final class TestNPOIFSFileSystem {
* Check we get the right data back for each block * Check we get the right data back for each block
*/ */
@Test @Test
public void getBlock() throws Exception { public void getBlock() throws IOException {
NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi")); NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
for(NPOIFSFileSystem fs : new NPOIFSFileSystem[] {fsA,fsB}) { for(NPOIFSFileSystem fs : new NPOIFSFileSystem[] {fsA,fsB}) {
@ -416,7 +420,7 @@ public final class TestNPOIFSFileSystem {
* to be had from the FAT * to be had from the FAT
*/ */
@Test @Test
public void getFreeBlockWithSpare() throws Exception { public void getFreeBlockWithSpare() throws IOException {
NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi")); NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
// Our first BAT block has spares // Our first BAT block has spares
@ -447,142 +451,143 @@ public final class TestNPOIFSFileSystem {
* file needs to be extended and another BAT/XBAT added * file needs to be extended and another BAT/XBAT added
*/ */
@Test @Test
public void getFreeBlockWithNoneSpare() throws Exception { public void getFreeBlockWithNoneSpare() throws IOException {
NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); NPOIFSFileSystem fs1 = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
int free; int free;
// We have one BAT at block 99 // We have one BAT at block 99
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(99));
assertBATCount(fs, 1, 0); assertBATCount(fs1, 1, 0);
// We've spare ones from 100 to 128 // We've spare ones from 100 to 128
for(int i=100; i<128; i++) { for(int i=100; i<128; i++) {
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(i)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(i));
} }
// Check our BAT knows it's free // Check our BAT knows it's free
assertEquals(true, fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); assertEquals(true, fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
// Allocate all the spare ones // Allocate all the spare ones
for(int i=100; i<128; i++) { for(int i=100; i<128; i++) {
fs.setNextBlock(i, POIFSConstants.END_OF_CHAIN); fs1.setNextBlock(i, POIFSConstants.END_OF_CHAIN);
} }
// BAT is now full, but there's only the one // BAT is now full, but there's only the one
assertEquals(false, fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); assertEquals(false, fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
try { try {
assertEquals(false, fs.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); assertEquals(false, fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
fail("Should only be one BAT"); fail("Should only be one BAT");
} catch(IndexOutOfBoundsException e) {} } catch(IndexOutOfBoundsException e) {}
assertBATCount(fs, 1, 0); assertBATCount(fs1, 1, 0);
// Now ask for a free one, will need to extend the file // Now ask for a free one, will need to extend the file
assertEquals(129, fs.getFreeBlock()); assertEquals(129, fs1.getFreeBlock());
assertEquals(false, fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); assertEquals(false, fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
assertEquals(true, fs.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); assertEquals(true, fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(128)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(128));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(129)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(129));
// We now have 2 BATs, but no XBATs // We now have 2 BATs, but no XBATs
assertBATCount(fs, 2, 0); assertBATCount(fs1, 2, 0);
// Fill up to hold 109 BAT blocks // Fill up to hold 109 BAT blocks
for(int i=0; i<109; i++) { for(int i=0; i<109; i++) {
fs.getFreeBlock(); fs1.getFreeBlock();
int startOffset = i*128; int startOffset = i*128;
while( fs.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors() ) { while( fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors() ) {
free = fs.getFreeBlock(); free = fs1.getFreeBlock();
fs.setNextBlock(free, POIFSConstants.END_OF_CHAIN); fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN);
} }
} }
assertEquals(false, fs.getBATBlockAndIndex(109*128-1).getBlock().hasFreeSectors()); assertEquals(false, fs1.getBATBlockAndIndex(109*128-1).getBlock().hasFreeSectors());
try { try {
assertEquals(false, fs.getBATBlockAndIndex(109*128).getBlock().hasFreeSectors()); assertEquals(false, fs1.getBATBlockAndIndex(109*128).getBlock().hasFreeSectors());
fail("Should only be 109 BATs"); fail("Should only be 109 BATs");
} catch(IndexOutOfBoundsException e) {} } catch(IndexOutOfBoundsException e) {}
// We now have 109 BATs, but no XBATs // We now have 109 BATs, but no XBATs
assertBATCount(fs, 109, 0); assertBATCount(fs1, 109, 0);
// Ask for it to be written out, and check the header // Ask for it to be written out, and check the header
HeaderBlock header = writeOutAndReadHeader(fs); HeaderBlock header = writeOutAndReadHeader(fs1);
assertEquals(109, header.getBATCount()); assertEquals(109, header.getBATCount());
assertEquals(0, header.getXBATCount()); assertEquals(0, header.getXBATCount());
// Ask for another, will get our first XBAT // Ask for another, will get our first XBAT
free = fs.getFreeBlock(); free = fs1.getFreeBlock();
assertEquals(false, fs.getBATBlockAndIndex(109*128-1).getBlock().hasFreeSectors()); assertEquals(false, fs1.getBATBlockAndIndex(109*128-1).getBlock().hasFreeSectors());
assertEquals(true, fs.getBATBlockAndIndex(110*128-1).getBlock().hasFreeSectors()); assertEquals(true, fs1.getBATBlockAndIndex(110*128-1).getBlock().hasFreeSectors());
try { try {
assertEquals(false, fs.getBATBlockAndIndex(110*128).getBlock().hasFreeSectors()); assertEquals(false, fs1.getBATBlockAndIndex(110*128).getBlock().hasFreeSectors());
fail("Should only be 110 BATs"); fail("Should only be 110 BATs");
} catch(IndexOutOfBoundsException e) {} } catch(IndexOutOfBoundsException e) {}
assertBATCount(fs, 110, 1); assertBATCount(fs1, 110, 1);
header = writeOutAndReadHeader(fs); header = writeOutAndReadHeader(fs1);
assertEquals(110, header.getBATCount()); assertEquals(110, header.getBATCount());
assertEquals(1, header.getXBATCount()); assertEquals(1, header.getXBATCount());
// Fill the XBAT, which means filling 127 BATs // Fill the XBAT, which means filling 127 BATs
for(int i=109; i<109+127; i++) { for(int i=109; i<109+127; i++) {
fs.getFreeBlock(); fs1.getFreeBlock();
int startOffset = i*128; int startOffset = i*128;
while( fs.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors() ) { while( fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors() ) {
free = fs.getFreeBlock(); free = fs1.getFreeBlock();
fs.setNextBlock(free, POIFSConstants.END_OF_CHAIN); fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN);
} }
assertBATCount(fs, i+1, 1); assertBATCount(fs1, i+1, 1);
} }
// Should now have 109+127 = 236 BATs // Should now have 109+127 = 236 BATs
assertEquals(false, fs.getBATBlockAndIndex(236*128-1).getBlock().hasFreeSectors()); assertEquals(false, fs1.getBATBlockAndIndex(236*128-1).getBlock().hasFreeSectors());
try { try {
assertEquals(false, fs.getBATBlockAndIndex(236*128).getBlock().hasFreeSectors()); assertEquals(false, fs1.getBATBlockAndIndex(236*128).getBlock().hasFreeSectors());
fail("Should only be 236 BATs"); fail("Should only be 236 BATs");
} catch(IndexOutOfBoundsException e) {} } catch(IndexOutOfBoundsException e) {}
assertBATCount(fs, 236, 1); assertBATCount(fs1, 236, 1);
// Ask for another, will get our 2nd XBAT // Ask for another, will get our 2nd XBAT
free = fs.getFreeBlock(); free = fs1.getFreeBlock();
assertEquals(false, fs.getBATBlockAndIndex(236*128-1).getBlock().hasFreeSectors()); assertEquals(false, fs1.getBATBlockAndIndex(236*128-1).getBlock().hasFreeSectors());
assertEquals(true, fs.getBATBlockAndIndex(237*128-1).getBlock().hasFreeSectors()); assertEquals(true, fs1.getBATBlockAndIndex(237*128-1).getBlock().hasFreeSectors());
try { try {
assertEquals(false, fs.getBATBlockAndIndex(237*128).getBlock().hasFreeSectors()); assertEquals(false, fs1.getBATBlockAndIndex(237*128).getBlock().hasFreeSectors());
fail("Should only be 237 BATs"); fail("Should only be 237 BATs");
} catch(IndexOutOfBoundsException e) {} } catch(IndexOutOfBoundsException e) {}
// Check the counts now // Check the counts now
assertBATCount(fs, 237, 2); assertBATCount(fs1, 237, 2);
// Check the header // Check the header
header = writeOutAndReadHeader(fs); header = writeOutAndReadHeader(fs1);
// Now, write it out, and read it back in again fully // Now, write it out, and read it back in again fully
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs2 = writeOutAndReadBack(fs1);
fs1.close();
// Check that it is seen correctly // Check that it is seen correctly
assertBATCount(fs, 237, 2); assertBATCount(fs2, 237, 2);
assertEquals(false, fs.getBATBlockAndIndex(236*128-1).getBlock().hasFreeSectors()); assertEquals(false, fs2.getBATBlockAndIndex(236*128-1).getBlock().hasFreeSectors());
assertEquals(true, fs.getBATBlockAndIndex(237*128-1).getBlock().hasFreeSectors()); assertEquals(true, fs2.getBATBlockAndIndex(237*128-1).getBlock().hasFreeSectors());
try { try {
assertEquals(false, fs.getBATBlockAndIndex(237*128).getBlock().hasFreeSectors()); assertEquals(false, fs2.getBATBlockAndIndex(237*128).getBlock().hasFreeSectors());
fail("Should only be 237 BATs"); fail("Should only be 237 BATs");
} catch(IndexOutOfBoundsException e) {} } catch(IndexOutOfBoundsException e) {}
// All done // All done
fs.close(); fs2.close();
} }
/** /**
@ -590,7 +595,7 @@ public final class TestNPOIFSFileSystem {
* entries, and the details on the files in them * entries, and the details on the files in them
*/ */
@Test @Test
public void listEntries() throws Exception { public void listEntries() throws IOException {
for(NPOIFSFileSystem fs : get512and4kFileAndInput()) { for(NPOIFSFileSystem fs : get512and4kFileAndInput()) {
DirectoryEntry root = fs.getRoot(); DirectoryEntry root = fs.getRoot();
assertEquals(5, root.getEntryCount()); assertEquals(5, root.getEntryCount());
@ -680,9 +685,9 @@ public final class TestNPOIFSFileSystem {
DocumentSummaryInformation dinf = null; DocumentSummaryInformation dinf = null;
DirectoryEntry root = null, testDir = null; DirectoryEntry root = null, testDir = null;
for(NPOIFSFileSystem fs : get512and4kFileAndInput()) { for(NPOIFSFileSystem fs1 : get512and4kFileAndInput()) {
// Check we can find the entries we expect // Check we can find the entries we expect
root = fs.getRoot(); root = fs1.getRoot();
assertEquals(5, root.getEntryCount()); assertEquals(5, root.getEntryCount());
assertThat(root.getEntryNames(), hasItem("Thumbnail")); assertThat(root.getEntryNames(), hasItem("Thumbnail"));
assertThat(root.getEntryNames(), hasItem("Image")); assertThat(root.getEntryNames(), hasItem("Image"));
@ -692,10 +697,11 @@ public final class TestNPOIFSFileSystem {
// Write out, re-load // Write out, re-load
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs2 = writeOutAndReadBack(fs1);
fs1.close();
// Check they're still there // Check they're still there
root = fs.getRoot(); root = fs2.getRoot();
assertEquals(5, root.getEntryCount()); assertEquals(5, root.getEntryCount());
assertThat(root.getEntryNames(), hasItem("Thumbnail")); assertThat(root.getEntryNames(), hasItem("Thumbnail"));
assertThat(root.getEntryNames(), hasItem("Image")); assertThat(root.getEntryNames(), hasItem("Image"));
@ -723,9 +729,10 @@ public final class TestNPOIFSFileSystem {
// Write out, re-load // Write out, re-load
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs3 = writeOutAndReadBack(fs2);
fs2.close();
root = fs.getRoot(); root = fs3.getRoot();
testDir = (DirectoryEntry)root.getEntry("Testing 123"); testDir = (DirectoryEntry)root.getEntry("Testing 123");
assertEquals(6, root.getEntryCount()); assertEquals(6, root.getEntryCount());
assertThat(root.getEntryNames(), hasItem("Thumbnail")); assertThat(root.getEntryNames(), hasItem("Thumbnail"));
@ -749,9 +756,10 @@ public final class TestNPOIFSFileSystem {
// Write out and read once more, just to be sure // Write out and read once more, just to be sure
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs4 = writeOutAndReadBack(fs3);
fs3.close();
root = fs.getRoot(); root = fs4.getRoot();
testDir = (DirectoryEntry)root.getEntry("Testing 123"); testDir = (DirectoryEntry)root.getEntry("Testing 123");
assertEquals(6, root.getEntryCount()); assertEquals(6, root.getEntryCount());
assertThat(root.getEntryNames(), hasItem("Thumbnail")); assertThat(root.getEntryNames(), hasItem("Thumbnail"));
@ -782,10 +790,11 @@ public final class TestNPOIFSFileSystem {
// Write out, re-load // Write out, re-load
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs5 = writeOutAndReadBack(fs4);
fs4.close();
// Check it's all there // Check it's all there
root = fs.getRoot(); root = fs5.getRoot();
testDir = (DirectoryEntry)root.getEntry("Testing 123"); testDir = (DirectoryEntry)root.getEntry("Testing 123");
assertEquals(5, root.getEntryCount()); assertEquals(5, root.getEntryCount());
assertThat(root.getEntryNames(), hasItem("Thumbnail")); assertThat(root.getEntryNames(), hasItem("Thumbnail"));
@ -814,10 +823,11 @@ public final class TestNPOIFSFileSystem {
// Save // Save
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs6 = writeOutAndReadBack(fs5);
fs5.close();
// Check // Check
root = fs.getRoot(); root = fs6.getRoot();
testDir = (DirectoryEntry)root.getEntry("Testing 123"); testDir = (DirectoryEntry)root.getEntry("Testing 123");
assertEquals(5, root.getEntryCount()); assertEquals(5, root.getEntryCount());
@ -839,9 +849,10 @@ public final class TestNPOIFSFileSystem {
testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); testDir.createDocument("Mini2", new ByteArrayInputStream(mini2));
// Save, load, check // Save, load, check
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs7 = writeOutAndReadBack(fs6);
fs6.close();
root = fs.getRoot(); root = fs7.getRoot();
testDir = (DirectoryEntry)root.getEntry("Testing 123"); testDir = (DirectoryEntry)root.getEntry("Testing 123");
assertEquals(5, root.getEntryCount()); assertEquals(5, root.getEntryCount());
@ -871,9 +882,10 @@ public final class TestNPOIFSFileSystem {
// Save, load, check // Save, load, check
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs8 = writeOutAndReadBack(fs7);
fs7.close();
root = fs.getRoot(); root = fs8.getRoot();
testDir = (DirectoryEntry)root.getEntry("Testing 123"); testDir = (DirectoryEntry)root.getEntry("Testing 123");
assertEquals(5, root.getEntryCount()); assertEquals(5, root.getEntryCount());
@ -907,9 +919,10 @@ public final class TestNPOIFSFileSystem {
// Re-check // Re-check
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs9 = writeOutAndReadBack(fs8);
fs8.close();
root = fs.getRoot(); root = fs9.getRoot();
testDir = (DirectoryEntry)root.getEntry("Testing 123"); testDir = (DirectoryEntry)root.getEntry("Testing 123");
assertEquals(5, root.getEntryCount()); assertEquals(5, root.getEntryCount());
@ -932,7 +945,7 @@ public final class TestNPOIFSFileSystem {
// All done // All done
fs.close(); fs9.close();
} }
} }
@ -941,51 +954,52 @@ public final class TestNPOIFSFileSystem {
* Then, add some streams, write and read * Then, add some streams, write and read
*/ */
@Test @Test
@SuppressWarnings("resource") public void createWriteRead() throws IOException {
public void createWriteRead() throws Exception { NPOIFSFileSystem fs1 = new NPOIFSFileSystem();
NPOIFSFileSystem fs = new NPOIFSFileSystem();
DocumentEntry miniDoc; DocumentEntry miniDoc;
DocumentEntry normDoc; DocumentEntry normDoc;
// Initially has Properties + BAT but not SBAT // Initially has Properties + BAT but not SBAT
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0));
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(2)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2));
// Check that the SBAT is empty // Check that the SBAT is empty
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getRoot().getProperty().getStartBlock()); assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getRoot().getProperty().getStartBlock());
// Check that properties table was given block 0 // Check that properties table was given block 0
assertEquals(0, fs._get_property_table().getStartBlock()); assertEquals(0, fs1._get_property_table().getStartBlock());
// Write and read it // Write and read it
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs2 = writeOutAndReadBack(fs1);
fs1.close();
// No change, SBAT remains empty // No change, SBAT remains empty
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(0));
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(2)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(2));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(3)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(3));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getRoot().getProperty().getStartBlock()); assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getRoot().getProperty().getStartBlock());
assertEquals(0, fs._get_property_table().getStartBlock()); assertEquals(0, fs2._get_property_table().getStartBlock());
fs2.close();
// Check the same but with saving to a file // Check the same but with saving to a file
fs = new NPOIFSFileSystem(); NPOIFSFileSystem fs3 = new NPOIFSFileSystem();
fs = writeOutFileAndReadBack(fs); NPOIFSFileSystem fs4 = writeOutFileAndReadBack(fs3);
fs3.close();
// Same, no change, SBAT remains empty // Same, no change, SBAT remains empty
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(2)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(2));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(3)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(3));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getRoot().getProperty().getStartBlock()); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock());
assertEquals(0, fs._get_property_table().getStartBlock()); assertEquals(0, fs4._get_property_table().getStartBlock());
// Put everything within a new directory // Put everything within a new directory
DirectoryEntry testDir = fs.createDirectory("Test Directory"); DirectoryEntry testDir = fs4.createDirectory("Test Directory");
// Add a new Normal Stream (Normal Streams minimum 4096 bytes) // Add a new Normal Stream (Normal Streams minimum 4096 bytes)
byte[] main4096 = new byte[4096]; byte[] main4096 = new byte[4096];
@ -993,20 +1007,20 @@ public final class TestNPOIFSFileSystem {
main4096[4095] = -11; main4096[4095] = -11;
testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
assertEquals(3, fs.getNextBlock(2)); assertEquals(3, fs4.getNextBlock(2));
assertEquals(4, fs.getNextBlock(3)); assertEquals(4, fs4.getNextBlock(3));
assertEquals(5, fs.getNextBlock(4)); assertEquals(5, fs4.getNextBlock(4));
assertEquals(6, fs.getNextBlock(5)); assertEquals(6, fs4.getNextBlock(5));
assertEquals(7, fs.getNextBlock(6)); assertEquals(7, fs4.getNextBlock(6));
assertEquals(8, fs.getNextBlock(7)); assertEquals(8, fs4.getNextBlock(7));
assertEquals(9, fs.getNextBlock(8)); assertEquals(9, fs4.getNextBlock(8));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(9)); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(10)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(10));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(11)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(11));
// SBAT still unused // SBAT still unused
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getRoot().getProperty().getStartBlock()); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock());
// Add a bigger Normal Stream // Add a bigger Normal Stream
@ -1015,32 +1029,32 @@ public final class TestNPOIFSFileSystem {
main5124[5123] = -33; main5124[5123] = -33;
testDir.createDocument("Normal5124", new ByteArrayInputStream(main5124)); testDir.createDocument("Normal5124", new ByteArrayInputStream(main5124));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
assertEquals(3, fs.getNextBlock(2)); assertEquals(3, fs4.getNextBlock(2));
assertEquals(4, fs.getNextBlock(3)); assertEquals(4, fs4.getNextBlock(3));
assertEquals(5, fs.getNextBlock(4)); assertEquals(5, fs4.getNextBlock(4));
assertEquals(6, fs.getNextBlock(5)); assertEquals(6, fs4.getNextBlock(5));
assertEquals(7, fs.getNextBlock(6)); assertEquals(7, fs4.getNextBlock(6));
assertEquals(8, fs.getNextBlock(7)); assertEquals(8, fs4.getNextBlock(7));
assertEquals(9, fs.getNextBlock(8)); assertEquals(9, fs4.getNextBlock(8));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(9)); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9));
assertEquals(11, fs.getNextBlock(10)); assertEquals(11, fs4.getNextBlock(10));
assertEquals(12, fs.getNextBlock(11)); assertEquals(12, fs4.getNextBlock(11));
assertEquals(13, fs.getNextBlock(12)); assertEquals(13, fs4.getNextBlock(12));
assertEquals(14, fs.getNextBlock(13)); assertEquals(14, fs4.getNextBlock(13));
assertEquals(15, fs.getNextBlock(14)); assertEquals(15, fs4.getNextBlock(14));
assertEquals(16, fs.getNextBlock(15)); assertEquals(16, fs4.getNextBlock(15));
assertEquals(17, fs.getNextBlock(16)); assertEquals(17, fs4.getNextBlock(16));
assertEquals(18, fs.getNextBlock(17)); assertEquals(18, fs4.getNextBlock(17));
assertEquals(19, fs.getNextBlock(18)); assertEquals(19, fs4.getNextBlock(18));
assertEquals(20, fs.getNextBlock(19)); assertEquals(20, fs4.getNextBlock(19));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(20)); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(21)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(21));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(22)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(22));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getRoot().getProperty().getStartBlock()); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock());
// Now Add a mini stream // Now Add a mini stream
@ -1048,40 +1062,41 @@ public final class TestNPOIFSFileSystem {
testDir.createDocument("Mini", new ByteArrayInputStream(mini)); testDir.createDocument("Mini", new ByteArrayInputStream(mini));
// Mini stream will get one block for fat + one block for data // Mini stream will get one block for fat + one block for data
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
assertEquals(3, fs.getNextBlock(2)); assertEquals(3, fs4.getNextBlock(2));
assertEquals(4, fs.getNextBlock(3)); assertEquals(4, fs4.getNextBlock(3));
assertEquals(5, fs.getNextBlock(4)); assertEquals(5, fs4.getNextBlock(4));
assertEquals(6, fs.getNextBlock(5)); assertEquals(6, fs4.getNextBlock(5));
assertEquals(7, fs.getNextBlock(6)); assertEquals(7, fs4.getNextBlock(6));
assertEquals(8, fs.getNextBlock(7)); assertEquals(8, fs4.getNextBlock(7));
assertEquals(9, fs.getNextBlock(8)); assertEquals(9, fs4.getNextBlock(8));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(9)); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9));
assertEquals(11, fs.getNextBlock(10)); assertEquals(11, fs4.getNextBlock(10));
assertEquals(12, fs.getNextBlock(11)); assertEquals(12, fs4.getNextBlock(11));
assertEquals(13, fs.getNextBlock(12)); assertEquals(13, fs4.getNextBlock(12));
assertEquals(14, fs.getNextBlock(13)); assertEquals(14, fs4.getNextBlock(13));
assertEquals(15, fs.getNextBlock(14)); assertEquals(15, fs4.getNextBlock(14));
assertEquals(16, fs.getNextBlock(15)); assertEquals(16, fs4.getNextBlock(15));
assertEquals(17, fs.getNextBlock(16)); assertEquals(17, fs4.getNextBlock(16));
assertEquals(18, fs.getNextBlock(17)); assertEquals(18, fs4.getNextBlock(17));
assertEquals(19, fs.getNextBlock(18)); assertEquals(19, fs4.getNextBlock(18));
assertEquals(20, fs.getNextBlock(19)); assertEquals(20, fs4.getNextBlock(19));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(20)); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(21)); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(21));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(22)); assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(22));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(23)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(23));
// Check the mini stream location was set // Check the mini stream location was set
// (21 is mini fat, 22 is first mini stream block) // (21 is mini fat, 22 is first mini stream block)
assertEquals(22, fs.getRoot().getProperty().getStartBlock()); assertEquals(22, fs4.getRoot().getProperty().getStartBlock());
// Write and read back // Write and read back
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs5 = writeOutAndReadBack(fs4);
HeaderBlock header = writeOutAndReadHeader(fs); fs4.close();
HeaderBlock header = writeOutAndReadHeader(fs5);
// Check the header has the right points in it // Check the header has the right points in it
assertEquals(1, header.getBATCount()); assertEquals(1, header.getBATCount());
@ -1089,44 +1104,44 @@ public final class TestNPOIFSFileSystem {
assertEquals(0, header.getPropertyStart()); assertEquals(0, header.getPropertyStart());
assertEquals(1, header.getSBATCount()); assertEquals(1, header.getSBATCount());
assertEquals(21, header.getSBATStart()); assertEquals(21, header.getSBATStart());
assertEquals(22, fs._get_property_table().getRoot().getStartBlock()); assertEquals(22, fs5._get_property_table().getRoot().getStartBlock());
// Block use should be almost the same, except the properties // Block use should be almost the same, except the properties
// stream will have grown out to cover 2 blocks // stream will have grown out to cover 2 blocks
// Check the block use is all unchanged // Check the block use is all unchanged
assertEquals(23, fs.getNextBlock(0)); // Properties now extends over 2 blocks assertEquals(23, fs5.getNextBlock(0)); // Properties now extends over 2 blocks
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs5.getNextBlock(1));
assertEquals(3, fs.getNextBlock(2)); assertEquals(3, fs5.getNextBlock(2));
assertEquals(4, fs.getNextBlock(3)); assertEquals(4, fs5.getNextBlock(3));
assertEquals(5, fs.getNextBlock(4)); assertEquals(5, fs5.getNextBlock(4));
assertEquals(6, fs.getNextBlock(5)); assertEquals(6, fs5.getNextBlock(5));
assertEquals(7, fs.getNextBlock(6)); assertEquals(7, fs5.getNextBlock(6));
assertEquals(8, fs.getNextBlock(7)); assertEquals(8, fs5.getNextBlock(7));
assertEquals(9, fs.getNextBlock(8)); assertEquals(9, fs5.getNextBlock(8));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(9)); // End of normal4096 assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(9)); // End of normal4096
assertEquals(11, fs.getNextBlock(10)); assertEquals(11, fs5.getNextBlock(10));
assertEquals(12, fs.getNextBlock(11)); assertEquals(12, fs5.getNextBlock(11));
assertEquals(13, fs.getNextBlock(12)); assertEquals(13, fs5.getNextBlock(12));
assertEquals(14, fs.getNextBlock(13)); assertEquals(14, fs5.getNextBlock(13));
assertEquals(15, fs.getNextBlock(14)); assertEquals(15, fs5.getNextBlock(14));
assertEquals(16, fs.getNextBlock(15)); assertEquals(16, fs5.getNextBlock(15));
assertEquals(17, fs.getNextBlock(16)); assertEquals(17, fs5.getNextBlock(16));
assertEquals(18, fs.getNextBlock(17)); assertEquals(18, fs5.getNextBlock(17));
assertEquals(19, fs.getNextBlock(18)); assertEquals(19, fs5.getNextBlock(18));
assertEquals(20, fs.getNextBlock(19)); assertEquals(20, fs5.getNextBlock(19));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(20)); // End of normal5124 assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(20)); // End of normal5124
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(21)); // Mini Stream FAT assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(21)); // Mini Stream FAT
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(22)); // Mini Stream data assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(22)); // Mini Stream data
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(23)); // Properties #2 assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(23)); // Properties #2
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(24)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs5.getNextBlock(24));
// Check some data // Check some data
assertEquals(1, fs.getRoot().getEntryCount()); assertEquals(1, fs5.getRoot().getEntryCount());
testDir = (DirectoryEntry)fs.getRoot().getEntry("Test Directory"); testDir = (DirectoryEntry)fs5.getRoot().getEntry("Test Directory");
assertEquals(3, testDir.getEntryCount()); assertEquals(3, testDir.getEntryCount());
miniDoc = (DocumentEntry)testDir.getEntry("Mini"); miniDoc = (DocumentEntry)testDir.getEntry("Mini");
@ -1145,55 +1160,56 @@ public final class TestNPOIFSFileSystem {
// Check - will have un-used sectors now // Check - will have un-used sectors now
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs6 = writeOutAndReadBack(fs5);
fs5.close();
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); // Props back in 1 block assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(0)); // Props back in 1 block
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs6.getNextBlock(1));
assertEquals(3, fs.getNextBlock(2)); assertEquals(3, fs6.getNextBlock(2));
assertEquals(4, fs.getNextBlock(3)); assertEquals(4, fs6.getNextBlock(3));
assertEquals(5, fs.getNextBlock(4)); assertEquals(5, fs6.getNextBlock(4));
assertEquals(6, fs.getNextBlock(5)); assertEquals(6, fs6.getNextBlock(5));
assertEquals(7, fs.getNextBlock(6)); assertEquals(7, fs6.getNextBlock(6));
assertEquals(8, fs.getNextBlock(7)); assertEquals(8, fs6.getNextBlock(7));
assertEquals(9, fs.getNextBlock(8)); assertEquals(9, fs6.getNextBlock(8));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(9)); // End of normal4096 assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(9)); // End of normal4096
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(10)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(10));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(11)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(11));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(12)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(12));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(13)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(13));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(14)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(14));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(15)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(15));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(16)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(16));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(17)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(17));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(18)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(18));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(19)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(19));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(20)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(20));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(21)); // Mini Stream FAT assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(21)); // Mini Stream FAT
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(22)); // Mini Stream data assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(22)); // Mini Stream data
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(23)); // Properties gone assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(23)); // Properties gone
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(24)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(24));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(25)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(25));
// All done // All done
fs.close(); fs6.close();
} }
@Test @Test
public void addBeforeWrite() throws Exception { public void addBeforeWrite() throws IOException {
NPOIFSFileSystem fs = new NPOIFSFileSystem(); NPOIFSFileSystem fs1 = new NPOIFSFileSystem();
DocumentEntry miniDoc; DocumentEntry miniDoc;
DocumentEntry normDoc; DocumentEntry normDoc;
HeaderBlock hdr; HeaderBlock hdr;
// Initially has Properties + BAT but nothing else // Initially has Properties + BAT but nothing else
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0));
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(2)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2));
hdr = writeOutAndReadHeader(fs); hdr = writeOutAndReadHeader(fs1);
// No mini stream, and no xbats // No mini stream, and no xbats
// Will have fat then properties stream // Will have fat then properties stream
assertEquals(1, hdr.getBATCount()); assertEquals(1, hdr.getBATCount());
@ -1201,14 +1217,14 @@ public final class TestNPOIFSFileSystem {
assertEquals(0, hdr.getPropertyStart()); assertEquals(0, hdr.getPropertyStart());
assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getSBATStart()); assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getSBATStart());
assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex()); assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex());
assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE*3, fs.size()); assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE*3, fs1.size());
fs1.close();
// Get a clean filesystem to start with // Get a clean filesystem to start with
fs = new NPOIFSFileSystem(); fs1 = new NPOIFSFileSystem();
// Put our test files in a non-standard place // Put our test files in a non-standard place
DirectoryEntry parentDir = fs.createDirectory("Parent Directory"); DirectoryEntry parentDir = fs1.createDirectory("Parent Directory");
DirectoryEntry testDir = parentDir.createDirectory("Test Directory"); DirectoryEntry testDir = parentDir.createDirectory("Test Directory");
@ -1224,20 +1240,20 @@ public final class TestNPOIFSFileSystem {
// Check the mini stream was added, then the main stream // Check the mini stream was added, then the main stream
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0));
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); // Mini Fat assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(2)); // Mini Fat
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(3)); // Mini Stream assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(3)); // Mini Stream
assertEquals(5, fs.getNextBlock(4)); // Main Stream assertEquals(5, fs1.getNextBlock(4)); // Main Stream
assertEquals(6, fs.getNextBlock(5)); assertEquals(6, fs1.getNextBlock(5));
assertEquals(7, fs.getNextBlock(6)); assertEquals(7, fs1.getNextBlock(6));
assertEquals(8, fs.getNextBlock(7)); assertEquals(8, fs1.getNextBlock(7));
assertEquals(9, fs.getNextBlock(8)); assertEquals(9, fs1.getNextBlock(8));
assertEquals(10, fs.getNextBlock(9)); assertEquals(10, fs1.getNextBlock(9));
assertEquals(11, fs.getNextBlock(10)); assertEquals(11, fs1.getNextBlock(10));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(11)); assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(11));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(12)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(12));
assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE*13, fs.size()); assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE*13, fs1.size());
// Check that we can read the right data pre-write // Check that we can read the right data pre-write
@ -1249,8 +1265,9 @@ public final class TestNPOIFSFileSystem {
// Write, read, check // Write, read, check
hdr = writeOutAndReadHeader(fs); hdr = writeOutAndReadHeader(fs1);
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs2 = writeOutAndReadBack(fs1);
fs1.close();
// Check the header details - will have the sbat near the start, // Check the header details - will have the sbat near the start,
// then the properties at the end // then the properties at the end
@ -1262,25 +1279,25 @@ public final class TestNPOIFSFileSystem {
// Check the block allocation is unchanged, other than // Check the block allocation is unchanged, other than
// the properties stream going in at the end // the properties stream going in at the end
assertEquals(12, fs.getNextBlock(0)); // Properties assertEquals(12, fs2.getNextBlock(0)); // Properties
assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(2));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(3)); assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(3));
assertEquals(5, fs.getNextBlock(4)); assertEquals(5, fs2.getNextBlock(4));
assertEquals(6, fs.getNextBlock(5)); assertEquals(6, fs2.getNextBlock(5));
assertEquals(7, fs.getNextBlock(6)); assertEquals(7, fs2.getNextBlock(6));
assertEquals(8, fs.getNextBlock(7)); assertEquals(8, fs2.getNextBlock(7));
assertEquals(9, fs.getNextBlock(8)); assertEquals(9, fs2.getNextBlock(8));
assertEquals(10, fs.getNextBlock(9)); assertEquals(10, fs2.getNextBlock(9));
assertEquals(11, fs.getNextBlock(10)); assertEquals(11, fs2.getNextBlock(10));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(11)); assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(11));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(12)); assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(12));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(13)); assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(13));
assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE*14, fs.size()); assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE*14, fs2.size());
// Check the data // Check the data
DirectoryEntry fsRoot = fs.getRoot(); DirectoryEntry fsRoot = fs2.getRoot();
assertEquals(1, fsRoot.getEntryCount()); assertEquals(1, fsRoot.getEntryCount());
parentDir = (DirectoryEntry)fsRoot.getEntry("Parent Directory"); parentDir = (DirectoryEntry)fsRoot.getEntry("Parent Directory");
@ -1308,9 +1325,10 @@ public final class TestNPOIFSFileSystem {
// Recheck the data in all 4 streams // Recheck the data in all 4 streams
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs3 = writeOutAndReadBack(fs2);
fs2.close();
fsRoot = fs.getRoot(); fsRoot = fs3.getRoot();
assertEquals(1, fsRoot.getEntryCount()); assertEquals(1, fsRoot.getEntryCount());
parentDir = (DirectoryEntry)fsRoot.getEntry("Parent Directory"); parentDir = (DirectoryEntry)fsRoot.getEntry("Parent Directory");
@ -1329,11 +1347,11 @@ public final class TestNPOIFSFileSystem {
assertContentsMatches(main4106, normDoc); assertContentsMatches(main4106, normDoc);
// All done // All done
fs.close(); fs3.close();
} }
@Test @Test
public void readZeroLengthEntries() throws Exception { public void readZeroLengthEntries() throws IOException {
NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.getFile("only-zero-byte-streams.ole2")); NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.getFile("only-zero-byte-streams.ole2"));
DirectoryNode testDir = fs.getRoot(); DirectoryNode testDir = fs.getRoot();
assertEquals(3, testDir.getEntryCount()); assertEquals(3, testDir.getEntryCount());
@ -1364,9 +1382,9 @@ public final class TestNPOIFSFileSystem {
} }
@Test @Test
public void writeZeroLengthEntries() throws Exception { public void writeZeroLengthEntries() throws IOException {
NPOIFSFileSystem fs = new NPOIFSFileSystem(); NPOIFSFileSystem fs1 = new NPOIFSFileSystem();
DirectoryNode testDir = fs.getRoot(); DirectoryNode testDir = fs1.getRoot();
DocumentEntry miniDoc; DocumentEntry miniDoc;
DocumentEntry normDoc; DocumentEntry normDoc;
DocumentEntry emptyDoc; DocumentEntry emptyDoc;
@ -1405,7 +1423,7 @@ public final class TestNPOIFSFileSystem {
// Look at the properties entry, and check the empty ones // Look at the properties entry, and check the empty ones
// have zero size and no start block // have zero size and no start block
NPropertyTable props = fs._get_property_table(); NPropertyTable props = fs1._get_property_table();
Iterator<Property> propsIt = props.getRoot().getChildren(); Iterator<Property> propsIt = props.getRoot().getChildren();
Property prop = propsIt.next(); Property prop = propsIt.next();
@ -1435,8 +1453,9 @@ public final class TestNPOIFSFileSystem {
// Save and re-check // Save and re-check
fs = writeOutAndReadBack(fs); NPOIFSFileSystem fs2 = writeOutAndReadBack(fs1);
testDir = fs.getRoot(); fs1.close();
testDir = fs2.getRoot();
miniDoc = (DocumentEntry)testDir.getEntry("Mini2"); miniDoc = (DocumentEntry)testDir.getEntry("Mini2");
assertContentsMatches(mini2, miniDoc); assertContentsMatches(mini2, miniDoc);
@ -1458,7 +1477,7 @@ public final class TestNPOIFSFileSystem {
assertEquals(64, testDir.getProperty().getSize()); assertEquals(64, testDir.getProperty().getSize());
// All done // All done
fs.close(); fs2.close();
} }
/** /**
@ -1466,7 +1485,7 @@ public final class TestNPOIFSFileSystem {
* write it out, read it with POIFS, and see the original data * write it out, read it with POIFS, and see the original data
*/ */
@Test @Test
public void NPOIFSReadCopyWritePOIFSRead() throws Exception { public void NPOIFSReadCopyWritePOIFSRead() throws IOException {
File testFile = POIDataSamples.getSpreadSheetInstance().getFile("Simple.xls"); File testFile = POIDataSamples.getSpreadSheetInstance().getFile("Simple.xls");
NPOIFSFileSystem src = new NPOIFSFileSystem(testFile); NPOIFSFileSystem src = new NPOIFSFileSystem(testFile);
byte wbDataExp[] = IOUtils.toByteArray(src.createDocumentInputStream("Workbook")); byte wbDataExp[] = IOUtils.toByteArray(src.createDocumentInputStream("Workbook"));
@ -1483,6 +1502,7 @@ public final class TestNPOIFSFileSystem {
byte wbDataAct[] = IOUtils.toByteArray(pfs.createDocumentInputStream("Workbook")); byte wbDataAct[] = IOUtils.toByteArray(pfs.createDocumentInputStream("Workbook"));
assertThat(wbDataExp, equalTo(wbDataAct)); assertThat(wbDataExp, equalTo(wbDataAct));
pfs.close();
} }
/** /**
@ -1490,7 +1510,7 @@ public final class TestNPOIFSFileSystem {
* contents * contents
*/ */
@Test @Test
public void RecursiveDelete() throws Exception { public void RecursiveDelete() throws IOException {
File testFile = POIDataSamples.getSpreadSheetInstance().getFile("SimpleMacro.xls"); File testFile = POIDataSamples.getSpreadSheetInstance().getFile("SimpleMacro.xls");
NPOIFSFileSystem src = new NPOIFSFileSystem(testFile); NPOIFSFileSystem src = new NPOIFSFileSystem(testFile);