]> source.dussan.org Git - poi.git/commitdiff
Close more file-handles in tests, convert junit3 tests
authorDominik Stadler <centic@apache.org>
Sun, 31 Mar 2019 19:29:34 +0000 (19:29 +0000)
committerDominik Stadler <centic@apache.org>
Sun, 31 Mar 2019 19:29:34 +0000 (19:29 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1856688 13f79535-47bb-0310-9956-ffa450edef68

src/java/org/apache/poi/hssf/usermodel/HSSFFormulaEvaluator.java
src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java
src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java
src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java
src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java
src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java

index e7d848202e1f702bbb6fc85a63d3bf06cf2472e8..f8ab24a0e840e66125dca4b8355cf73b03c64871 100644 (file)
@@ -194,7 +194,7 @@ public class HSSFFormulaEvaluator extends BaseFormulaEvaluator {
 
     /**
      * Returns a CellValue wrapper around the supplied ValueEval instance.
-     * @param cell
+     * @param cell The cell with the formula
      */
     protected CellValue evaluateFormulaCellValue(Cell cell) {
         ValueEval eval = _bookEvaluator.evaluate(new HSSFEvaluationCell((HSSFCell)cell));
index 0596a941f08692fdcc70d3422d3455581c3fffac..bd057008f2dcf3010df61451d758d9ad7185ac39 100644 (file)
 
 package org.apache.poi.xwpf.model;
 
-import java.io.IOException;
-
-import junit.framework.TestCase;
-
 import org.apache.poi.xwpf.XWPFTestDataSamples;
 import org.apache.poi.xwpf.usermodel.XWPFDocument;
 import org.apache.poi.xwpf.usermodel.XWPFFooter;
 import org.apache.poi.xwpf.usermodel.XWPFHeader;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.IOException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 
 /**
  * Tests for XWPF Header Footer Stuff
  */
-public class TestXWPFHeaderFooterPolicy extends TestCase {
+public class TestXWPFHeaderFooterPolicy {
     private XWPFDocument noHeader;
     private XWPFDocument header;
     private XWPFDocument headerFooter;
@@ -37,8 +42,8 @@ public class TestXWPFHeaderFooterPolicy extends TestCase {
     private XWPFDocument oddEven;
     private XWPFDocument diffFirst;
 
-    @Override
-    protected void setUp() throws IOException {
+    @Before
+    public void setUp() throws IOException {
         noHeader = XWPFTestDataSamples.openSampleDocument("NoHeadFoot.docx");
         header = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx");
         headerFooter = XWPFTestDataSamples.openSampleDocument("SimpleHeadThreeColFoot.docx");
@@ -47,6 +52,17 @@ public class TestXWPFHeaderFooterPolicy extends TestCase {
         diffFirst = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx");
     }
 
+    @After
+    public void tearDown() throws IOException {
+        noHeader.close();
+        header.close();
+        headerFooter.close();
+        footer.close();
+        oddEven.close();
+        diffFirst.close();
+    }
+
+    @Test
     public void testPolicy() {
         XWPFHeaderFooterPolicy policy;
 
@@ -127,36 +143,39 @@ public class TestXWPFHeaderFooterPolicy extends TestCase {
         assertEquals(policy.getDefaultFooter(), policy.getFooter(2));
         assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
     }
-    
-    @SuppressWarnings("resource")
+
+    @Test
     public void testCreate() throws Exception {
-        XWPFDocument doc = new XWPFDocument();
-        assertEquals(null, doc.getHeaderFooterPolicy());
-        assertEquals(0, doc.getHeaderList().size());
-        assertEquals(0, doc.getFooterList().size());
-        
-        XWPFHeaderFooterPolicy policy = doc.createHeaderFooterPolicy();
-        assertNotNull(doc.getHeaderFooterPolicy());
-        assertEquals(0, doc.getHeaderList().size());
-        assertEquals(0, doc.getFooterList().size());
-        
-        // Create a header and a footer
-        XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
-        XWPFFooter footer = policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
-        header.createParagraph().createRun().setText("Header Hello");
-        footer.createParagraph().createRun().setText("Footer Bye");
-        
-        
-        // Save, re-load, and check
-        doc = XWPFTestDataSamples.writeOutAndReadBack(doc);
-        assertNotNull(doc.getHeaderFooterPolicy());
-        assertEquals(1, doc.getHeaderList().size());
-        assertEquals(1, doc.getFooterList().size());
-        
-        assertEquals("Header Hello\n", doc.getHeaderList().get(0).getText());
-        assertEquals("Footer Bye\n", doc.getFooterList().get(0).getText());
+        try (XWPFDocument doc = new XWPFDocument()) {
+            assertNull(doc.getHeaderFooterPolicy());
+            assertEquals(0, doc.getHeaderList().size());
+            assertEquals(0, doc.getFooterList().size());
+
+            XWPFHeaderFooterPolicy policy = doc.createHeaderFooterPolicy();
+            assertNotNull(doc.getHeaderFooterPolicy());
+            assertEquals(0, doc.getHeaderList().size());
+            assertEquals(0, doc.getFooterList().size());
+
+            // Create a header and a footer
+            XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
+            XWPFFooter footer = policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
+            header.createParagraph().createRun().setText("Header Hello");
+            footer.createParagraph().createRun().setText("Footer Bye");
+
+
+            // Save, re-load, and check
+            try (XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc)) {
+                assertNotNull(docBack.getHeaderFooterPolicy());
+                assertEquals(1, docBack.getHeaderList().size());
+                assertEquals(1, docBack.getFooterList().size());
+
+                assertEquals("Header Hello\n", docBack.getHeaderList().get(0).getText());
+                assertEquals("Footer Bye\n", docBack.getFooterList().get(0).getText());
+            }
+        }
     }
 
+    @Test
     public void testContents() {
         XWPFHeaderFooterPolicy policy;
 
index 47ec7652454ef5f95cb5b8634410120fbee8ef3f..b43b9e69148150f47a7d340fc0d8655dcea465e0 100644 (file)
@@ -28,41 +28,44 @@ import org.junit.Test;
 public class TestChangeTracking {
     @Test
     public void detection() throws Exception {
-        XWPFDocument documentWithoutChangeTracking = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_off.docx");
-        assertFalse(documentWithoutChangeTracking.isTrackRevisions());
+        try (XWPFDocument documentWithoutChangeTracking = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_off.docx")) {
+            assertFalse(documentWithoutChangeTracking.isTrackRevisions());
 
-        XWPFDocument documentWithChangeTracking = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_on.docx");
-        assertTrue(documentWithChangeTracking.isTrackRevisions());
+            try (XWPFDocument documentWithChangeTracking = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_on.docx")) {
+                assertTrue(documentWithChangeTracking.isTrackRevisions());
+            }
+        }
     }
 
     @Test
     public void activateChangeTracking() throws Exception {
-        XWPFDocument document = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_off.docx");
-        assertFalse(document.isTrackRevisions());
+        try (XWPFDocument document = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_off.docx")) {
+            assertFalse(document.isTrackRevisions());
 
-        document.setTrackRevisions(true);
+            document.setTrackRevisions(true);
 
-        assertTrue(document.isTrackRevisions());
+            assertTrue(document.isTrackRevisions());
+        }
     }
 
     @Test
-    @SuppressWarnings("resource")
     public void integration() throws Exception {
-        XWPFDocument doc = new XWPFDocument();
+        try (XWPFDocument doc = new XWPFDocument()) {
 
-        XWPFParagraph p1 = doc.createParagraph();
+            XWPFParagraph p1 = doc.createParagraph();
 
-        XWPFRun r1 = p1.createRun();
-        r1.setText("Lorem ipsum dolor sit amet.");
-        doc.setTrackRevisions(true);
+            XWPFRun r1 = p1.createRun();
+            r1.setText("Lorem ipsum dolor sit amet.");
+            doc.setTrackRevisions(true);
 
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        doc.write(out);
+            ByteArrayOutputStream out = new ByteArrayOutputStream();
+            doc.write(out);
 
-        ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toByteArray());
-        XWPFDocument document = new XWPFDocument(inputStream);
-        inputStream.close();
+            ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toByteArray());
+            XWPFDocument document = new XWPFDocument(inputStream);
+            inputStream.close();
 
-        assertTrue(document.isTrackRevisions());
+            assertTrue(document.isTrackRevisions());
+        }
     }
 }
index e367f04ae4fe3c918c137339f6a597571e8fdd80..be2258bd56452a10ead073076463e93ce977237a 100644 (file)
@@ -56,575 +56,560 @@ public final class TestXWPFParagraph {
 
     /**
      * Check that we get the right paragraph from the header
-     *
-     * @throws IOException
      */
     @Test
     public void testHeaderParagraph() throws IOException {
-        XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx");
+        try (XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx")) {
 
-        XWPFHeader hdr = xml.getHeaderFooterPolicy().getDefaultHeader();
-        assertNotNull(hdr);
+            XWPFHeader hdr = xml.getHeaderFooterPolicy().getDefaultHeader();
+            assertNotNull(hdr);
 
-        List<XWPFParagraph> ps = hdr.getParagraphs();
-        assertEquals(1, ps.size());
-        XWPFParagraph p = ps.get(0);
+            List<XWPFParagraph> ps = hdr.getParagraphs();
+            assertEquals(1, ps.size());
+            XWPFParagraph p = ps.get(0);
 
-        assertEquals(5, p.getCTP().sizeOfRArray());
-        assertEquals("First header column!\tMid header\tRight header!", p.getText());
-        
-        xml.close();
+            assertEquals(5, p.getCTP().sizeOfRArray());
+            assertEquals("First header column!\tMid header\tRight header!", p.getText());
+        }
     }
 
     /**
      * Check that we get the right paragraphs from the document
-     *
-     * @throws IOException
      */
     @Test
     public void testDocumentParagraph() throws IOException {
-        XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx");
-        List<XWPFParagraph> ps = xml.getParagraphs();
-        assertEquals(10, ps.size());
+        try (XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx")) {
+            List<XWPFParagraph> ps = xml.getParagraphs();
+            assertEquals(10, ps.size());
 
-        assertFalse(ps.get(0).isEmpty());
-        assertEquals(
-                "This is a sample word document. It has two pages. It has a three column heading, but no footer.",
-                ps.get(0).getText());
+            assertFalse(ps.get(0).isEmpty());
+            assertEquals(
+                    "This is a sample word document. It has two pages. It has a three column heading, but no footer.",
+                    ps.get(0).getText());
 
-        assertTrue(ps.get(1).isEmpty());
-        assertEquals("", ps.get(1).getText());
+            assertTrue(ps.get(1).isEmpty());
+            assertEquals("", ps.get(1).getText());
 
-        assertFalse(ps.get(2).isEmpty());
-        assertEquals("HEADING TEXT", ps.get(2).getText());
+            assertFalse(ps.get(2).isEmpty());
+            assertEquals("HEADING TEXT", ps.get(2).getText());
 
-        assertTrue(ps.get(3).isEmpty());
-        assertEquals("", ps.get(3).getText());
+            assertTrue(ps.get(3).isEmpty());
+            assertEquals("", ps.get(3).getText());
 
-        assertFalse(ps.get(4).isEmpty());
-        assertEquals("More on page one", ps.get(4).getText());
-        
-        xml.close();
+            assertFalse(ps.get(4).isEmpty());
+            assertEquals("More on page one", ps.get(4).getText());
+        }
     }
 
     @Test
     public void testSetGetBorderTop() throws IOException {
         //new clean instance of paragraph
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
 
-        assertEquals(STBorder.NONE.intValue(), p.getBorderTop().getValue());
+            assertEquals(STBorder.NONE.intValue(), p.getBorderTop().getValue());
 
-        CTP ctp = p.getCTP();
-        CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
+            CTP ctp = p.getCTP();
+            CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
 
-        //bordi
-        CTPBdr bdr = ppr.addNewPBdr();
-        CTBorder borderTop = bdr.addNewTop();
-        borderTop.setVal(STBorder.DOUBLE);
-        bdr.setTop(borderTop);
+            CTPBdr bdr = ppr.addNewPBdr();
+            CTBorder borderTop = bdr.addNewTop();
+            borderTop.setVal(STBorder.DOUBLE);
+            bdr.setTop(borderTop);
 
-        assertEquals(Borders.DOUBLE, p.getBorderTop());
-        p.setBorderTop(Borders.SINGLE);
-        assertEquals(STBorder.SINGLE, borderTop.getVal());
-        
-        doc.close();
+            assertEquals(Borders.DOUBLE, p.getBorderTop());
+            p.setBorderTop(Borders.SINGLE);
+            assertEquals(STBorder.SINGLE, borderTop.getVal());
+        }
     }
 
     @Test
     public void testSetGetAlignment() throws IOException {
         //new clean instance of paragraph
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
 
-        assertEquals(STJc.LEFT.intValue(), p.getAlignment().getValue());
+            assertEquals(STJc.LEFT.intValue(), p.getAlignment().getValue());
 
-        CTP ctp = p.getCTP();
-        CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
+            CTP ctp = p.getCTP();
+            CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
 
-        CTJc align = ppr.addNewJc();
-        align.setVal(STJc.CENTER);
-        assertEquals(ParagraphAlignment.CENTER, p.getAlignment());
+            CTJc align = ppr.addNewJc();
+            align.setVal(STJc.CENTER);
+            assertEquals(ParagraphAlignment.CENTER, p.getAlignment());
 
-        p.setAlignment(ParagraphAlignment.BOTH);
-        assertEquals(STJc.BOTH, ppr.getJc().getVal());
-        
-        doc.close();
+            p.setAlignment(ParagraphAlignment.BOTH);
+            assertEquals(STJc.BOTH, ppr.getJc().getVal());
+        }
     }
 
     @Test
     public void testSetGetSpacing() throws IOException {
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
-
-        CTP ctp = p.getCTP();
-        CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
-
-        assertEquals(-1, p.getSpacingBefore());
-        assertEquals(-1, p.getSpacingAfter());
-        assertEquals(-1, p.getSpacingBetween(), 0.1);
-        assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule());
-
-        CTSpacing spacing = ppr.addNewSpacing();
-        spacing.setAfter(new BigInteger("10"));
-        assertEquals(10, p.getSpacingAfter());
-        spacing.setBefore(new BigInteger("10"));
-        assertEquals(10, p.getSpacingBefore());
-
-        p.setSpacingAfter(100);
-        assertEquals(100, spacing.getAfter().intValue());
-        p.setSpacingBefore(100);
-        assertEquals(100, spacing.getBefore().intValue());
-        
-        p.setSpacingBetween(.25, LineSpacingRule.EXACT);
-        assertEquals(.25, p.getSpacingBetween(), 0.01);
-        assertEquals(LineSpacingRule.EXACT, p.getSpacingLineRule());
-        p.setSpacingBetween(1.25, LineSpacingRule.AUTO);
-        assertEquals(1.25, p.getSpacingBetween(), 0.01);
-        assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule());
-        p.setSpacingBetween(.5, LineSpacingRule.AT_LEAST);
-        assertEquals(.5, p.getSpacingBetween(), 0.01);
-        assertEquals(LineSpacingRule.AT_LEAST, p.getSpacingLineRule());
-        p.setSpacingBetween(1.15);
-        assertEquals(1.15, p.getSpacingBetween(), 0.01);
-        assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule());
-        
-        doc.close();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
+
+            CTP ctp = p.getCTP();
+            CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
+
+            assertEquals(-1, p.getSpacingBefore());
+            assertEquals(-1, p.getSpacingAfter());
+            assertEquals(-1, p.getSpacingBetween(), 0.1);
+            assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule());
+
+            CTSpacing spacing = ppr.addNewSpacing();
+            spacing.setAfter(new BigInteger("10"));
+            assertEquals(10, p.getSpacingAfter());
+            spacing.setBefore(new BigInteger("10"));
+            assertEquals(10, p.getSpacingBefore());
+
+            p.setSpacingAfter(100);
+            assertEquals(100, spacing.getAfter().intValue());
+            p.setSpacingBefore(100);
+            assertEquals(100, spacing.getBefore().intValue());
+
+            p.setSpacingBetween(.25, LineSpacingRule.EXACT);
+            assertEquals(.25, p.getSpacingBetween(), 0.01);
+            assertEquals(LineSpacingRule.EXACT, p.getSpacingLineRule());
+            p.setSpacingBetween(1.25, LineSpacingRule.AUTO);
+            assertEquals(1.25, p.getSpacingBetween(), 0.01);
+            assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule());
+            p.setSpacingBetween(.5, LineSpacingRule.AT_LEAST);
+            assertEquals(.5, p.getSpacingBetween(), 0.01);
+            assertEquals(LineSpacingRule.AT_LEAST, p.getSpacingLineRule());
+            p.setSpacingBetween(1.15);
+            assertEquals(1.15, p.getSpacingBetween(), 0.01);
+            assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule());
+        }
     }
 
     @Test
     public void testSetGetSpacingLineRule() throws IOException {
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
 
-        CTP ctp = p.getCTP();
-        CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
+            CTP ctp = p.getCTP();
+            CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
 
-        assertEquals(STLineSpacingRule.INT_AUTO, p.getSpacingLineRule().getValue());
+            assertEquals(STLineSpacingRule.INT_AUTO, p.getSpacingLineRule().getValue());
 
-        CTSpacing spacing = ppr.addNewSpacing();
-        spacing.setLineRule(STLineSpacingRule.AT_LEAST);
-        assertEquals(LineSpacingRule.AT_LEAST, p.getSpacingLineRule());
+            CTSpacing spacing = ppr.addNewSpacing();
+            spacing.setLineRule(STLineSpacingRule.AT_LEAST);
+            assertEquals(LineSpacingRule.AT_LEAST, p.getSpacingLineRule());
 
-        p.setSpacingAfter(100);
-        assertEquals(100, spacing.getAfter().intValue());
-        
-        doc.close();
+            p.setSpacingAfter(100);
+            assertEquals(100, spacing.getAfter().intValue());
+        }
     }
 
     @Test
     public void testSetGetIndentation() throws IOException {
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
 
-        assertEquals(-1, p.getIndentationLeft());
+            assertEquals(-1, p.getIndentationLeft());
 
-        CTP ctp = p.getCTP();
-        CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
+            CTP ctp = p.getCTP();
+            CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
 
-        assertEquals(-1, p.getIndentationLeft());
+            assertEquals(-1, p.getIndentationLeft());
 
-        CTInd ind = ppr.addNewInd();
-        ind.setLeft(new BigInteger("10"));
-        assertEquals(10, p.getIndentationLeft());
+            CTInd ind = ppr.addNewInd();
+            ind.setLeft(new BigInteger("10"));
+            assertEquals(10, p.getIndentationLeft());
 
-        p.setIndentationLeft(100);
-        assertEquals(100, ind.getLeft().intValue());
-        
-        doc.close();
+            p.setIndentationLeft(100);
+            assertEquals(100, ind.getLeft().intValue());
+        }
     }
 
     @Test
     public void testSetGetVerticalAlignment() throws IOException {
         //new clean instance of paragraph
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
 
-        CTP ctp = p.getCTP();
-        CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
+            CTP ctp = p.getCTP();
+            CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
 
-        CTTextAlignment txtAlign = ppr.addNewTextAlignment();
-        txtAlign.setVal(STTextAlignment.CENTER);
-        assertEquals(TextAlignment.CENTER, p.getVerticalAlignment());
+            CTTextAlignment txtAlign = ppr.addNewTextAlignment();
+            txtAlign.setVal(STTextAlignment.CENTER);
+            assertEquals(TextAlignment.CENTER, p.getVerticalAlignment());
 
-        p.setVerticalAlignment(TextAlignment.BOTTOM);
-        assertEquals(STTextAlignment.BOTTOM, ppr.getTextAlignment().getVal());
-        
-        doc.close();
+            p.setVerticalAlignment(TextAlignment.BOTTOM);
+            assertEquals(STTextAlignment.BOTTOM, ppr.getTextAlignment().getVal());
+        }
     }
 
     @Test
     public void testSetGetWordWrap() throws IOException {
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
 
-        CTP ctp = p.getCTP();
-        CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
+            CTP ctp = p.getCTP();
+            CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
 
-        CTOnOff wordWrap = ppr.addNewWordWrap();
-        wordWrap.setVal(STOnOff.FALSE);
-        assertEquals(false, p.isWordWrap());
+            CTOnOff wordWrap = ppr.addNewWordWrap();
+            wordWrap.setVal(STOnOff.FALSE);
+            assertFalse(p.isWordWrap());
 
-        p.setWordWrapped(true);
-        assertEquals(STOnOff.TRUE, ppr.getWordWrap().getVal());
-        
-        doc.close();
+            p.setWordWrapped(true);
+            assertEquals(STOnOff.TRUE, ppr.getWordWrap().getVal());
+        }
     }
 
     @Test
     public void testSetGetPageBreak() throws IOException {
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
 
-        CTP ctp = p.getCTP();
-        CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
+            CTP ctp = p.getCTP();
+            CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
 
-        CTOnOff pageBreak = ppr.addNewPageBreakBefore();
-        pageBreak.setVal(STOnOff.FALSE);
-        assertEquals(false, p.isPageBreak());
+            CTOnOff pageBreak = ppr.addNewPageBreakBefore();
+            pageBreak.setVal(STOnOff.FALSE);
+            assertFalse(p.isPageBreak());
 
-        p.setPageBreak(true);
-        assertEquals(STOnOff.TRUE, ppr.getPageBreakBefore().getVal());
-        doc.close();
+            p.setPageBreak(true);
+            assertEquals(STOnOff.TRUE, ppr.getPageBreakBefore().getVal());
+        }
     }
 
     @Test
     public void testBookmarks() throws IOException {
-        XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("bookmarks.docx");
-        XWPFParagraph paragraph = doc.getParagraphs().get(0);
-        assertEquals("Sample Word Document", paragraph.getText());
-        assertEquals(1, paragraph.getCTP().sizeOfBookmarkStartArray());
-        assertEquals(0, paragraph.getCTP().sizeOfBookmarkEndArray());
-        CTBookmark ctBookmark = paragraph.getCTP().getBookmarkStartArray(0);
-        assertEquals("poi", ctBookmark.getName());
-        for (CTBookmark bookmark : paragraph.getCTP().getBookmarkStartList()) {
-            assertEquals("poi", bookmark.getName());
+        try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("bookmarks.docx")) {
+            XWPFParagraph paragraph = doc.getParagraphs().get(0);
+            assertEquals("Sample Word Document", paragraph.getText());
+            assertEquals(1, paragraph.getCTP().sizeOfBookmarkStartArray());
+            assertEquals(0, paragraph.getCTP().sizeOfBookmarkEndArray());
+            CTBookmark ctBookmark = paragraph.getCTP().getBookmarkStartArray(0);
+            assertEquals("poi", ctBookmark.getName());
+            for (CTBookmark bookmark : paragraph.getCTP().getBookmarkStartList()) {
+                assertEquals("poi", bookmark.getName());
+            }
         }
-        doc.close();
     }
 
     @Test
     public void testGetSetNumID() throws IOException {
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
 
-        p.setNumID(new BigInteger("10"));
-        assertEquals("10", p.getNumID().toString());
-        doc.close();
+            p.setNumID(new BigInteger("10"));
+            assertEquals("10", p.getNumID().toString());
+        }
     }
 
     @Test
     public void testAddingRuns() throws IOException {
-        XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
+        try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) {
 
-        XWPFParagraph p = doc.getParagraphs().get(0);
-        assertEquals(2, p.getRuns().size());
+            XWPFParagraph p = doc.getParagraphs().get(0);
+            assertEquals(2, p.getRuns().size());
 
-        XWPFRun r = p.createRun();
-        assertEquals(3, p.getRuns().size());
-        assertEquals(2, p.getRuns().indexOf(r));
+            XWPFRun r = p.createRun();
+            assertEquals(3, p.getRuns().size());
+            assertEquals(2, p.getRuns().indexOf(r));
 
-        XWPFRun r2 = p.insertNewRun(1);
-        assertEquals(4, p.getRuns().size());
-        assertEquals(1, p.getRuns().indexOf(r2));
-        assertEquals(3, p.getRuns().indexOf(r));
-        
-        doc.close();
+            XWPFRun r2 = p.insertNewRun(1);
+            assertEquals(4, p.getRuns().size());
+            assertEquals(1, p.getRuns().indexOf(r2));
+            assertEquals(3, p.getRuns().indexOf(r));
+        }
     }
 
     @Test
     public void testPictures() throws IOException {
-        XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx");
-        assertEquals(7, doc.getParagraphs().size());
-
-        XWPFParagraph p;
-        XWPFRun r;
-
-        // Text paragraphs
-        assertEquals("Sheet with various pictures", doc.getParagraphs().get(0).getText());
-        assertEquals("(jpeg, png, wmf, emf and pict) ", doc.getParagraphs().get(1).getText());
-
-        // Spacer ones
-        assertEquals("", doc.getParagraphs().get(2).getText());
-        assertEquals("", doc.getParagraphs().get(3).getText());
-        assertEquals("", doc.getParagraphs().get(4).getText());
-
-        // Image one
-        p = doc.getParagraphs().get(5);
-        assertEquals(6, p.getRuns().size());
-
-        r = p.getRuns().get(0);
-        assertEquals("", r.toString());
-        assertEquals(1, r.getEmbeddedPictures().size());
-        assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
-        assertEquals("image1.wmf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
-
-        r = p.getRuns().get(1);
-        assertEquals("", r.toString());
-        assertEquals(1, r.getEmbeddedPictures().size());
-        assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
-        assertEquals("image2.png", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
-
-        r = p.getRuns().get(2);
-        assertEquals("", r.toString());
-        assertEquals(1, r.getEmbeddedPictures().size());
-        assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
-        assertEquals("image3.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
-
-        r = p.getRuns().get(3);
-        assertEquals("", r.toString());
-        assertEquals(1, r.getEmbeddedPictures().size());
-        assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
-        assertEquals("image4.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
-
-        r = p.getRuns().get(4);
-        assertEquals("", r.toString());
-        assertEquals(1, r.getEmbeddedPictures().size());
-        assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
-        assertEquals("image5.jpeg", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
-
-        r = p.getRuns().get(5);
-        assertEquals(" ", r.toString());
-        assertEquals(0, r.getEmbeddedPictures().size());
-
-        // Final spacer
-        assertEquals("", doc.getParagraphs().get(6).getText());
-
-
-        // Look in detail at one
-        r = p.getRuns().get(4);
-        XWPFPicture pict = r.getEmbeddedPictures().get(0);
-        CTPicture picture = pict.getCTPicture();
-        assertEquals("rId8", picture.getBlipFill().getBlip().getEmbed());
-
-        // Ensure that the ooxml compiler finds everything we need
-        r.getCTR().getDrawingArray(0);
-        r.getCTR().getDrawingArray(0).getInlineArray(0);
-        r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic();
-        r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic().getGraphicData();
-        PicDocument pd = new PicDocumentImpl(null);
-        assertTrue(pd.isNil());
-        
-        doc.close();
+        try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx")) {
+            assertEquals(7, doc.getParagraphs().size());
+
+            XWPFParagraph p;
+            XWPFRun r;
+
+            // Text paragraphs
+            assertEquals("Sheet with various pictures", doc.getParagraphs().get(0).getText());
+            assertEquals("(jpeg, png, wmf, emf and pict) ", doc.getParagraphs().get(1).getText());
+
+            // Spacer ones
+            assertEquals("", doc.getParagraphs().get(2).getText());
+            assertEquals("", doc.getParagraphs().get(3).getText());
+            assertEquals("", doc.getParagraphs().get(4).getText());
+
+            // Image one
+            p = doc.getParagraphs().get(5);
+            assertEquals(6, p.getRuns().size());
+
+            r = p.getRuns().get(0);
+            assertEquals("", r.toString());
+            assertEquals(1, r.getEmbeddedPictures().size());
+            assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
+            assertEquals("image1.wmf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
+
+            r = p.getRuns().get(1);
+            assertEquals("", r.toString());
+            assertEquals(1, r.getEmbeddedPictures().size());
+            assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
+            assertEquals("image2.png", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
+
+            r = p.getRuns().get(2);
+            assertEquals("", r.toString());
+            assertEquals(1, r.getEmbeddedPictures().size());
+            assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
+            assertEquals("image3.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
+
+            r = p.getRuns().get(3);
+            assertEquals("", r.toString());
+            assertEquals(1, r.getEmbeddedPictures().size());
+            assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
+            assertEquals("image4.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
+
+            r = p.getRuns().get(4);
+            assertEquals("", r.toString());
+            assertEquals(1, r.getEmbeddedPictures().size());
+            assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
+            assertEquals("image5.jpeg", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
+
+            r = p.getRuns().get(5);
+            assertEquals(" ", r.toString());
+            assertEquals(0, r.getEmbeddedPictures().size());
+
+            // Final spacer
+            assertEquals("", doc.getParagraphs().get(6).getText());
+
+
+            // Look in detail at one
+            r = p.getRuns().get(4);
+            XWPFPicture pict = r.getEmbeddedPictures().get(0);
+            CTPicture picture = pict.getCTPicture();
+            assertEquals("rId8", picture.getBlipFill().getBlip().getEmbed());
+
+            // Ensure that the ooxml compiler finds everything we need
+            r.getCTR().getDrawingArray(0);
+            r.getCTR().getDrawingArray(0).getInlineArray(0);
+            r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic();
+            r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic().getGraphicData();
+            PicDocument pd = new PicDocumentImpl(null);
+            assertTrue(pd.isNil());
+        }
     }
 
     @Test
     public void testTika792() throws Exception {
         //This test forces the loading of CTMoveBookmark and
         //CTMoveBookmarkImpl into ooxml-lite.
-        XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Tika-792.docx");
-        XWPFParagraph paragraph = doc.getParagraphs().get(0);
-        assertEquals("", paragraph.getText());
-        paragraph = doc.getParagraphs().get(1);
-        assertEquals("b", paragraph.getText());
-        doc.close();
+        try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Tika-792.docx")) {
+            XWPFParagraph paragraph = doc.getParagraphs().get(0);
+            assertEquals("", paragraph.getText());
+            paragraph = doc.getParagraphs().get(1);
+            assertEquals("b", paragraph.getText());
+        }
     }
 
     @Test
     public void testSettersGetters() throws IOException {
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
-
-        assertTrue(p.isEmpty());
-        assertFalse(p.removeRun(0));
-
-        p.setBorderTop(Borders.BABY_PACIFIER);
-        p.setBorderBetween(Borders.BABY_PACIFIER);
-        p.setBorderBottom(Borders.BABY_RATTLE);
-
-        assertNotNull(p.getIRuns());
-        assertEquals(0, p.getIRuns().size());
-        assertFalse(p.isEmpty());
-        assertNull(p.getStyleID());
-        assertNull(p.getStyle());
-
-        assertNull(p.getNumID());
-        p.setNumID(BigInteger.valueOf(12));
-        assertEquals(BigInteger.valueOf(12), p.getNumID());
-        p.setNumID(BigInteger.valueOf(13));
-        assertEquals(BigInteger.valueOf(13), p.getNumID());
-
-        assertNull(p.getNumFmt());
-
-        assertNull(p.getNumIlvl());
-
-        assertEquals("", p.getParagraphText());
-        assertEquals("", p.getPictureText());
-        assertEquals("", p.getFootnoteText());
-
-        p.setBorderBetween(Borders.NONE);
-        assertEquals(Borders.NONE, p.getBorderBetween());
-        p.setBorderBetween(Borders.BASIC_BLACK_DASHES);
-        assertEquals(Borders.BASIC_BLACK_DASHES, p.getBorderBetween());
-
-        p.setBorderBottom(Borders.NONE);
-        assertEquals(Borders.NONE, p.getBorderBottom());
-        p.setBorderBottom(Borders.BABY_RATTLE);
-        assertEquals(Borders.BABY_RATTLE, p.getBorderBottom());
-
-        p.setBorderLeft(Borders.NONE);
-        assertEquals(Borders.NONE, p.getBorderLeft());
-        p.setBorderLeft(Borders.BASIC_WHITE_SQUARES);
-        assertEquals(Borders.BASIC_WHITE_SQUARES, p.getBorderLeft());
-
-        p.setBorderRight(Borders.NONE);
-        assertEquals(Borders.NONE, p.getBorderRight());
-        p.setBorderRight(Borders.BASIC_WHITE_DASHES);
-        assertEquals(Borders.BASIC_WHITE_DASHES, p.getBorderRight());
-
-        p.setBorderBottom(Borders.NONE);
-        assertEquals(Borders.NONE, p.getBorderBottom());
-        p.setBorderBottom(Borders.BASIC_WHITE_DOTS);
-        assertEquals(Borders.BASIC_WHITE_DOTS, p.getBorderBottom());
-
-        assertFalse(p.isPageBreak());
-        p.setPageBreak(true);
-        assertTrue(p.isPageBreak());
-        p.setPageBreak(false);
-        assertFalse(p.isPageBreak());
-
-        assertEquals(-1, p.getSpacingAfter());
-        p.setSpacingAfter(12);
-        assertEquals(12, p.getSpacingAfter());
-
-        assertEquals(-1, p.getSpacingAfterLines());
-        p.setSpacingAfterLines(14);
-        assertEquals(14, p.getSpacingAfterLines());
-
-        assertEquals(-1, p.getSpacingBefore());
-        p.setSpacingBefore(16);
-        assertEquals(16, p.getSpacingBefore());
-
-        assertEquals(-1, p.getSpacingBeforeLines());
-        p.setSpacingBeforeLines(18);
-        assertEquals(18, p.getSpacingBeforeLines());
-
-        assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule());
-        p.setSpacingLineRule(LineSpacingRule.EXACT);
-        assertEquals(LineSpacingRule.EXACT, p.getSpacingLineRule());
-
-        assertEquals(-1, p.getIndentationLeft());
-        p.setIndentationLeft(21);
-        assertEquals(21, p.getIndentationLeft());
-
-        assertEquals(-1, p.getIndentationRight());
-        p.setIndentationRight(25);
-        assertEquals(25, p.getIndentationRight());
-
-        assertEquals(-1, p.getIndentationHanging());
-        p.setIndentationHanging(25);
-        assertEquals(25, p.getIndentationHanging());
-
-        assertEquals(-1, p.getIndentationFirstLine());
-        p.setIndentationFirstLine(25);
-        assertEquals(25, p.getIndentationFirstLine());
-
-        assertFalse(p.isWordWrap());
-        p.setWordWrapped(true);
-        assertTrue(p.isWordWrap());
-        p.setWordWrapped(false);
-        assertFalse(p.isWordWrap());
-
-        assertNull(p.getStyle());
-        p.setStyle("teststyle");
-        assertEquals("teststyle", p.getStyle());
-
-        p.addRun(CTR.Factory.newInstance());
-
-        //assertTrue(p.removeRun(0));
-
-        assertNotNull(p.getBody());
-        assertEquals(BodyElementType.PARAGRAPH, p.getElementType());
-        assertEquals(BodyType.DOCUMENT, p.getPartType());
-        
-        doc.close();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
+
+            assertTrue(p.isEmpty());
+            assertFalse(p.removeRun(0));
+
+            p.setBorderTop(Borders.BABY_PACIFIER);
+            p.setBorderBetween(Borders.BABY_PACIFIER);
+            p.setBorderBottom(Borders.BABY_RATTLE);
+
+            assertNotNull(p.getIRuns());
+            assertEquals(0, p.getIRuns().size());
+            assertFalse(p.isEmpty());
+            assertNull(p.getStyleID());
+            assertNull(p.getStyle());
+
+            assertNull(p.getNumID());
+            p.setNumID(BigInteger.valueOf(12));
+            assertEquals(BigInteger.valueOf(12), p.getNumID());
+            p.setNumID(BigInteger.valueOf(13));
+            assertEquals(BigInteger.valueOf(13), p.getNumID());
+
+            assertNull(p.getNumFmt());
+
+            assertNull(p.getNumIlvl());
+
+            assertEquals("", p.getParagraphText());
+            assertEquals("", p.getPictureText());
+            assertEquals("", p.getFootnoteText());
+
+            p.setBorderBetween(Borders.NONE);
+            assertEquals(Borders.NONE, p.getBorderBetween());
+            p.setBorderBetween(Borders.BASIC_BLACK_DASHES);
+            assertEquals(Borders.BASIC_BLACK_DASHES, p.getBorderBetween());
+
+            p.setBorderBottom(Borders.NONE);
+            assertEquals(Borders.NONE, p.getBorderBottom());
+            p.setBorderBottom(Borders.BABY_RATTLE);
+            assertEquals(Borders.BABY_RATTLE, p.getBorderBottom());
+
+            p.setBorderLeft(Borders.NONE);
+            assertEquals(Borders.NONE, p.getBorderLeft());
+            p.setBorderLeft(Borders.BASIC_WHITE_SQUARES);
+            assertEquals(Borders.BASIC_WHITE_SQUARES, p.getBorderLeft());
+
+            p.setBorderRight(Borders.NONE);
+            assertEquals(Borders.NONE, p.getBorderRight());
+            p.setBorderRight(Borders.BASIC_WHITE_DASHES);
+            assertEquals(Borders.BASIC_WHITE_DASHES, p.getBorderRight());
+
+            p.setBorderBottom(Borders.NONE);
+            assertEquals(Borders.NONE, p.getBorderBottom());
+            p.setBorderBottom(Borders.BASIC_WHITE_DOTS);
+            assertEquals(Borders.BASIC_WHITE_DOTS, p.getBorderBottom());
+
+            assertFalse(p.isPageBreak());
+            p.setPageBreak(true);
+            assertTrue(p.isPageBreak());
+            p.setPageBreak(false);
+            assertFalse(p.isPageBreak());
+
+            assertEquals(-1, p.getSpacingAfter());
+            p.setSpacingAfter(12);
+            assertEquals(12, p.getSpacingAfter());
+
+            assertEquals(-1, p.getSpacingAfterLines());
+            p.setSpacingAfterLines(14);
+            assertEquals(14, p.getSpacingAfterLines());
+
+            assertEquals(-1, p.getSpacingBefore());
+            p.setSpacingBefore(16);
+            assertEquals(16, p.getSpacingBefore());
+
+            assertEquals(-1, p.getSpacingBeforeLines());
+            p.setSpacingBeforeLines(18);
+            assertEquals(18, p.getSpacingBeforeLines());
+
+            assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule());
+            p.setSpacingLineRule(LineSpacingRule.EXACT);
+            assertEquals(LineSpacingRule.EXACT, p.getSpacingLineRule());
+
+            assertEquals(-1, p.getIndentationLeft());
+            p.setIndentationLeft(21);
+            assertEquals(21, p.getIndentationLeft());
+
+            assertEquals(-1, p.getIndentationRight());
+            p.setIndentationRight(25);
+            assertEquals(25, p.getIndentationRight());
+
+            assertEquals(-1, p.getIndentationHanging());
+            p.setIndentationHanging(25);
+            assertEquals(25, p.getIndentationHanging());
+
+            assertEquals(-1, p.getIndentationFirstLine());
+            p.setIndentationFirstLine(25);
+            assertEquals(25, p.getIndentationFirstLine());
+
+            assertFalse(p.isWordWrap());
+            p.setWordWrapped(true);
+            assertTrue(p.isWordWrap());
+            p.setWordWrapped(false);
+            assertFalse(p.isWordWrap());
+
+            assertNull(p.getStyle());
+            p.setStyle("testStyle");
+            assertEquals("testStyle", p.getStyle());
+
+            p.addRun(CTR.Factory.newInstance());
+
+            //assertTrue(p.removeRun(0));
+
+            assertNotNull(p.getBody());
+            assertEquals(BodyElementType.PARAGRAPH, p.getElementType());
+            assertEquals(BodyType.DOCUMENT, p.getPartType());
+        }
     }
 
     @Test
     public void testSearchTextNotFound() throws IOException {
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
 
-        assertNull(p.searchText("test", new PositionInParagraph()));
-        assertEquals("", p.getText());
-        doc.close();
+            assertNull(p.searchText("test", new PositionInParagraph()));
+            assertEquals("", p.getText());
+        }
     }
 
     @Test
     public void testSearchTextFound() throws IOException {
-        XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx");
+        try (XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx")) {
 
-        List<XWPFParagraph> ps = xml.getParagraphs();
-        assertEquals(10, ps.size());
+            List<XWPFParagraph> ps = xml.getParagraphs();
+            assertEquals(10, ps.size());
 
-        XWPFParagraph p = ps.get(0);
+            XWPFParagraph p = ps.get(0);
 
-        TextSegment segment = p.searchText("sample word document", new PositionInParagraph());
-        assertNotNull(segment);
+            TextSegment segment = p.searchText("sample word document", new PositionInParagraph());
+            assertNotNull(segment);
 
-        assertEquals("sample word document", p.getText(segment));
+            assertEquals("sample word document", p.getText(segment));
 
-        assertTrue(p.removeRun(0));
-        xml.close();
+            assertTrue(p.removeRun(0));
+        }
     }
     
     @Test
     public void testFieldRuns() throws IOException {
-        XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx");
-        List<XWPFParagraph> ps = doc.getParagraphs();
-        assertEquals(1, ps.size());
-        
-        XWPFParagraph p = ps.get(0);
-        assertEquals(1, p.getRuns().size());
-        assertEquals(1, p.getIRuns().size());
-        
-        XWPFRun r = p.getRuns().get(0);
-        assertEquals(XWPFFieldRun.class, r.getClass());
-        
-        XWPFFieldRun fr = (XWPFFieldRun)r;
-        assertEquals(" FILENAME   \\* MERGEFORMAT ", fr.getFieldInstruction());
-        assertEquals("FldSimple.docx", fr.text());
-        assertEquals("FldSimple.docx", p.getText());
-        doc.close();
+        try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx")) {
+            List<XWPFParagraph> ps = doc.getParagraphs();
+            assertEquals(1, ps.size());
+
+            XWPFParagraph p = ps.get(0);
+            assertEquals(1, p.getRuns().size());
+            assertEquals(1, p.getIRuns().size());
+
+            XWPFRun r = p.getRuns().get(0);
+            assertEquals(XWPFFieldRun.class, r.getClass());
+
+            XWPFFieldRun fr = (XWPFFieldRun) r;
+            assertEquals(" FILENAME   \\* MERGEFORMAT ", fr.getFieldInstruction());
+            assertEquals("FldSimple.docx", fr.text());
+            assertEquals("FldSimple.docx", p.getText());
+        }
     }
 
     @SuppressWarnings("deprecation")
     @Test
     public void testRuns() throws IOException {
-        XWPFDocument doc = new XWPFDocument();
-        XWPFParagraph p = doc.createParagraph();
+        try (XWPFDocument doc = new XWPFDocument()) {
+            XWPFParagraph p = doc.createParagraph();
 
-        CTR run = CTR.Factory.newInstance();
-        XWPFRun r = new XWPFRun(run, doc.createParagraph());
-        p.addRun(r);
-        p.addRun(r);
+            CTR run = CTR.Factory.newInstance();
+            XWPFRun r = new XWPFRun(run, doc.createParagraph());
+            p.addRun(r);
+            p.addRun(r);
 
-        assertNotNull(p.getRun(run));
-        assertNull(p.getRun(null));
-        doc.close();
+            assertNotNull(p.getRun(run));
+            assertNull(p.getRun(null));
+        }
     }
 
     @Test
     public void test58067() throws IOException {
-        XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("58067.docx");
-        
-        StringBuilder str = new StringBuilder();
-        for(XWPFParagraph par : doc.getParagraphs()) {
-            str.append(par.getText()).append("\n");
+        try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("58067.docx")) {
+
+            StringBuilder str = new StringBuilder();
+            for (XWPFParagraph par : doc.getParagraphs()) {
+                str.append(par.getText()).append("\n");
+            }
+            assertEquals("This is a test.\n\n\n\n3\n4\n5\n\n\n\nThis is a whole paragraph where one word is deleted.\n", str.toString());
         }
-        assertEquals("This is a test.\n\n\n\n3\n4\n5\n\n\n\nThis is a whole paragraph where one word is deleted.\n", str.toString());
     }
 
     @Test
     public void test61787() throws IOException {
-        XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61787.docx");
-
-        StringBuilder str = new StringBuilder();
-        for(XWPFParagraph par : doc.getParagraphs()) {
-            str.append(par.getText()).append("\n");
+        try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61787.docx")) {
+
+            StringBuilder str = new StringBuilder();
+            for (XWPFParagraph par : doc.getParagraphs()) {
+                str.append(par.getText()).append("\n");
+            }
+            String s = str.toString();
+            assertTrue("Having text: \n" + s + "\nTrimmed length: " + s.trim().length(), s.trim().length() > 0);
         }
-        String s = str.toString();
-        assertTrue("Having text: \n" + s + "\nTrimmed lenght: " + s.trim().length(), s.trim().length() > 0);
     }
 
     /**
@@ -635,85 +620,86 @@ public final class TestXWPFParagraph {
      */
     @Test
     public void testNumberedLists() throws Exception {
-        XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ComplexNumberedLists.docx");
-        XWPFParagraph p;
-        
-        p = doc.getParagraphArray(0);
-        assertEquals("This is a document with numbered lists", p.getText());
-        assertEquals(null, p.getNumID());
-        assertEquals(null, p.getNumIlvl());
-        assertEquals(null, p.getNumStartOverride());
-        
-        p = doc.getParagraphArray(1);
-        assertEquals("Entry #1", p.getText());
-        assertEquals(BigInteger.valueOf(1), p.getNumID());
-        assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
-        assertEquals(null, p.getNumStartOverride());
-        
-        p = doc.getParagraphArray(2);
-        assertEquals("Entry #2, with children", p.getText());
-        assertEquals(BigInteger.valueOf(1), p.getNumID());
-        assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
-        assertEquals(null, p.getNumStartOverride());
-        
-        p = doc.getParagraphArray(3);
-        assertEquals("2-a", p.getText());
-        assertEquals(BigInteger.valueOf(1), p.getNumID());
-        assertEquals(BigInteger.valueOf(1), p.getNumIlvl());
-        assertEquals(null, p.getNumStartOverride());
-        
-        p = doc.getParagraphArray(4);
-        assertEquals("2-b", p.getText());
-        assertEquals(BigInteger.valueOf(1), p.getNumID());
-        assertEquals(BigInteger.valueOf(1), p.getNumIlvl());
-        assertEquals(null, p.getNumStartOverride());
-        
-        p = doc.getParagraphArray(5);
-        assertEquals("2-c", p.getText());
-        assertEquals(BigInteger.valueOf(1), p.getNumID());
-        assertEquals(BigInteger.valueOf(1), p.getNumIlvl());
-        assertEquals(null, p.getNumStartOverride());
-        
-        p = doc.getParagraphArray(6);
-        assertEquals("Entry #3", p.getText());
-        assertEquals(BigInteger.valueOf(1), p.getNumID());
-        assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
-        assertEquals(null, p.getNumStartOverride());
-        
-        p = doc.getParagraphArray(7);
-        assertEquals("Entry #4", p.getText());
-        assertEquals(BigInteger.valueOf(1), p.getNumID());
-        assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
-        assertEquals(null, p.getNumStartOverride());
-        
-        // New list
-        p = doc.getParagraphArray(8);
-        assertEquals("Restarted to 1 from 5", p.getText());
-        assertEquals(BigInteger.valueOf(2), p.getNumID());
-        assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
-        assertEquals(null, p.getNumStartOverride());
-        
-        p = doc.getParagraphArray(9);
-        assertEquals("Restarted @ 2", p.getText());
-        assertEquals(BigInteger.valueOf(2), p.getNumID());
-        assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
-        assertEquals(null, p.getNumStartOverride());
-        
-        p = doc.getParagraphArray(10);
-        assertEquals("Restarted @ 3", p.getText());
-        assertEquals(BigInteger.valueOf(2), p.getNumID());
-        assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
-        assertEquals(null, p.getNumStartOverride());
-        
-        // New list starting at 10
-        p = doc.getParagraphArray(11);
-        assertEquals("Jump to new list at 10", p.getText());
-        assertEquals(BigInteger.valueOf(6), p.getNumID());
-        assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
-        // TODO Why isn't this seen as 10?
-        assertEquals(null, p.getNumStartOverride());
-        
-        // TODO Shouldn't we use XWPFNumbering or similar here?
-        // TODO Make it easier to change
+        try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ComplexNumberedLists.docx")) {
+            XWPFParagraph p;
+
+            p = doc.getParagraphArray(0);
+            assertEquals("This is a document with numbered lists", p.getText());
+            assertNull(p.getNumID());
+            assertNull(p.getNumIlvl());
+            assertNull(p.getNumStartOverride());
+
+            p = doc.getParagraphArray(1);
+            assertEquals("Entry #1", p.getText());
+            assertEquals(BigInteger.valueOf(1), p.getNumID());
+            assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
+            assertNull(p.getNumStartOverride());
+
+            p = doc.getParagraphArray(2);
+            assertEquals("Entry #2, with children", p.getText());
+            assertEquals(BigInteger.valueOf(1), p.getNumID());
+            assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
+            assertNull(p.getNumStartOverride());
+
+            p = doc.getParagraphArray(3);
+            assertEquals("2-a", p.getText());
+            assertEquals(BigInteger.valueOf(1), p.getNumID());
+            assertEquals(BigInteger.valueOf(1), p.getNumIlvl());
+            assertNull(p.getNumStartOverride());
+
+            p = doc.getParagraphArray(4);
+            assertEquals("2-b", p.getText());
+            assertEquals(BigInteger.valueOf(1), p.getNumID());
+            assertEquals(BigInteger.valueOf(1), p.getNumIlvl());
+            assertNull(p.getNumStartOverride());
+
+            p = doc.getParagraphArray(5);
+            assertEquals("2-c", p.getText());
+            assertEquals(BigInteger.valueOf(1), p.getNumID());
+            assertEquals(BigInteger.valueOf(1), p.getNumIlvl());
+            assertNull(p.getNumStartOverride());
+
+            p = doc.getParagraphArray(6);
+            assertEquals("Entry #3", p.getText());
+            assertEquals(BigInteger.valueOf(1), p.getNumID());
+            assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
+            assertNull(p.getNumStartOverride());
+
+            p = doc.getParagraphArray(7);
+            assertEquals("Entry #4", p.getText());
+            assertEquals(BigInteger.valueOf(1), p.getNumID());
+            assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
+            assertNull(p.getNumStartOverride());
+
+            // New list
+            p = doc.getParagraphArray(8);
+            assertEquals("Restarted to 1 from 5", p.getText());
+            assertEquals(BigInteger.valueOf(2), p.getNumID());
+            assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
+            assertNull(p.getNumStartOverride());
+
+            p = doc.getParagraphArray(9);
+            assertEquals("Restarted @ 2", p.getText());
+            assertEquals(BigInteger.valueOf(2), p.getNumID());
+            assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
+            assertNull(p.getNumStartOverride());
+
+            p = doc.getParagraphArray(10);
+            assertEquals("Restarted @ 3", p.getText());
+            assertEquals(BigInteger.valueOf(2), p.getNumID());
+            assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
+            assertNull(p.getNumStartOverride());
+
+            // New list starting at 10
+            p = doc.getParagraphArray(11);
+            assertEquals("Jump to new list at 10", p.getText());
+            assertEquals(BigInteger.valueOf(6), p.getNumID());
+            assertEquals(BigInteger.valueOf(0), p.getNumIlvl());
+            // TODO Why isn't this seen as 10?
+            assertNull(p.getNumStartOverride());
+
+            // TODO Shouldn't we use XWPFNumbering or similar here?
+            // TODO Make it easier to change
+        }
     }
 }
index c1406520122aab7b803adf6255368a33ca7cf2e9..daf4675f9dd7a47ddef68c7fc508a3a8bb76a7e3 100644 (file)
@@ -34,61 +34,65 @@ import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
 public class TestXWPFPictureData extends TestCase {
 
     public void testRead() throws InvalidFormatException, IOException {
-        XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx");
-        List<XWPFPictureData> pictures = sampleDoc.getAllPictures();
+        try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx")) {
+            List<XWPFPictureData> pictures = sampleDoc.getAllPictures();
 
-        assertEquals(5, pictures.size());
-        String[] ext = {"wmf", "png", "emf", "emf", "jpeg"};
-        for (int i = 0; i < pictures.size(); i++) {
-            assertEquals(ext[i], pictures.get(i).suggestFileExtension());
-        }
+            assertEquals(5, pictures.size());
+            String[] ext = {"wmf", "png", "emf", "emf", "jpeg"};
+            for (int i = 0; i < pictures.size(); i++) {
+                assertEquals(ext[i], pictures.get(i).suggestFileExtension());
+            }
 
-        int num = pictures.size();
+            int num = pictures.size();
 
-        byte[] pictureData = XWPFTestDataSamples.getImage("nature1.jpg");
+            byte[] pictureData = XWPFTestDataSamples.getImage("nature1.jpg");
 
-        String relationId = sampleDoc.addPictureData(pictureData, XWPFDocument.PICTURE_TYPE_JPEG);
-        // picture list was updated
-        assertEquals(num + 1, pictures.size());
-        XWPFPictureData pict = (XWPFPictureData) sampleDoc.getRelationById(relationId);
-        assertEquals("jpeg", pict.suggestFileExtension());
-        assertArrayEquals(pictureData, pict.getData());
+            String relationId = sampleDoc.addPictureData(pictureData, XWPFDocument.PICTURE_TYPE_JPEG);
+            // picture list was updated
+            assertEquals(num + 1, pictures.size());
+            XWPFPictureData pict = (XWPFPictureData) sampleDoc.getRelationById(relationId);
+            assertNotNull(pict);
+            assertEquals("jpeg", pict.suggestFileExtension());
+            assertArrayEquals(pictureData, pict.getData());
+        }
     }
 
     public void testPictureInHeader() throws IOException {
-        XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx");
-        verifyOneHeaderPicture(sampleDoc);
+        try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx")) {
+            verifyOneHeaderPicture(sampleDoc);
 
-        XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc);
-        verifyOneHeaderPicture(readBack);
+            XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc);
+            verifyOneHeaderPicture(readBack);
+        }
     }
     
     public void testCreateHeaderPicture() throws Exception {
-        XWPFDocument doc = new XWPFDocument();
-        
-        // Starts with no header
-        XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy();
-        assertNull(policy);
-        
-        // Add a default header
-        policy = doc.createHeaderFooterPolicy();
-        XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
-        header.createParagraph().createRun().setText("Hello, Header World!");
-        header.createParagraph().createRun().setText("Paragraph 2");
-        assertEquals(0, header.getAllPictures().size());
-        assertEquals(2, header.getParagraphs().size());
-        
-        // Add a picture to the first paragraph
-        header.getParagraphs().get(0).getRuns().get(0).addPicture(
-                new ByteArrayInputStream(new byte[] {1,2,3,4}), 
-                Document.PICTURE_TYPE_JPEG, "test.jpg", 2, 2);
-        
-        // Check
-        verifyOneHeaderPicture(doc);
-        
-        // Save, re-load, re-check
-        XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(doc);
-        verifyOneHeaderPicture(readBack);
+        try (XWPFDocument doc = new XWPFDocument()) {
+
+            // Starts with no header
+            XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy();
+            assertNull(policy);
+
+            // Add a default header
+            policy = doc.createHeaderFooterPolicy();
+            XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
+            header.createParagraph().createRun().setText("Hello, Header World!");
+            header.createParagraph().createRun().setText("Paragraph 2");
+            assertEquals(0, header.getAllPictures().size());
+            assertEquals(2, header.getParagraphs().size());
+
+            // Add a picture to the first paragraph
+            header.getParagraphs().get(0).getRuns().get(0).addPicture(
+                    new ByteArrayInputStream(new byte[]{1, 2, 3, 4}),
+                    Document.PICTURE_TYPE_JPEG, "test.jpg", 2, 2);
+
+            // Check
+            verifyOneHeaderPicture(doc);
+
+            // Save, re-load, re-check
+            XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(doc);
+            verifyOneHeaderPicture(readBack);
+        }
     }
 
     private void verifyOneHeaderPicture(XWPFDocument sampleDoc) {
@@ -101,75 +105,78 @@ public class TestXWPFPictureData extends TestCase {
     }
 
     public void testNew() throws InvalidFormatException, IOException {
-        XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx");
-        byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg");
-        assertNotNull(jpegData);
-        byte[] gifData = XWPFTestDataSamples.getImage("nature1.gif");
-        assertNotNull(gifData);
-        byte[] pngData = XWPFTestDataSamples.getImage("nature1.png");
-        assertNotNull(pngData);
-
-        List<XWPFPictureData> pictures = doc.getAllPictures();
-        assertEquals(0, pictures.size());
-
-        // Document shouldn't have any image relationships
-        assertEquals(13, doc.getPackagePart().getRelationships().size());
-        for (PackageRelationship rel : doc.getPackagePart().getRelationships()) {
-            if (rel.getRelationshipType().equals(XSSFRelation.IMAGE_JPEG.getRelation())) {
-                fail("Shouldn't have JPEG yet");
+        try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx")) {
+            byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg");
+            assertNotNull(jpegData);
+            byte[] gifData = XWPFTestDataSamples.getImage("nature1.gif");
+            assertNotNull(gifData);
+            byte[] pngData = XWPFTestDataSamples.getImage("nature1.png");
+            assertNotNull(pngData);
+
+            List<XWPFPictureData> pictures = doc.getAllPictures();
+            assertEquals(0, pictures.size());
+
+            // Document shouldn't have any image relationships
+            assertEquals(13, doc.getPackagePart().getRelationships().size());
+            for (PackageRelationship rel : doc.getPackagePart().getRelationships()) {
+                if (rel.getRelationshipType().equals(XSSFRelation.IMAGE_JPEG.getRelation())) {
+                    fail("Shouldn't have JPEG yet");
+                }
             }
-        }
 
-        // Add the image
-        String relationId = doc.addPictureData(jpegData, XWPFDocument.PICTURE_TYPE_JPEG);
-        assertEquals(1, pictures.size());
-        XWPFPictureData jpgPicData = (XWPFPictureData) doc.getRelationById(relationId);
-        assertEquals("jpeg", jpgPicData.suggestFileExtension());
-        assertArrayEquals(jpegData, jpgPicData.getData());
-
-        // Ensure it now has one
-        assertEquals(14, doc.getPackagePart().getRelationships().size());
-        PackageRelationship jpegRel = null;
-        for (PackageRelationship rel : doc.getPackagePart().getRelationships()) {
-            if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation())) {
-                if (jpegRel != null)
-                    fail("Found 2 jpegs!");
-                jpegRel = rel;
+            // Add the image
+            String relationId = doc.addPictureData(jpegData, XWPFDocument.PICTURE_TYPE_JPEG);
+            assertEquals(1, pictures.size());
+            XWPFPictureData jpgPicData = (XWPFPictureData) doc.getRelationById(relationId);
+            assertNotNull(jpgPicData);
+            assertEquals("jpeg", jpgPicData.suggestFileExtension());
+            assertArrayEquals(jpegData, jpgPicData.getData());
+
+            // Ensure it now has one
+            assertEquals(14, doc.getPackagePart().getRelationships().size());
+            PackageRelationship jpegRel = null;
+            for (PackageRelationship rel : doc.getPackagePart().getRelationships()) {
+                if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation())) {
+                    if (jpegRel != null)
+                        fail("Found 2 jpegs!");
+                    jpegRel = rel;
+                }
             }
-        }
-        assertNotNull("JPEG Relationship not found", jpegRel);
-
-        // Check the details
-        assertNotNull(jpegRel);
-        assertEquals(XWPFRelation.IMAGE_JPEG.getRelation(), jpegRel.getRelationshipType());
-        assertEquals("/word/document.xml", jpegRel.getSource().getPartName().toString());
-        assertEquals("/word/media/image1.jpeg", jpegRel.getTargetURI().getPath());
+            assertNotNull("JPEG Relationship not found", jpegRel);
 
-        XWPFPictureData pictureDataByID = doc.getPictureDataByID(jpegRel.getId());
-        assertArrayEquals(jpegData, pictureDataByID.getData());
+            // Check the details
+            assertNotNull(jpegRel);
+            assertEquals(XWPFRelation.IMAGE_JPEG.getRelation(), jpegRel.getRelationshipType());
+            assertEquals("/word/document.xml", jpegRel.getSource().getPartName().toString());
+            assertEquals("/word/media/image1.jpeg", jpegRel.getTargetURI().getPath());
 
-        // Save an re-load, check it appears
-        doc = XWPFTestDataSamples.writeOutAndReadBack(doc);
-        assertEquals(1, doc.getAllPictures().size());
-        assertEquals(1, doc.getAllPackagePictures().size());
+            XWPFPictureData pictureDataByID = doc.getPictureDataByID(jpegRel.getId());
+            assertArrayEquals(jpegData, pictureDataByID.getData());
 
-        // verify the picture that we read back in
-        pictureDataByID = doc.getPictureDataByID(jpegRel.getId());
-        assertArrayEquals(jpegData, pictureDataByID.getData());
+            // Save an re-load, check it appears
+            try (XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc)) {
+                assertEquals(1, docBack.getAllPictures().size());
+                assertEquals(1, docBack.getAllPackagePictures().size());
 
+                // verify the picture that we read back in
+                pictureDataByID = docBack.getPictureDataByID(jpegRel.getId());
+                assertArrayEquals(jpegData, pictureDataByID.getData());
+            }
+        }
     }
 
     public void testBug51770() throws IOException {
-        XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug51170.docx");
-        XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy();
-        XWPFHeader header = policy.getDefaultHeader();
-        for (XWPFParagraph paragraph : header.getParagraphs()) {
-            for (XWPFRun run : paragraph.getRuns()) {
-                for (XWPFPicture picture : run.getEmbeddedPictures()) {
-                    if (paragraph.getDocument() != null) {
-                        XWPFPictureData data = picture.getPictureData();
-                        if (data != null) {
-                            fail("Should have returned null: "+ data.getFileName());
+        try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug51170.docx")) {
+            XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy();
+            XWPFHeader header = policy.getDefaultHeader();
+            for (XWPFParagraph paragraph : header.getParagraphs()) {
+                for (XWPFRun run : paragraph.getRuns()) {
+                    for (XWPFPicture picture : run.getEmbeddedPictures()) {
+                        if (paragraph.getDocument() != null) {
+                            XWPFPictureData data = picture.getPictureData();
+                            if (data != null) {
+                                fail("Should have returned null: " + data.getFileName());
+                            }
                         }
                     }
                 }
index ce0d97f2b8de489d05643f3a3a5d57d5321d856e..ce16b01a44d02fde5bc220de0b84b71f7ea59b8c 100644 (file)
@@ -875,25 +875,25 @@ public abstract class BaseTestCell {
 
     @Test
     public void test57008() throws IOException {
-        Workbook wb1 = _testDataProvider.createWorkbook();
-        Sheet sheet = wb1.createSheet();
-        
-        Row row0 = sheet.createRow(0);
-        Cell cell0 = row0.createCell(0);
-        cell0.setCellValue("row 0, cell 0 _x0046_ without changes");
-        
-        Cell cell1 = row0.createCell(1);
-        cell1.setCellValue("row 0, cell 1 _x005fx0046_ with changes");
-        
-        Cell cell2 = row0.createCell(2);
-        cell2.setCellValue("hgh_x0041_**_x0100_*_x0101_*_x0190_*_x0200_*_x0300_*_x0427_*");
+        try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb1.createSheet();
 
-        checkUnicodeValues(wb1);
-        
-        Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
-        checkUnicodeValues(wb2);
-        wb2.close();
-        wb1.close();
+            Row row0 = sheet.createRow(0);
+            Cell cell0 = row0.createCell(0);
+            cell0.setCellValue("row 0, cell 0 _x0046_ without changes");
+
+            Cell cell1 = row0.createCell(1);
+            cell1.setCellValue("row 0, cell 1 _x005fx0046_ with changes");
+
+            Cell cell2 = row0.createCell(2);
+            cell2.setCellValue("hgh_x0041_**_x0100_*_x0101_*_x0190_*_x0200_*_x0300_*_x0427_*");
+
+            checkUnicodeValues(wb1);
+
+            try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+                checkUnicodeValues(wb2);
+            }
+        }
     }
 
     /**
@@ -903,30 +903,29 @@ public abstract class BaseTestCell {
     @SuppressWarnings("ConstantConditions")
     @Test
     public void testSetCellValueNullRichTextString() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-        Cell cell = sheet.createRow(0).createCell(0);
-
-        RichTextString nullStr = null;
-        cell.setCellValue(nullStr);
-        assertEquals("", cell.getStringCellValue());
-        assertEquals(CellType.BLANK, cell.getCellType());
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+            Cell cell = sheet.createRow(0).createCell(0);
 
-        cell = sheet.createRow(0).createCell(1);
-        cell.setCellValue(1.2d);
-        assertEquals(CellType.NUMERIC, cell.getCellType());
-        cell.setCellValue(nullStr);
-        assertEquals("", cell.getStringCellValue());
-        assertEquals(CellType.BLANK, cell.getCellType());
+            RichTextString nullStr = null;
+            cell.setCellValue(nullStr);
+            assertEquals("", cell.getStringCellValue());
+            assertEquals(CellType.BLANK, cell.getCellType());
 
-        cell = sheet.createRow(0).createCell(1);
-        cell.setCellValue(wb.getCreationHelper().createRichTextString("Test"));
-        assertEquals(CellType.STRING, cell.getCellType());
-        cell.setCellValue(nullStr);
-        assertEquals("", cell.getStringCellValue());
-        assertEquals(CellType.BLANK, cell.getCellType());
+            cell = sheet.createRow(0).createCell(1);
+            cell.setCellValue(1.2d);
+            assertEquals(CellType.NUMERIC, cell.getCellType());
+            cell.setCellValue(nullStr);
+            assertEquals("", cell.getStringCellValue());
+            assertEquals(CellType.BLANK, cell.getCellType());
 
-        wb.close();
+            cell = sheet.createRow(0).createCell(1);
+            cell.setCellValue(wb.getCreationHelper().createRichTextString("Test"));
+            assertEquals(CellType.STRING, cell.getCellType());
+            cell.setCellValue(nullStr);
+            assertEquals("", cell.getStringCellValue());
+            assertEquals(CellType.BLANK, cell.getCellType());
+        }
     }
 
     private void checkUnicodeValues(Workbook wb) {
@@ -943,33 +942,32 @@ public abstract class BaseTestCell {
      */
     @Test
     public void testMaxTextLength() throws IOException{
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-        Cell cell = sheet.createRow(0).createCell(0);
-
-        int maxlen = wb instanceof HSSFWorkbook ? 
-                SpreadsheetVersion.EXCEL97.getMaxTextLength()
-                : SpreadsheetVersion.EXCEL2007.getMaxTextLength();
-        assertEquals(32767, maxlen);
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+            Cell cell = sheet.createRow(0).createCell(0);
 
-        StringBuilder b = new StringBuilder() ;
+            int maxlen = wb instanceof HSSFWorkbook ?
+                    SpreadsheetVersion.EXCEL97.getMaxTextLength()
+                    : SpreadsheetVersion.EXCEL2007.getMaxTextLength();
+            assertEquals(32767, maxlen);
 
-        // 32767 is okay
-        for( int i = 0 ; i < maxlen ; i++ )
-        {
-            b.append( "X" ) ;
-        }
-        cell.setCellValue(b.toString());
+            StringBuilder b = new StringBuilder();
 
-        b.append("X");
-        // 32768 produces an invalid XLS file
-        try {
+            // 32767 is okay
+            for (int i = 0; i < maxlen; i++) {
+                b.append("X");
+            }
             cell.setCellValue(b.toString());
-            fail("Expected exception");
-        } catch (IllegalArgumentException e){
-            assertEquals("The maximum length of cell contents (text) is 32767 characters", e.getMessage());
+
+            b.append("X");
+            // 32768 produces an invalid XLS file
+            try {
+                cell.setCellValue(b.toString());
+                fail("Expected exception");
+            } catch (IllegalArgumentException e) {
+                assertEquals("The maximum length of cell contents (text) is 32767 characters", e.getMessage());
+            }
         }
-        wb.close();
     }
 
     /**
@@ -977,49 +975,47 @@ public abstract class BaseTestCell {
      */
     @Test
     public void setAsActiveCell() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-        Row row = sheet.createRow(0);
-        Cell A1 = row.createCell(0);
-        Cell B1 = row.createCell(1);
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+            Row row = sheet.createRow(0);
+            Cell A1 = row.createCell(0);
+            Cell B1 = row.createCell(1);
 
-        A1.setAsActiveCell();
-        assertEquals(A1.getAddress(), sheet.getActiveCell());
+            A1.setAsActiveCell();
+            assertEquals(A1.getAddress(), sheet.getActiveCell());
 
-        B1.setAsActiveCell();
-        assertEquals(B1.getAddress(), sheet.getActiveCell());
-        
-        wb.close();
+            B1.setAsActiveCell();
+            assertEquals(B1.getAddress(), sheet.getActiveCell());
+        }
     }
 
     @Test
     public void getCellComment() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-        CreationHelper factory = wb.getCreationHelper();
-        Row row = sheet.createRow(0);
-        Cell cell = row.createCell(1);
-        
-        // cell does not have a comment
-        assertNull(cell.getCellComment());
-        // add a cell comment
-        ClientAnchor anchor = factory.createClientAnchor();
-        anchor.setCol1(cell.getColumnIndex());
-        anchor.setCol2(cell.getColumnIndex()+1);
-        anchor.setRow1(row.getRowNum());
-        anchor.setRow2(row.getRowNum()+3);
-
-        Drawing<?> drawing = sheet.createDrawingPatriarch();
-        Comment comment = drawing.createCellComment(anchor);
-        RichTextString str = factory.createRichTextString("Hello, World!");
-        comment.setString(str);
-        comment.setAuthor("Apache POI");
-        cell.setCellComment(comment);
-        // ideally assertSame, but XSSFCell creates a new XSSFCellComment wrapping the same bean for every call to getCellComment.
-        assertEquals(comment, cell.getCellComment());
-
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+            CreationHelper factory = wb.getCreationHelper();
+            Row row = sheet.createRow(0);
+            Cell cell = row.createCell(1);
+
+            // cell does not have a comment
+            assertNull(cell.getCellComment());
+
+            // add a cell comment
+            ClientAnchor anchor = factory.createClientAnchor();
+            anchor.setCol1(cell.getColumnIndex());
+            anchor.setCol2(cell.getColumnIndex() + 1);
+            anchor.setRow1(row.getRowNum());
+            anchor.setRow2(row.getRowNum() + 3);
+
+            Drawing<?> drawing = sheet.createDrawingPatriarch();
+            Comment comment = drawing.createCellComment(anchor);
+            RichTextString str = factory.createRichTextString("Hello, World!");
+            comment.setString(str);
+            comment.setAuthor("Apache POI");
+            cell.setCellComment(comment);
+            // ideally assertSame, but XSSFCell creates a new XSSFCellComment wrapping the same bean for every call to getCellComment.
+            assertEquals(comment, cell.getCellComment());
+        }
     }
 
     @Test
@@ -1080,33 +1076,32 @@ public abstract class BaseTestCell {
 
     @Test
     public void testSetNullValues() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Cell cell = wb.createSheet("test").createRow(0).createCell(0);
-
-        cell.setCellValue((Calendar)null);
-        assertEquals(CellType.BLANK, cell.getCellType());
-        assertEquals("", cell.getStringCellValue());
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Cell cell = wb.createSheet("test").createRow(0).createCell(0);
 
-        cell.setCellValue((Date)null);
-        assertEquals(CellType.BLANK, cell.getCellType());
-        assertEquals("", cell.getStringCellValue());
+            cell.setCellValue((Calendar) null);
+            assertEquals(CellType.BLANK, cell.getCellType());
+            assertEquals("", cell.getStringCellValue());
 
-        cell.setCellValue((String)null);
-        assertEquals(CellType.BLANK, cell.getCellType());
-        assertEquals("", cell.getStringCellValue());
+            cell.setCellValue((Date) null);
+            assertEquals(CellType.BLANK, cell.getCellType());
+            assertEquals("", cell.getStringCellValue());
 
-        assertEquals(CellType.BLANK, cell.getCellType());
-        assertEquals("", cell.getStringCellValue());
+            cell.setCellValue((String) null);
+            assertEquals(CellType.BLANK, cell.getCellType());
+            assertEquals("", cell.getStringCellValue());
 
-        cell.setCellValue((RichTextString) null);
-        assertEquals(CellType.BLANK, cell.getCellType());
-        assertEquals("", cell.getStringCellValue());
+            assertEquals(CellType.BLANK, cell.getCellType());
+            assertEquals("", cell.getStringCellValue());
 
-        cell.setCellValue((String)null);
-        assertEquals(CellType.BLANK, cell.getCellType());
-        assertEquals("", cell.getStringCellValue());
+            cell.setCellValue((RichTextString) null);
+            assertEquals(CellType.BLANK, cell.getCellType());
+            assertEquals("", cell.getStringCellValue());
 
-        wb.close();
+            cell.setCellValue((String) null);
+            assertEquals(CellType.BLANK, cell.getCellType());
+            assertEquals("", cell.getStringCellValue());
+        }
     }
 
     @Test
@@ -1140,18 +1135,22 @@ public abstract class BaseTestCell {
     }
 
     @Test
-    public void testGetNumericCellValueOnABlankCellReturnsZero() {
-        Cell cell = _testDataProvider.createWorkbook().createSheet().createRow(0).createCell(0);
-        assertEquals(CellType.BLANK, cell.getCellType());
-        assertEquals(0, cell.getNumericCellValue(), 0);
+    public void testGetNumericCellValueOnABlankCellReturnsZero() throws IOException {
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Cell cell = workbook.createSheet().createRow(0).createCell(0);
+            assertEquals(CellType.BLANK, cell.getCellType());
+            assertEquals(0, cell.getNumericCellValue(), 0);
+        }
     }
 
     @Test
-    public void getDateCellValue_returnsNull_onABlankCell() {
-        Cell cell = _testDataProvider.createWorkbook().createSheet().createRow(0).createCell(0);
-        assertEquals(CellType.BLANK, cell.getCellType());
-        Date result = cell.getDateCellValue();
-        assertNull(result);
+    public void getDateCellValue_returnsNull_onABlankCell() throws IOException {
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Cell cell = workbook.createSheet().createRow(0).createCell(0);
+            assertEquals(CellType.BLANK, cell.getCellType());
+            Date result = cell.getDateCellValue();
+            assertNull(result);
+        }
     }
 
     @Test
@@ -1188,31 +1187,37 @@ public abstract class BaseTestCell {
     }
 
     @Test
-    public void setStringCellValueWithRichTextString_ifThrows_shallNotChangeCell() {
-        Cell cell = _testDataProvider.createWorkbook().createSheet().createRow(0).createCell(0);
+    public void setStringCellValueWithRichTextString_ifThrows_shallNotChangeCell() throws IOException {
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Cell cell = workbook.createSheet().createRow(0).createCell(0);
 
-        final double value = 2.78;
-        cell.setCellValue(value);
-        assertEquals(CellType.NUMERIC, cell.getCellType());
+            final double value = 2.78;
+            cell.setCellValue(value);
+            assertEquals(CellType.NUMERIC, cell.getCellType());
 
-        int badLength = cell.getSheet().getWorkbook().getSpreadsheetVersion().getMaxTextLength() + 1;
-        RichTextString badStringValue = cell.getSheet().getWorkbook().getCreationHelper().
-                createRichTextString(new String(new byte[badLength], StandardCharsets.UTF_8));
+            int badLength = cell.getSheet().getWorkbook().getSpreadsheetVersion().getMaxTextLength() + 1;
+            RichTextString badStringValue = cell.getSheet().getWorkbook().getCreationHelper().
+                    createRichTextString(new String(new byte[badLength], StandardCharsets.UTF_8));
 
-        try {
-            cell.setCellValue(badStringValue);
-        } catch (IllegalArgumentException e) {
-            // no-op, expected to throw but we need to assert something more
-        }
+            try {
+                cell.setCellValue(badStringValue);
+            } catch (IllegalArgumentException e) {
+                // no-op, expected to throw but we need to assert something more
+            }
 
-        assertEquals(CellType.NUMERIC, cell.getCellType());
-        assertEquals(value, cell.getNumericCellValue(), 0);
+            assertEquals(CellType.NUMERIC, cell.getCellType());
+            assertEquals(value, cell.getNumericCellValue(), 0);
+        }
     }
 
     @Test(expected = IllegalArgumentException.class)
-    public void setCellType_null_throwsIAE() {
+    public void setCellType_null_throwsIAE() throws IOException {
         Cell cell = getInstance();
-        cell.setCellType(null);
+        try {
+            cell.setCellType(null);
+        } finally {
+            cell.getSheet().getWorkbook().close();
+        }
     }
 
     @Test(expected = IllegalArgumentException.class)
@@ -1246,14 +1251,18 @@ public abstract class BaseTestCell {
     }
 
     @Test(expected = IllegalStateException.class)
-    public void setCellFormula_throwsISE_ifCellIsPartOfAnArrayFormulaGroupContainingOtherCells() {
+    public void setCellFormula_throwsISE_ifCellIsPartOfAnArrayFormulaGroupContainingOtherCells() throws IOException {
         Cell cell = getInstance();
 
-        cell.getSheet().setArrayFormula("1", CellRangeAddress.valueOf("A1:B1"));
-        assertTrue(cell.isPartOfArrayFormulaGroup());
-        assertEquals(CellType.FORMULA, cell.getCellType());
+        try {
+            cell.getSheet().setArrayFormula("1", CellRangeAddress.valueOf("A1:B1"));
+            assertTrue(cell.isPartOfArrayFormulaGroup());
+            assertEquals(CellType.FORMULA, cell.getCellType());
 
-        cell.setCellFormula("1");
+            cell.setCellFormula("1");
+        } finally {
+            cell.getSheet().getWorkbook().close();
+        }
     }
 
     @Test
@@ -1311,23 +1320,25 @@ public abstract class BaseTestCell {
     }
 
     @Test
-    public void setCellFormula_onABlankCell_setsValueToZero() {
+    public void setCellFormula_onABlankCell_setsValueToZero() throws IOException {
         Cell cell = getInstance();
         cell.setCellFormula("\"foo\"");
         assertEquals(CellType.FORMULA, cell.getCellType());
         assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType());
         assertEquals(0, cell.getNumericCellValue(), 0);
+        cell.getSheet().getWorkbook().close();
     }
 
 
     @Test
-    public void setCellFormula_onANonBlankCell_preservesTheValue() {
+    public void setCellFormula_onANonBlankCell_preservesTheValue() throws IOException {
         Cell cell = getInstance();
         cell.setCellValue(true);
         cell.setCellFormula("\"foo\"");
         assertEquals(CellType.FORMULA, cell.getCellType());
         assertEquals(CellType.BOOLEAN, cell.getCachedFormulaResultType());
         assertTrue(cell.getBooleanCellValue());
+        cell.getSheet().getWorkbook().close();
     }
 
     @Test