]> source.dussan.org Git - poi.git/commitdiff
Add missing close() of resources in both production code and tests
authorDominik Stadler <centic@apache.org>
Sun, 28 Dec 2014 09:16:57 +0000 (09:16 +0000)
committerDominik Stadler <centic@apache.org>
Sun, 28 Dec 2014 09:16:57 +0000 (09:16 +0000)
Use revert() instead of close() on OCPPackage in some places to not re-write the file unnecessarily.
This should now run tests without leftover file handles when checked with file leak detector and
allows to find newly introduced cases more easily.

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1648160 13f79535-47bb-0310-9956-ffa450edef68

27 files changed:
src/ooxml/java/org/apache/poi/POIXMLTextExtractor.java
src/ooxml/java/org/apache/poi/ss/usermodel/WorkbookFactory.java
src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFNotesMaster.java
src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFWorkbook.java
src/ooxml/testcases/org/apache/poi/TestDetectAsOOXML.java
src/ooxml/testcases/org/apache/poi/TestPOIXMLDocument.java
src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java
src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java
src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java
src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java
src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java
src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSignatureInfo.java
src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java
src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java
src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentEncryption.java
src/testcases/org/apache/poi/hpsf/basic/TestBasic.java
src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java
src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java
src/testcases/org/apache/poi/hpsf/basic/Util.java
src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java
src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java
src/testcases/org/apache/poi/poifs/filesystem/TestOffice2007XMLException.java
src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java
src/testcases/org/apache/poi/poifs/nio/TestDataSource.java
src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java

index eeb03f7aad15827d6dbff034b9673cc69c7be20d..3a600f48a963f4e67780944b5b67eafd41de78b8 100644 (file)
@@ -84,7 +84,8 @@ public abstract class POIXMLTextExtractor extends POITextExtractor {
                if(_document != null) {
                        OPCPackage pkg = _document.getPackage();
                        if(pkg != null) {
-                               pkg.close();
+                           // revert the package to not re-write the file, which is very likely not wanted for a TextExtractor!
+                               pkg.revert();
                        }
                }
                super.close();
index dae4ff36ed59c8deb7d601ce78103c6159571fcc..de847fd19a57a2f71ab12ad5c12ce89792baba76 100644 (file)
@@ -107,7 +107,23 @@ public class WorkbookFactory {
         } catch(OfficeXmlFileException e) {
             // opening as .xls failed => try opening as .xlsx
             OPCPackage pkg = OPCPackage.open(file);
-            return new XSSFWorkbook(pkg);
+            try {
+                return new XSSFWorkbook(pkg);
+            } catch (IOException ioe) {
+                // ensure that file handles are closed (use revert() to not re-write the file)
+                pkg.revert();
+                //pkg.close();
+                
+                // rethrow exception
+                throw ioe;
+            } catch (IllegalArgumentException ioe) {
+                // ensure that file handles are closed (use revert() to not re-write the file) 
+                pkg.revert();
+                //pkg.close();
+                
+                // rethrow exception
+                throw ioe;
+            }
         }
     }
 }
index 7ea875d36e39251af606449ab5fe11252b28fc23..40937e87858daf36c944412b47d94ac1b6db3498 100644 (file)
@@ -70,9 +70,13 @@ import org.openxmlformats.schemas.presentationml.x2006.main.NotesMasterDocument;
         }        
 
         try {
-            NotesMasterDocument doc = NotesMasterDocument.Factory.parse(is);
-            CTNotesMaster slide =  doc.getNotesMaster();
-            return slide;
+            try {
+                NotesMasterDocument doc = NotesMasterDocument.Factory.parse(is);
+                CTNotesMaster slide =  doc.getNotesMaster();
+                return slide;
+            } finally {
+                is.close();
+            }            
         } catch (Exception e) {
             throw new POIXMLException("Can't initialize NotesMaster", e);
         }
index e3afdc5c02be07dabc6ccead2189c342ba6cbeec..87d8847bdec27024bf9a872ed3a61f30fea1d240 100644 (file)
@@ -312,7 +312,16 @@ public class SXSSFWorkbook implements Workbook
     void deregisterSheetMapping(XSSFSheet xSheet)
     {
         SXSSFSheet sxSheet=getSXSSFSheet(xSheet);
+        
+        // ensure that the writer is closed in all cases to not have lingering writers
+        try {
+            sxSheet.getSheetDataWriter().close();
+        } catch (IOException e) {
+            // ignore exception here
+        }
+        
         _sxFromXHash.remove(sxSheet);
+
         _xFromSxHash.remove(xSheet);
     }
     private XSSFSheet getSheetFromZipEntryName(String sheetRef)
@@ -827,6 +836,17 @@ public class SXSSFWorkbook implements Workbook
      */
     @Override
     public void close() throws IOException {
+        // ensure that any lingering writer is closed
+        for (SXSSFSheet sheet : _xFromSxHash.values())
+        {
+            try {
+                sheet.getSheetDataWriter().close();
+            } catch (IOException e) {
+                // ignore exception here
+            }
+        }
+
+        
         // Tell the base workbook to close, does nothing if 
         //  it's a newly created one
         _wb.close();
index 2461f463ddd25a7c821109194186ffae1a3f99cf..4ea22134188be96de552d2139ce10ce95eec8619 100644 (file)
 
 package org.apache.poi;
 
+import java.io.InputStream;
+import java.io.PushbackInputStream;
+
 import junit.framework.TestCase;
-import java.io.*;
 
 import org.apache.poi.hssf.HSSFTestDataSamples;
 import org.apache.poi.openxml4j.opc.OPCPackage;
@@ -44,17 +46,20 @@ public class TestDetectAsOOXML extends TestCase
                                HSSFTestDataSamples.openSampleFileStream("SampleSS.xlsx"), 10
                );
                assertTrue(POIXMLDocument.hasOOXMLHeader(in));
+               in.close();
                
                // xls file isn't
                in = new PushbackInputStream(
                                HSSFTestDataSamples.openSampleFileStream("SampleSS.xls"), 10
                );
                assertFalse(POIXMLDocument.hasOOXMLHeader(in));
+               in.close();
                
                // text file isn't
                in = new PushbackInputStream(
                                HSSFTestDataSamples.openSampleFileStream("SampleSS.txt"), 10
                );
                assertFalse(POIXMLDocument.hasOOXMLHeader(in));
+               in.close();
        }
 }
index 3aca24f36ca610f20cd88ab303a66b275d50c1e3..f4e39ab6588ca165a639eb845d444634a6f601c1 100644 (file)
@@ -105,29 +105,32 @@ public final class TestPOIXMLDocument extends TestCase {
         out.close();
 
         OPCPackage pkg2 = OPCPackage.open(tmp.getAbsolutePath());
-
-        doc = new OPCParser(pkg1);
-        doc.parse(new TestFactory());
-        context = new HashMap<String,POIXMLDocumentPart>();
-        traverse(doc, context);
-        context.clear();
-
-        assertEquals(pkg1.getRelationships().size(), pkg2.getRelationships().size());
-
-        ArrayList<PackagePart> l1 = pkg1.getParts();
-        ArrayList<PackagePart> l2 = pkg2.getParts();
-
-        assertEquals(l1.size(), l2.size());
-        for (int i=0; i < l1.size(); i++){
-            PackagePart p1 = l1.get(i);
-            PackagePart p2 = l2.get(i);
-
-            assertEquals(p1.getContentType(), p2.getContentType());
-            assertEquals(p1.hasRelationships(), p2.hasRelationships());
-            if(p1.hasRelationships()){
-                assertEquals(p1.getRelationships().size(), p2.getRelationships().size());
+        try {
+            doc = new OPCParser(pkg1);
+            doc.parse(new TestFactory());
+            context = new HashMap<String,POIXMLDocumentPart>();
+            traverse(doc, context);
+            context.clear();
+    
+            assertEquals(pkg1.getRelationships().size(), pkg2.getRelationships().size());
+    
+            ArrayList<PackagePart> l1 = pkg1.getParts();
+            ArrayList<PackagePart> l2 = pkg2.getParts();
+    
+            assertEquals(l1.size(), l2.size());
+            for (int i=0; i < l1.size(); i++){
+                PackagePart p1 = l1.get(i);
+                PackagePart p2 = l2.get(i);
+    
+                assertEquals(p1.getContentType(), p2.getContentType());
+                assertEquals(p1.hasRelationships(), p2.hasRelationships());
+                if(p1.hasRelationships()){
+                    assertEquals(p1.getRelationships().size(), p2.getRelationships().size());
+                }
+                assertEquals(p1.getPartName(), p2.getPartName());
             }
-            assertEquals(p1.getPartName(), p2.getPartName());
+        } finally {
+            pkg2.close();
         }
     }
 
@@ -156,6 +159,7 @@ public final class TestPOIXMLDocument extends TestCase {
 
         for(POIXMLDocumentPart rel : doc.getRelations()){
             //TODO finish me
+            assertNotNull(rel);
         }
 
     }
index cffd372e6e039a31f47d18838b7b2eeeb9aa6b56..7f79afaad3c2529f235326e647545ac6d1d7b3dc 100644 (file)
@@ -25,6 +25,7 @@ import junit.framework.TestCase;
 import org.apache.poi.POIDataSamples;
 import org.apache.poi.POIOLE2TextExtractor;
 import org.apache.poi.POITextExtractor;
+import org.apache.poi.POIXMLTextExtractor;
 import org.apache.poi.hdgf.extractor.VisioTextExtractor;
 import org.apache.poi.hpbf.extractor.PublisherTextExtractor;
 import org.apache.poi.hslf.extractor.PowerPointExtractor;
@@ -35,6 +36,7 @@ import org.apache.poi.hwpf.extractor.Word6Extractor;
 import org.apache.poi.hwpf.extractor.WordExtractor;
 import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
 import org.apache.poi.openxml4j.opc.OPCPackage;
+import org.apache.poi.openxml4j.opc.PackageAccess;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor;
 import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor;
@@ -128,22 +130,33 @@ public class TestExtractorFactory extends TestCase {
       assertTrue(
             xlsExtractor.getText().length() > 200
       );
+      xlsExtractor.close();
 
+      POITextExtractor extractor = ExtractorFactory.createExtractor(xlsx);
       assertTrue(
-            ExtractorFactory.createExtractor(xlsx)
+            extractor
             instanceof XSSFExcelExtractor
       );
+      extractor.close();
+
+      extractor = ExtractorFactory.createExtractor(xlsx);
       assertTrue(
-            ExtractorFactory.createExtractor(xlsx).getText().length() > 200
+            extractor.getText().length() > 200
       );
+      extractor.close();
 
+      extractor = ExtractorFactory.createExtractor(xltx);
       assertTrue(
-            ExtractorFactory.createExtractor(xltx)
+            extractor
             instanceof XSSFExcelExtractor
       );
+      extractor.close();
+
+      extractor = ExtractorFactory.createExtractor(xltx);
       assertTrue(
-            ExtractorFactory.createExtractor(xltx).getText().contains("test")
+            extractor.getText().contains("test")
       );
+      extractor.close();
 
 
       // Word
@@ -171,22 +184,29 @@ public class TestExtractorFactory extends TestCase {
             ExtractorFactory.createExtractor(doc95).getText().length() > 120
       );
           
-        
+      extractor = ExtractorFactory.createExtractor(docx);
       assertTrue(
-            ExtractorFactory.createExtractor(docx)
-            instanceof XWPFWordExtractor
+            extractor instanceof XWPFWordExtractor
       );
+      extractor.close();
+      
+      extractor = ExtractorFactory.createExtractor(docx);
       assertTrue(
-            ExtractorFactory.createExtractor(docx).getText().length() > 120
+            extractor.getText().length() > 120
       );
+      extractor.close();
 
+      extractor = ExtractorFactory.createExtractor(dotx);
       assertTrue(
-            ExtractorFactory.createExtractor(dotx)
-            instanceof XWPFWordExtractor
+            extractor instanceof XWPFWordExtractor
       );
+      extractor.close();
+      
+      extractor = ExtractorFactory.createExtractor(dotx);
       assertTrue(
-            ExtractorFactory.createExtractor(dotx).getText().contains("Test")
+            extractor.getText().contains("Test")
       );
+      extractor.close();
 
       // PowerPoint
       assertTrue(
@@ -197,13 +217,18 @@ public class TestExtractorFactory extends TestCase {
             ExtractorFactory.createExtractor(ppt).getText().length() > 120
       );
 
+      extractor = ExtractorFactory.createExtractor(pptx);
       assertTrue(
-            ExtractorFactory.createExtractor(pptx)
+            extractor
             instanceof XSLFPowerPointExtractor
       );
+      extractor.close();
+
+      extractor = ExtractorFactory.createExtractor(pptx);
       assertTrue(
-            ExtractorFactory.createExtractor(pptx).getText().length() > 120
+            extractor.getText().length() > 120
       );
+      extractor.close();
 
       // Visio
       assertTrue(
@@ -338,8 +363,13 @@ public class TestExtractorFactory extends TestCase {
                
                // Text
                try {
-                       ExtractorFactory.createExtractor(new FileInputStream(txt));
-                       fail();
+                       FileInputStream stream = new FileInputStream(txt);
+                       try {
+                ExtractorFactory.createExtractor(stream);
+                       fail();
+                       } finally {
+                           stream.close();
+                       }
                } catch(IllegalArgumentException e) {
                        // Good
                }
@@ -427,31 +457,43 @@ public class TestExtractorFactory extends TestCase {
        
        public void testPackage() throws Exception {
                // Excel
-               assertTrue(
-                               ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString()))
+               POIXMLTextExtractor extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString(), PackageAccess.READ));
+        assertTrue(
+                               extractor
                                instanceof XSSFExcelExtractor
                );
-               assertTrue(
-                               ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())).getText().length() > 200
-               );
+        extractor.close();
+               extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString()));
+        assertTrue(extractor.getText().length() > 200);
+        extractor.close();
                
                // Word
-               assertTrue(
-                               ExtractorFactory.createExtractor(OPCPackage.open(docx.toString()))
+               extractor = ExtractorFactory.createExtractor(OPCPackage.open(docx.toString()));
+        assertTrue(
+                               extractor
                                instanceof XWPFWordExtractor
                );
-               assertTrue(
-                               ExtractorFactory.createExtractor(OPCPackage.open(docx.toString())).getText().length() > 120
+        extractor.close();
+        
+               extractor = ExtractorFactory.createExtractor(OPCPackage.open(docx.toString()));
+        assertTrue(
+                               extractor.getText().length() > 120
                );
+        extractor.close();
                
                // PowerPoint
-               assertTrue(
-                               ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString()))
+               extractor = ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString()));
+        assertTrue(
+                               extractor
                                instanceof XSLFPowerPointExtractor
                );
-               assertTrue(
-                               ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString())).getText().length() > 120
+        extractor.close();
+
+               extractor = ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString()));
+        assertTrue(
+                               extractor.getText().length() > 120
                );
+        extractor.close();
                
                // Text
                try {
@@ -487,21 +529,27 @@ public class TestExtractorFactory extends TestCase {
       
       
       // Check we get the right extractors now
+      POITextExtractor extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)));
       assertTrue(
-            ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)))
+            extractor
             instanceof EventBasedExcelExtractor
       );
+      extractor.close();
+      extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)));
       assertTrue(
-            ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls))).getText().length() > 200
+            extractor.getText().length() > 200
       );
+      extractor.close();
       
+      extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString(), PackageAccess.READ));
+      assertTrue(extractor instanceof XSSFEventBasedExcelExtractor);
+      extractor.close();
+
+      extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString(), PackageAccess.READ));
       assertTrue(
-            ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString()))
-            instanceof XSSFEventBasedExcelExtractor
-      );
-      assertTrue(
-            ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())).getText().length() > 200
+            extractor.getText().length() > 200
       );
+      extractor.close();
       
       
       // Put back to normal
@@ -511,21 +559,29 @@ public class TestExtractorFactory extends TestCase {
       assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors());
       
       // And back
+      extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)));
       assertTrue(
-            ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)))
+            extractor
             instanceof ExcelExtractor
       );
+      extractor.close();
+      extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)));
       assertTrue(
-            ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls))).getText().length() > 200
+            extractor.getText().length() > 200
       );
+      extractor.close();
       
+      extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString(), PackageAccess.READ));
       assertTrue(
-            ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString()))
+            extractor
             instanceof XSSFExcelExtractor
       );
+      extractor.close();
+      extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString()));
       assertTrue(
-            ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())).getText().length() > 200
+            extractor.getText().length() > 200
       );
+      extractor.close();
        }
 
    /**
index c42ce63d4397c15edc70a1f346583ea75552add8..07a2b333d65faec8b9c2834a11a8063099f4935a 100644 (file)
@@ -58,12 +58,17 @@ public final class TestPackage extends TestCase {
                File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
 
                OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
-               p.save(targetFile.getAbsoluteFile());
-
-               // Compare the original and newly saved document
-               assertTrue(targetFile.exists());
-               ZipFileAssert.assertEquals(new File(originalFile), targetFile);
-               assertTrue(targetFile.delete());
+               try {
+               p.save(targetFile.getAbsoluteFile());
+    
+               // Compare the original and newly saved document
+               assertTrue(targetFile.exists());
+               ZipFileAssert.assertEquals(new File(originalFile), targetFile);
+               assertTrue(targetFile.delete());
+               } finally {
+            // use revert to not re-write the input file
+            p.revert();
+               }
        }
 
        /**
@@ -168,6 +173,8 @@ public final class TestPackage extends TestCase {
         PackageRelationship rel =
                 corePart.addRelationship(sheetPartName, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", "rSheet1");
         PackagePart part = pkg.createPart(sheetPartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml");
+        assertNotNull(part);
+
         // Dummy content again
         coreOut = corePart.getOutputStream();
         coreOut.write("<dummy-xml2 />".getBytes());
@@ -189,28 +196,35 @@ public final class TestPackage extends TestCase {
         // Save and re-load
         pkg.close();
         File tmp = TempFile.createTempFile("testCreatePackageWithCoreDocument", ".zip");
-            FileOutputStream fout = new FileOutputStream(tmp);
-        fout.write(baos.toByteArray());
-        fout.close();
+        OutputStream fout = new FileOutputStream(tmp);
+        try {
+            fout.write(baos.toByteArray());
+        } finally {
+            fout.close();
+        }
         pkg = OPCPackage.open(tmp.getPath());
         //tmp.delete();
 
-        // Check still right
-        coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
-        assertEquals(1, coreRels.size());
-        coreRel = coreRels.getRelationship(0);
-
-        assertEquals("/", coreRel.getSourceURI().toString());
-        assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString());
-        corePart = pkg.getPart(coreRel);
-        assertNotNull(corePart);
-
-        PackageRelationshipCollection rels = corePart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
-        assertEquals(1, rels.size());
-        rel = rels.getRelationship(0);
-        assertEquals("Sheet1!A1", rel.getTargetURI().getRawFragment());
-
-        assertMSCompatibility(pkg);
+        try {
+            // Check still right
+            coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
+            assertEquals(1, coreRels.size());
+            coreRel = coreRels.getRelationship(0);
+    
+            assertEquals("/", coreRel.getSourceURI().toString());
+            assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString());
+            corePart = pkg.getPart(coreRel);
+            assertNotNull(corePart);
+    
+            PackageRelationshipCollection rels = corePart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
+            assertEquals(1, rels.size());
+            rel = rels.getRelationship(0);
+            assertEquals("Sheet1!A1", rel.getTargetURI().getRawFragment());
+    
+            assertMSCompatibility(pkg);
+        } finally {
+            pkg.close();
+        }
     }
 
     private void assertMSCompatibility(OPCPackage pkg) throws Exception {
@@ -297,14 +311,22 @@ public final class TestPackage extends TestCase {
                File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
 
                OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
-               FileOutputStream fout = new FileOutputStream(targetFile);
-               p.save(fout);
-               fout.close();
-
-               // Compare the original and newly saved document
-               assertTrue(targetFile.exists());
-               ZipFileAssert.assertEquals(new File(originalFile), targetFile);
-               assertTrue(targetFile.delete());
+               try {
+               FileOutputStream fout = new FileOutputStream(targetFile);
+               try {
+                   p.save(fout);
+               } finally {
+                   fout.close();
+               }
+    
+               // Compare the original and newly saved document
+               assertTrue(targetFile.exists());
+               ZipFileAssert.assertEquals(new File(originalFile), targetFile);
+               assertTrue(targetFile.delete());
+               } finally {
+                   // use revert to not re-write the input file
+                   p.revert();
+               }
        }
 
        /**
@@ -511,48 +533,56 @@ public final class TestPackage extends TestCase {
         String filepath =  OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
 
         OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
-        List<PackagePart> rs =  pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml"));
-        HashMap<String, PackagePart>  selected = new HashMap<String, PackagePart>();
-
-        for(PackagePart p : rs)
-            selected.put(p.getPartName().getName(), p);
-
-        assertEquals(6, selected.size());
-        assertTrue(selected.containsKey("/word/document.xml"));
-        assertTrue(selected.containsKey("/word/fontTable.xml"));
-        assertTrue(selected.containsKey("/word/settings.xml"));
-        assertTrue(selected.containsKey("/word/styles.xml"));
-        assertTrue(selected.containsKey("/word/theme/theme1.xml"));
-        assertTrue(selected.containsKey("/word/webSettings.xml"));
+        try {
+            List<PackagePart> rs =  pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml"));
+            HashMap<String, PackagePart>  selected = new HashMap<String, PackagePart>();
+    
+            for(PackagePart p : rs)
+                selected.put(p.getPartName().getName(), p);
+    
+            assertEquals(6, selected.size());
+            assertTrue(selected.containsKey("/word/document.xml"));
+            assertTrue(selected.containsKey("/word/fontTable.xml"));
+            assertTrue(selected.containsKey("/word/settings.xml"));
+            assertTrue(selected.containsKey("/word/styles.xml"));
+            assertTrue(selected.containsKey("/word/theme/theme1.xml"));
+            assertTrue(selected.containsKey("/word/webSettings.xml"));
+        } finally {
+            // use revert to not re-write the input file
+            pkg.revert();
+        }
     }
     
     public void testGetPartSize() throws Exception {
        String filepath =  OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
        OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ);
-
-       int checked = 0;
-       for (PackagePart part : pkg.getParts()) {
-          // Can get the size of zip parts
-          if (part.getPartName().getName().equals("/word/document.xml")) {
-             checked++;
-             assertEquals(ZipPackagePart.class, part.getClass());
-             assertEquals(6031l, part.getSize());
-          }
-          if (part.getPartName().getName().equals("/word/fontTable.xml")) {
-             checked++;
-             assertEquals(ZipPackagePart.class, part.getClass());
-             assertEquals(1312l, part.getSize());
-          }
-          
-          // But not from the others
-          if (part.getPartName().getName().equals("/docProps/core.xml")) {
-             checked++;
-             assertEquals(PackagePropertiesPart.class, part.getClass());
-             assertEquals(-1, part.getSize());
-          }
+       try {
+           int checked = 0;
+           for (PackagePart part : pkg.getParts()) {
+              // Can get the size of zip parts
+              if (part.getPartName().getName().equals("/word/document.xml")) {
+                 checked++;
+                 assertEquals(ZipPackagePart.class, part.getClass());
+                 assertEquals(6031l, part.getSize());
+              }
+              if (part.getPartName().getName().equals("/word/fontTable.xml")) {
+                 checked++;
+                 assertEquals(ZipPackagePart.class, part.getClass());
+                 assertEquals(1312l, part.getSize());
+              }
+              
+              // But not from the others
+              if (part.getPartName().getName().equals("/docProps/core.xml")) {
+                 checked++;
+                 assertEquals(PackagePropertiesPart.class, part.getClass());
+                 assertEquals(-1, part.getSize());
+              }
+           }
+           // Ensure we actually found the parts we want to check
+           assertEquals(3, checked);
+       } finally {
+           pkg.close();
        }
-       // Ensure we actually found the parts we want to check
-       assertEquals(3, checked);
     }
 
     public void testReplaceContentType() throws Exception {
index 0cf3efa53c701cd89bbc76dcd21e2dc19b290a1b..ddc36af0be9ba9c2889d832fba9216b53fa702ca 100644 (file)
@@ -70,37 +70,45 @@ public final class TestPackageCoreProperties extends TestCase {
 
                // Open package
                OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE);
-
-               SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
-        df.setTimeZone(TimeZone.getTimeZone("UTC"));
-               Date dateToInsert = df.parse("2007-05-12T08:00:00Z", new ParsePosition(
-                               0));
-
-               PackageProperties props = p.getPackageProperties();
-               props.setCategoryProperty("MyCategory");
-               props.setContentStatusProperty("MyContentStatus");
-               props.setContentTypeProperty("MyContentType");
-               props.setCreatedProperty(new Nullable<Date>(dateToInsert));
-               props.setCreatorProperty("MyCreator");
-               props.setDescriptionProperty("MyDescription");
-               props.setIdentifierProperty("MyIdentifier");
-               props.setKeywordsProperty("MyKeywords");
-               props.setLanguageProperty("MyLanguage");
-               props.setLastModifiedByProperty("Julien Chable");
-               props.setLastPrintedProperty(new Nullable<Date>(dateToInsert));
-               props.setModifiedProperty(new Nullable<Date>(dateToInsert));
-               props.setRevisionProperty("2");
-               props.setTitleProperty("MyTitle");
-               props.setSubjectProperty("MySubject");
-               props.setVersionProperty("2");
-               // Save the package in the output directory
-               p.save(outputFile);
-
-               // Open the newly created file to check core properties saved values.
-               OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ);
-               compareProperties(p2);
-               p2.revert();
-               outputFile.delete();
+               try {
+               SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
+            df.setTimeZone(TimeZone.getTimeZone("UTC"));
+               Date dateToInsert = df.parse("2007-05-12T08:00:00Z", new ParsePosition(
+                               0));
+    
+               PackageProperties props = p.getPackageProperties();
+               props.setCategoryProperty("MyCategory");
+               props.setContentStatusProperty("MyContentStatus");
+               props.setContentTypeProperty("MyContentType");
+               props.setCreatedProperty(new Nullable<Date>(dateToInsert));
+               props.setCreatorProperty("MyCreator");
+               props.setDescriptionProperty("MyDescription");
+               props.setIdentifierProperty("MyIdentifier");
+               props.setKeywordsProperty("MyKeywords");
+               props.setLanguageProperty("MyLanguage");
+               props.setLastModifiedByProperty("Julien Chable");
+               props.setLastPrintedProperty(new Nullable<Date>(dateToInsert));
+               props.setModifiedProperty(new Nullable<Date>(dateToInsert));
+               props.setRevisionProperty("2");
+               props.setTitleProperty("MyTitle");
+               props.setSubjectProperty("MySubject");
+               props.setVersionProperty("2");
+               // Save the package in the output directory
+               p.save(outputFile);
+    
+               // Open the newly created file to check core properties saved values.
+               OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ);
+               try {
+                   compareProperties(p2);
+                   p2.revert();
+               } finally {
+                   p2.close();
+               }
+               outputFile.delete();
+               } finally {
+            // use revert to not re-write the input file
+            p.revert();
+               }
        }
 
        private void compareProperties(OPCPackage p) throws InvalidFormatException {
index 01a44327c7b72335769cdea5bb2a394c91fc4b76..432bd896c99182d387897208e98e192b46c814ba 100644 (file)
@@ -42,16 +42,24 @@ public final class TestPackageThumbnail extends TestCase {
 
                // Open package
                OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE);
-               p.addThumbnail(imagePath);
-               // Save the package in the output directory
-               p.save(outputFile);
-
-               // Open the newly created file to check core properties saved values.
-               OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ);
-               if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL)
-                               .size() == 0)
-                       fail("Thumbnail not added to the package !");
-               p2.revert();
-               outputFile.delete();
+               try {
+               p.addThumbnail(imagePath);
+               // Save the package in the output directory
+               p.save(outputFile);
+    
+               // Open the newly created file to check core properties saved values.
+               OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ);
+               try {
+                       if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL)
+                                       .size() == 0)
+                               fail("Thumbnail not added to the package !");
+               } finally {
+                   p2.revert();
+                   p2.close();
+               }
+               } finally {
+                   p.revert();
+                   outputFile.delete();
+               }
        }
 }
index cdd74c07ac1816234eec8152976fae243d1d67ac..cf485ed1f6d04e88bad9035613713b559ea59537 100644 (file)
@@ -188,7 +188,11 @@ public class TestRelationships extends TestCase {
            // Write out and re-load
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            pkg.save(baos);
-           ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+        
+           // use revert to not re-write the input file
+        pkg.revert();
+
+        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            pkg = OPCPackage.open(bais);
            
            // Check again
@@ -280,7 +284,6 @@ public class TestRelationships extends TestCase {
 
 
     public void testTargetWithSpecialChars() throws Exception{
-
         OPCPackage pkg;
 
         String filepath = OpenXML4JTestDataSamples.getSampleFileName("50154.xlsx");
@@ -289,6 +292,10 @@ public class TestRelationships extends TestCase {
 
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         pkg.save(baos);
+
+        // use revert to not re-write the input file
+        pkg.revert();
+
         ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
         pkg = OPCPackage.open(bais);
 
index fe7a91bc024dded2fa4a59b41738640d47137fa1..e469f9c3efef17ca49b5541f2cee22b4ca6e98fc 100644 (file)
@@ -114,12 +114,16 @@ public class TestSignatureInfo {
     @Test\r
     public void office2007prettyPrintedRels() throws Exception {\r
         OPCPackage pkg = OPCPackage.open(testdata.getFile("office2007prettyPrintedRels.docx"), PackageAccess.READ);\r
-        SignatureConfig sic = new SignatureConfig();\r
-        sic.setOpcPackage(pkg);\r
-        SignatureInfo si = new SignatureInfo();\r
-        si.setSignatureConfig(sic);\r
-        boolean isValid = si.verifySignature();\r
-        assertTrue(isValid);\r
+        try {\r
+            SignatureConfig sic = new SignatureConfig();\r
+            sic.setOpcPackage(pkg);\r
+            SignatureInfo si = new SignatureInfo();\r
+            si.setSignatureConfig(sic);\r
+            boolean isValid = si.verifySignature();\r
+            assertTrue(isValid);\r
+        } finally {\r
+            pkg.close();\r
+        }\r
     }\r
     \r
     @Test\r
index 9dee1a5c01e51e83edebe466f16a079fec5e6a22..28983ff6fa3e44457012080f835447b88b67e2ad 100644 (file)
@@ -17,6 +17,8 @@
 
 package org.apache.poi.ss;
 
+import java.io.InputStream;
+
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.hssf.HSSFTestDataSamples;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
@@ -47,6 +49,7 @@ public final class TestWorkbookFactory extends TestCase {
                );
                assertNotNull(wb);
                assertTrue(wb instanceof HSSFWorkbook);
+               wb.close();
 
                // Package -> xssf
                wb = WorkbookFactory.create(
@@ -55,6 +58,7 @@ public final class TestWorkbookFactory extends TestCase {
                );
                assertNotNull(wb);
                assertTrue(wb instanceof XSSFWorkbook);
+               // TODO: this re-writes the sample-file?! wb.close();
        }
 
        /**
@@ -71,12 +75,14 @@ public final class TestWorkbookFactory extends TestCase {
                );
                assertNotNull(wb);
                assertTrue(wb instanceof HSSFWorkbook);
+               wb.close();
 
                wb = WorkbookFactory.create(
                                HSSFTestDataSamples.openSampleFileStream(xlsx)
                );
                assertNotNull(wb);
                assertTrue(wb instanceof XSSFWorkbook);
+               // TODO: this re-writes the sample-file?! wb.close();
                
                // File -> either
       wb = WorkbookFactory.create(
@@ -84,18 +90,25 @@ public final class TestWorkbookFactory extends TestCase {
       );
       assertNotNull(wb);
       assertTrue(wb instanceof HSSFWorkbook);
+      wb.close();
 
       wb = WorkbookFactory.create(
             HSSFTestDataSamples.getSampleFile(xlsx)
       );
       assertNotNull(wb);
       assertTrue(wb instanceof XSSFWorkbook);
+      
+      // TODO: close() re-writes the sample-file?! Resort to revert() for now to close file handle...
+      ((XSSFWorkbook)wb).getPackage().revert();
 
                // Invalid type -> exception
                try {
-                       wb = WorkbookFactory.create(
-                                       HSSFTestDataSamples.openSampleFileStream(txt)
-                       );
+                       InputStream stream = HSSFTestDataSamples.openSampleFileStream(txt);
+                       try {
+                wb = WorkbookFactory.create(stream);
+                       } finally {
+                           stream.close();
+                       }
                        fail();
                } catch(IllegalArgumentException e) {
                        // Good
index f4d7781b19dbccbf364c4597ecfc9e809dc50fb8..2cf660955ed56c36a0cbbb985bde4292ed5803a7 100644 (file)
@@ -22,6 +22,8 @@ package org.apache.poi.xssf.streaming;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
 
+import java.io.IOException;
+
 import org.apache.poi.ss.usermodel.BaseTestSheet;
 import org.apache.poi.ss.usermodel.Sheet;
 import org.apache.poi.ss.usermodel.Workbook;
@@ -94,41 +96,49 @@ public class TestSXSSFSheet extends BaseTestSheet {
     }
 
     @Test
-    public void overrideFlushedRows() {
+    public void overrideFlushedRows() throws IOException {
         Workbook wb = new SXSSFWorkbook(3);
-        Sheet sheet = wb.createSheet();
-
-        sheet.createRow(1);
-        sheet.createRow(2);
-        sheet.createRow(3);
-        sheet.createRow(4);
-
-        thrown.expect(Throwable.class);
-        thrown.expectMessage("Attempting to write a row[1] in the range [0,1] that is already written to disk.");
-        sheet.createRow(1);
+        try {
+            Sheet sheet = wb.createSheet();
+    
+            sheet.createRow(1);
+            sheet.createRow(2);
+            sheet.createRow(3);
+            sheet.createRow(4);
+    
+            thrown.expect(Throwable.class);
+            thrown.expectMessage("Attempting to write a row[1] in the range [0,1] that is already written to disk.");
+            sheet.createRow(1);
+        } finally {
+            wb.close();
+        }
     }
 
     @Test
-    public void overrideRowsInTemplate() {
+    public void overrideRowsInTemplate() throws IOException {
         XSSFWorkbook template = new XSSFWorkbook();
         template.createSheet().createRow(1);
 
         Workbook wb = new SXSSFWorkbook(template);
-        Sheet sheet = wb.getSheetAt(0);
-
         try {
-            sheet.createRow(1);
-            fail("expected exception");
-        } catch (Throwable e){
-            assertEquals("Attempting to write a row[1] in the range [0,1] that is already written to disk.", e.getMessage());
-        }
-        try {
-            sheet.createRow(0);
-            fail("expected exception");
-        } catch (Throwable e){
-            assertEquals("Attempting to write a row[0] in the range [0,1] that is already written to disk.", e.getMessage());
+            Sheet sheet = wb.getSheetAt(0);
+    
+            try {
+                sheet.createRow(1);
+                fail("expected exception");
+            } catch (Throwable e){
+                assertEquals("Attempting to write a row[1] in the range [0,1] that is already written to disk.", e.getMessage());
+            }
+            try {
+                sheet.createRow(0);
+                fail("expected exception");
+            } catch (Throwable e){
+                assertEquals("Attempting to write a row[0] in the range [0,1] that is already written to disk.", e.getMessage());
+            }
+            sheet.createRow(2);
+        } finally {
+            wb.close();
         }
-        sheet.createRow(2);
 
     }
 }
index a0fb72922ca89940318ad942f5ef69677d4328e9..973d234aa800e895babd0f2aae862e0a332d434b 100644 (file)
@@ -28,6 +28,7 @@ import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertSame;
 import static org.junit.Assert.fail;
 
+import java.io.IOException;
 import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
@@ -1188,7 +1189,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
     }
 
     @Test
-    public void bug54607() {
+    public void bug54607() throws IOException {
         // run with the file provided in the Bug-Report
         runGetTopRow("54607.xlsx", true, 1, 0, 0);
         runGetLeftCol("54607.xlsx", true, 0, 0, 0);
@@ -1202,7 +1203,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
         runGetLeftCol("TwoSheetsNoneHidden.xls", false, 0, 0);
     }
 
-    private void runGetTopRow(String file, boolean isXSSF, int... topRows) {
+    private void runGetTopRow(String file, boolean isXSSF, int... topRows) throws IOException {
         final Workbook wb;
         if(isXSSF) {
             wb = XSSFTestDataSamples.openSampleWorkbook(file);
@@ -1218,15 +1219,19 @@ public final class TestXSSFSheet extends BaseTestSheet {
         // for XSSF also test with SXSSF
         if(isXSSF) {
             Workbook swb = new SXSSFWorkbook((XSSFWorkbook) wb);
-            for (int si = 0; si < swb.getNumberOfSheets(); si++) {
-                Sheet sh = swb.getSheetAt(si);
-                assertNotNull(sh.getSheetName());
-                assertEquals("Did not match for sheet " + si, topRows[si], sh.getTopRow());
+            try {
+                for (int si = 0; si < swb.getNumberOfSheets(); si++) {
+                    Sheet sh = swb.getSheetAt(si);
+                    assertNotNull(sh.getSheetName());
+                    assertEquals("Did not match for sheet " + si, topRows[si], sh.getTopRow());
+                }
+            } finally {
+                swb.close();
             }
         }
     }
 
-    private void runGetLeftCol(String file, boolean isXSSF, int... topRows) {
+    private void runGetLeftCol(String file, boolean isXSSF, int... topRows) throws IOException {
         final Workbook wb;
         if(isXSSF) {
             wb = XSSFTestDataSamples.openSampleWorkbook(file);
@@ -1247,6 +1252,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
                 assertNotNull(sh.getSheetName());
                 assertEquals("Did not match for sheet " + si, topRows[si], sh.getLeftCol());
             }
+            swb.close();
         }
     }
 
index 538d4a11b1d565eca4393173ca1bb6f50a73145a..346abe0790c9d2d6b258f11a4b648b125615252a 100644 (file)
@@ -18,6 +18,7 @@ package org.apache.poi.xssf.usermodel;
 
 import java.io.ByteArrayOutputStream;
 import java.io.ByteArrayInputStream;
+import java.io.InputStream;
 import java.math.BigInteger;
 import java.util.List;
 
@@ -25,6 +26,7 @@ import junit.framework.TestCase;
 
 import org.apache.poi.POIDataSamples;
 import org.apache.xmlbeans.XmlObject;
+
 import schemasMicrosoftComVml.*;
 import schemasMicrosoftComOfficeOffice.CTShapeLayout;
 import schemasMicrosoftComOfficeOffice.STConnectType;
@@ -95,7 +97,12 @@ public class TestXSSFVMLDrawing extends TestCase {
     public void testFindCommentShape() throws Exception {
         
         XSSFVMLDrawing vml = new XSSFVMLDrawing();
-        vml.read(POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml"));
+        InputStream stream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml");
+        try {
+            vml.read(stream);
+        } finally {
+            stream.close();
+        }
 
         CTShape sh_a1 = vml.findCommentShape(0, 0);
         assertNotNull(sh_a1);
@@ -127,7 +134,12 @@ public class TestXSSFVMLDrawing extends TestCase {
 
     public void testRemoveCommentShape() throws Exception {
         XSSFVMLDrawing vml = new XSSFVMLDrawing();
-        vml.read(POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml"));
+        InputStream stream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml");
+        try {
+            vml.read(stream);
+        } finally {
+            stream.close();
+        }
 
         CTShape sh_a1 = vml.findCommentShape(0, 0);
         assertNotNull(sh_a1);
index 067a94c9a79c091d2091e666712abf9431e83c91..d9e3717842de17154804b8e0f69b348c1b9b6d75 100644 (file)
@@ -178,5 +178,6 @@ public class TestDocumentEncryption {
         ps = PropertySetFactory.create(fs2.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);\r
         assertTrue(ps.isDocumentSummaryInformation());\r
         assertEquals("On-screen Show (4:3)", ps.getProperties()[1].getValue());\r
+        fs.close();\r
     }\r
 }\r
index 5e4beccb8f06e6f5e06397fa5b4ce60ba74cf62d..b9b0edec84b21fe423848f3b70a45b7f37893dbf 100644 (file)
@@ -25,8 +25,8 @@ import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
 import java.util.List;
 
-import junit.framework.Assert;
 import junit.framework.TestCase;
+
 import org.apache.poi.POIDataSamples;
 import org.apache.poi.hpsf.DocumentSummaryInformation;
 import org.apache.poi.hpsf.HPSFException;
@@ -95,7 +95,7 @@ public final class TestBasic extends TestCase {
     {
         String[] expected = POI_FILES;
         for (int i = 0; i < expected.length; i++)
-            Assert.assertEquals(poiFiles[i].getName(), expected[i]);
+            assertEquals(poiFiles[i].getName(), expected[i]);
     }
 
     /**
@@ -115,7 +115,7 @@ public final class TestBasic extends TestCase {
     public void testCreatePropertySets()
     throws UnsupportedEncodingException, IOException
     {
-        Class[] expected = new Class[]
+        Class<?>[] expected = new Class[]
             {
                 SummaryInformation.class,
                 DocumentSummaryInformation.class,
@@ -140,7 +140,7 @@ public final class TestBasic extends TestCase {
                 o = ex;
             }
             in.close();
-            Assert.assertEquals(expected[i], o.getClass());
+            assertEquals(expected[i], o.getClass());
         }
     }
 
@@ -160,15 +160,15 @@ public final class TestBasic extends TestCase {
             byte[] b = poiFiles[i].getBytes();
             PropertySet ps =
                 PropertySetFactory.create(new ByteArrayInputStream(b));
-            Assert.assertEquals(ps.getByteOrder(), BYTE_ORDER);
-            Assert.assertEquals(ps.getFormat(), FORMAT);
-            Assert.assertEquals(ps.getOSVersion(), OS_VERSION);
-            Assert.assertEquals(new String(ps.getClassID().getBytes()),
+            assertEquals(ps.getByteOrder(), BYTE_ORDER);
+            assertEquals(ps.getFormat(), FORMAT);
+            assertEquals(ps.getOSVersion(), OS_VERSION);
+            assertEquals(new String(ps.getClassID().getBytes()),
                                 new String(CLASS_ID));
-            Assert.assertEquals(ps.getSectionCount(), SECTION_COUNT[i]);
-            Assert.assertEquals(ps.isSummaryInformation(),
+            assertEquals(ps.getSectionCount(), SECTION_COUNT[i]);
+            assertEquals(ps.isSummaryInformation(),
                                 IS_SUMMARY_INFORMATION[i]);
-            Assert.assertEquals(ps.isDocumentSummaryInformation(),
+            assertEquals(ps.isDocumentSummaryInformation(),
                                 IS_DOCUMENT_SUMMARY_INFORMATION[i]);
         }
     }
@@ -186,13 +186,13 @@ public final class TestBasic extends TestCase {
         final SummaryInformation si = (SummaryInformation)
             PropertySetFactory.create(new ByteArrayInputStream
                 (poiFiles[0].getBytes()));
-        final List sections = si.getSections();
-        final Section s = (Section) sections.get(0);
-        Assert.assertTrue(org.apache.poi.hpsf.Util.equal
+        final List<Section> sections = si.getSections();
+        final Section s = sections.get(0);
+        assertTrue(org.apache.poi.hpsf.Util.equal
             (s.getFormatID().getBytes(), SectionIDMap.SUMMARY_INFORMATION_ID));
-        Assert.assertNotNull(s.getProperties());
-        Assert.assertEquals(17, s.getPropertyCount());
-        Assert.assertEquals("Titel", s.getProperty(2));
-        Assert.assertEquals(1764, s.getSize());
+        assertNotNull(s.getProperties());
+        assertEquals(17, s.getPropertyCount());
+        assertEquals("Titel", s.getProperty(2));
+        assertEquals(1764, s.getSize());
     }
 }
index 47c4adc340680ef75e040c62cf1afa15c4dffbac..4e3bb21a1eea31fd90ede05bd8ef78540f2b6bd8 100644 (file)
@@ -24,9 +24,9 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
 
-import junit.framework.Assert;
 import junit.framework.TestCase;
 
+import org.apache.poi.POIDataSamples;
 import org.apache.poi.hpsf.DocumentSummaryInformation;
 import org.apache.poi.hpsf.HPSFException;
 import org.apache.poi.hpsf.MarkUnsupportedException;
@@ -35,7 +35,6 @@ import org.apache.poi.hpsf.PropertySet;
 import org.apache.poi.hpsf.PropertySetFactory;
 import org.apache.poi.hpsf.SummaryInformation;
 import org.apache.poi.hpsf.Variant;
-import org.apache.poi.POIDataSamples;
 
 /**
  * <p>Test case for OLE2 files with empty properties. An empty property's type
@@ -84,7 +83,7 @@ public final class TestEmptyProperties extends TestCase {
     {
         String[] expected = POI_FILES;
         for (int i = 0; i < expected.length; i++)
-            Assert.assertEquals(poiFiles[i].getName(), expected[i]);
+            assertEquals(poiFiles[i].getName(), expected[i]);
     }
 
     /**
@@ -104,7 +103,7 @@ public final class TestEmptyProperties extends TestCase {
     public void testCreatePropertySets()
     throws UnsupportedEncodingException, IOException
     {
-        Class[] expected = new Class[]
+        Class<?>[] expected = new Class[]
             {
                 NoPropertySetStreamException.class,
                 SummaryInformation.class,
@@ -127,7 +126,7 @@ public final class TestEmptyProperties extends TestCase {
                 o = ex;
             }
             in.close();
-            Assert.assertEquals(o.getClass(), expected[i]);
+            assertEquals(o.getClass(), expected[i]);
         }
     }
 
index 406a8dd7a06d74789ff62c0d6fe8d5e3b54dbb1a..adaee32d9cf1fe63f3919174f98003d0ecfdfa7c 100644 (file)
@@ -22,7 +22,6 @@ import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 
-import junit.framework.Assert;
 import junit.framework.TestCase;
 
 import org.apache.poi.POIDataSamples;
@@ -78,18 +77,18 @@ public class TestUnicode extends TestCase {
         byte[] b = poiFile.getBytes();
         PropertySet ps =
             PropertySetFactory.create(new ByteArrayInputStream(b));
-        Assert.assertTrue(ps.isDocumentSummaryInformation());
-        Assert.assertEquals(ps.getSectionCount(), 2);
-        Section s = (Section) ps.getSections().get(1);
-        Assert.assertEquals(s.getProperty(1),
+        assertTrue(ps.isDocumentSummaryInformation());
+        assertEquals(ps.getSectionCount(), 2);
+        Section s = ps.getSections().get(1);
+        assertEquals(s.getProperty(1),
                             Integer.valueOf(CodePageUtil.CP_UTF16));
-        Assert.assertEquals(s.getProperty(2),
+        assertEquals(s.getProperty(2),
                             Integer.valueOf(-96070278));
-        Assert.assertEquals(s.getProperty(3),
+        assertEquals(s.getProperty(3),
                             "MCon_Info zu Office bei Schreiner");
-        Assert.assertEquals(s.getProperty(4),
+        assertEquals(s.getProperty(4),
                             "petrovitsch@schreiner-online.de");
-        Assert.assertEquals(s.getProperty(5),
+        assertEquals(s.getProperty(5),
                             "Petrovitsch, Wilhelm");
     }
 }
index 8eca84b65c9a82805947bdc69d2f077b6540e767..097ff1aa15494185fb639a6e15fd4837de0023c0 100644 (file)
@@ -167,7 +167,12 @@ final class Util {
                 r.registerListener(pfl, poiFiles[i]);
 
         /* Read the POI filesystem. */
-        r.read(new FileInputStream(poiFs));
+        FileInputStream stream = new FileInputStream(poiFs);
+        try {
+            r.read(stream);
+        } finally {
+            stream.close();
+        }
         POIFile[] result = new POIFile[files.size()];
         for (int i = 0; i < result.length; i++)
             result[i] = files.get(i);
@@ -238,7 +243,7 @@ final class Util {
 
         POIFile[] result = new POIFile[files.size()];
         for (int i = 0; i < result.length; i++)
-            result[i] = (POIFile) files.get(i);
+            result[i] = files.get(i);
         return result;
     }
 
@@ -250,14 +255,14 @@ final class Util {
     public static void printSystemProperties()
     {
         final Properties p = System.getProperties();
-        final List names = new LinkedList();
-        for (Iterator i = p.keySet().iterator(); i.hasNext();)
+        final List<String> names = new LinkedList<String>();
+        for (Iterator<String> i = p.stringPropertyNames().iterator(); i.hasNext();)
             names.add(i.next());
         Collections.sort(names);
-        for (final Iterator i = names.iterator(); i.hasNext();)
+        for (final Iterator<String> i = names.iterator(); i.hasNext();)
         {
-            String name = (String) i.next();
-            String value = (String) p.get(name);
+            String name = i.next();
+            String value = p.getProperty(name);
             System.out.println(name + ": " + value);
         }
         System.out.println("Current directory: " +
index a5b69658e8385fcff6922990eb6c50698d48f349..86e7f2a8a2355d02686e2c7ccebd6ce7f8fa86c2 100644 (file)
@@ -850,12 +850,21 @@ public final class TestFormulas extends TestCase {
     /** test for bug 34021*/
     public void testComplexSheetRefs () throws IOException {
          HSSFWorkbook sb = new HSSFWorkbook();
-         HSSFSheet s1 = sb.createSheet("Sheet a.1");
-         HSSFSheet s2 = sb.createSheet("Sheet.A");
-         s2.createRow(1).createCell(2).setCellFormula("'Sheet a.1'!A1");
-         s1.createRow(1).createCell(2).setCellFormula("'Sheet.A'!A1");
-         File file = TempFile.createTempFile("testComplexSheetRefs",".xls");
-         sb.write(new FileOutputStream(file));
+         try {
+             HSSFSheet s1 = sb.createSheet("Sheet a.1");
+             HSSFSheet s2 = sb.createSheet("Sheet.A");
+             s2.createRow(1).createCell(2).setCellFormula("'Sheet a.1'!A1");
+             s1.createRow(1).createCell(2).setCellFormula("'Sheet.A'!A1");
+             File file = TempFile.createTempFile("testComplexSheetRefs",".xls");
+             FileOutputStream stream = new FileOutputStream(file);
+             try {
+                 sb.write(stream);
+             } finally {
+                 stream.close();
+             }
+         } finally {
+             sb.close();
+         }
     }
 
     /** Unknown Ptg 3C*/
@@ -864,7 +873,12 @@ public final class TestFormulas extends TestCase {
         wb.getSheetAt(0);
         assertEquals("Reference for named range ", "Compliance!#REF!",wb.getNameAt(0).getRefersToFormula());
         File outF = TempFile.createTempFile("bug27272_1",".xls");
-        wb.write(new FileOutputStream(outF));
+        FileOutputStream stream = new FileOutputStream(outF);
+        try {
+            wb.write(stream);
+        } finally {
+            stream.close();
+        }
         System.out.println("Open "+outF.getAbsolutePath()+" in Excel");
     }
     /** Unknown Ptg 3D*/
@@ -872,15 +886,25 @@ public final class TestFormulas extends TestCase {
         HSSFWorkbook wb = openSample("27272_2.xls");
         assertEquals("Reference for named range ", "LOAD.POD_HISTORIES!#REF!",wb.getNameAt(0).getRefersToFormula());
         File outF = TempFile.createTempFile("bug27272_2",".xls");
-        wb.write(new FileOutputStream(outF));
+        FileOutputStream stream = new FileOutputStream(outF);
+        try {
+            wb.write(stream);
+        } finally {
+            stream.close();
+        }
         System.out.println("Open "+outF.getAbsolutePath()+" in Excel");
     }
 
-    /** MissingArgPtg */
-    public void testMissingArgPtg() {
+    /** MissingArgPtg 
+     * @throws IOException */
+    public void testMissingArgPtg() throws IOException {
         HSSFWorkbook wb = new HSSFWorkbook();
-        HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell(0);
-        cell.setCellFormula("IF(A1=\"A\",1,)");
+        try {
+            HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell(0);
+            cell.setCellFormula("IF(A1=\"A\",1,)");
+        } finally {
+            wb.close();
+        }
     }
 
     public void testSharedFormula() {
@@ -942,20 +966,25 @@ public final class TestFormulas extends TestCase {
     /**
      * Verify that FormulaParser handles defined names beginning with underscores,
      * see Bug #49640
+     * @throws IOException 
      */
-    public void testFormulasWithUnderscore(){
+    public void testFormulasWithUnderscore() throws IOException{
         HSSFWorkbook wb = new HSSFWorkbook();
-        Name nm1 = wb.createName();
-        nm1.setNameName("_score1");
-        nm1.setRefersToFormula("A1");
-
-        Name nm2 = wb.createName();
-        nm2.setNameName("_score2");
-        nm2.setRefersToFormula("A2");
-
-        Sheet sheet = wb.createSheet();
-        Cell cell = sheet.createRow(0).createCell(2);
-        cell.setCellFormula("_score1*SUM(_score1+_score2)");
-        assertEquals("_score1*SUM(_score1+_score2)", cell.getCellFormula());
+        try {
+            Name nm1 = wb.createName();
+            nm1.setNameName("_score1");
+            nm1.setRefersToFormula("A1");
+    
+            Name nm2 = wb.createName();
+            nm2.setNameName("_score2");
+            nm2.setRefersToFormula("A2");
+    
+            Sheet sheet = wb.createSheet();
+            Cell cell = sheet.createRow(0).createCell(2);
+            cell.setCellFormula("_score1*SUM(_score1+_score2)");
+            assertEquals("_score1*SUM(_score1+_score2)", cell.getCellFormula());
+        } finally {
+            wb.close();
+        }
     }
 }
index bdedcb190959f0f1c11b148b225aa059da09e8b3..6ba10f99c6ae60754bc171544e718e22e85b2b5e 100644 (file)
@@ -513,36 +513,40 @@ public final class TestDocumentInputStream extends TestCase {
        DocumentInputStream stream;
        
        NPOIFSFileSystem npoifs = new NPOIFSFileSystem(sample);
-       POIFSFileSystem  opoifs = new POIFSFileSystem(new FileInputStream(sample));
-       
-       // Ensure we have what we expect on the root
-       assertEquals(npoifs, npoifs.getRoot().getNFileSystem());
-       assertEquals(null,   npoifs.getRoot().getFileSystem());
-       assertEquals(opoifs, opoifs.getRoot().getFileSystem());
-       assertEquals(null,   opoifs.getRoot().getNFileSystem());
-       
-       // Check inside
-       for(DirectoryNode root : new DirectoryNode[] { opoifs.getRoot(), npoifs.getRoot() }) {
-          // Top Level
-          Entry top = root.getEntry("Contents");
-          assertEquals(true, top.isDocumentEntry());
-          stream = root.createDocumentInputStream(top);
-          stream.read();
-          
-          // One Level Down
-          DirectoryNode escher = (DirectoryNode)root.getEntry("Escher");
-          Entry one = escher.getEntry("EscherStm");
-          assertEquals(true, one.isDocumentEntry());
-          stream = escher.createDocumentInputStream(one);
-          stream.read();
-          
-          // Two Levels Down
-          DirectoryNode quill = (DirectoryNode)root.getEntry("Quill");
-          DirectoryNode quillSub = (DirectoryNode)quill.getEntry("QuillSub");
-          Entry two = quillSub.getEntry("CONTENTS");
-          assertEquals(true, two.isDocumentEntry());
-          stream = quillSub.createDocumentInputStream(two);
-          stream.read();
+       try {
+           POIFSFileSystem  opoifs = new POIFSFileSystem(new FileInputStream(sample));
+           
+           // Ensure we have what we expect on the root
+           assertEquals(npoifs, npoifs.getRoot().getNFileSystem());
+           assertEquals(null,   npoifs.getRoot().getFileSystem());
+           assertEquals(opoifs, opoifs.getRoot().getFileSystem());
+           assertEquals(null,   opoifs.getRoot().getNFileSystem());
+           
+           // Check inside
+           for(DirectoryNode root : new DirectoryNode[] { opoifs.getRoot(), npoifs.getRoot() }) {
+              // Top Level
+              Entry top = root.getEntry("Contents");
+              assertEquals(true, top.isDocumentEntry());
+              stream = root.createDocumentInputStream(top);
+              stream.read();
+              
+              // One Level Down
+              DirectoryNode escher = (DirectoryNode)root.getEntry("Escher");
+              Entry one = escher.getEntry("EscherStm");
+              assertEquals(true, one.isDocumentEntry());
+              stream = escher.createDocumentInputStream(one);
+              stream.read();
+              
+              // Two Levels Down
+              DirectoryNode quill = (DirectoryNode)root.getEntry("Quill");
+              DirectoryNode quillSub = (DirectoryNode)quill.getEntry("QuillSub");
+              Entry two = quillSub.getEntry("CONTENTS");
+              assertEquals(true, two.isDocumentEntry());
+              stream = quillSub.createDocumentInputStream(two);
+              stream.read();
+           }
+       } finally {
+           npoifs.close();
        }
     }
 }
index 7de2841d4dce1a861152ed628aca2fbc4b4470df..d475b7aad0e27372e0c47bd0c4115da7aa4eaed4 100644 (file)
@@ -18,6 +18,7 @@
 package org.apache.poi.poifs.filesystem;
 
 import junit.framework.TestCase;
+
 import java.io.*;
 
 import org.apache.poi.hssf.HSSFTestDataSamples;
@@ -46,7 +47,7 @@ public class TestOffice2007XMLException extends TestCase {
                }
        }
        
-       public void testDetectAsPOIFS() {
+       public void testDetectAsPOIFS() throws IOException {
                
                // ooxml file isn't
                confirmIsPOIFS("SampleSS.xlsx", false);
@@ -57,14 +58,18 @@ public class TestOffice2007XMLException extends TestCase {
                // text file isn't
                confirmIsPOIFS("SampleSS.txt", false);
        }
-       private void confirmIsPOIFS(String sampleFileName, boolean expectedResult) {
+       private void confirmIsPOIFS(String sampleFileName, boolean expectedResult) throws IOException {
                InputStream in  = new PushbackInputStream(openSampleStream(sampleFileName), 10);
-               boolean actualResult;
                try {
-                       actualResult = POIFSFileSystem.hasPOIFSHeader(in);
-               } catch (IOException e) {
-                       throw new RuntimeException(e);
+               boolean actualResult;
+               try {
+                       actualResult = POIFSFileSystem.hasPOIFSHeader(in);
+               } catch (IOException e) {
+                       throw new RuntimeException(e);
+               }
+               assertEquals(expectedResult, actualResult);
+               } finally {
+                   in.close();
                }
-               assertEquals(expectedResult, actualResult);
        }
 }
index aa610bce65b15f6433996748fc536428099f7b4e..de5824efe28624bf76473cad24f7ae20807f66d0 100644 (file)
@@ -163,16 +163,19 @@ public final class TestPOIFSFileSystem extends TestCase {
         *  sectors that exist in the file.
         */
        public void testFATandDIFATsectors() throws Exception {
-      // Open the file up
-      try {
-         POIFSFileSystem fs = new POIFSFileSystem(
-             _samples.openResourceAsStream("ReferencesInvalidSectors.mpp")
-         );
-         fail("File is corrupt and shouldn't have been opened");
-      } catch(IOException e) {
-         String msg = e.getMessage();
-         assertTrue(msg.startsWith("Your file contains 695 sectors"));
-      }
+        // Open the file up
+        try {
+            InputStream stream = _samples.openResourceAsStream("ReferencesInvalidSectors.mpp");
+            try {
+                new POIFSFileSystem(stream);
+                fail("File is corrupt and shouldn't have been opened");
+            } finally {
+                stream.close();
+            }
+        } catch (IOException e) {
+            String msg = e.getMessage();
+            assertTrue(msg.startsWith("Your file contains 695 sectors"));
+        }
        }
        
        /**
@@ -242,39 +245,40 @@ public final class TestPOIFSFileSystem extends TestCase {
         *  use 4k blocks. Check that we can open these.
         */
        public void test4KBlocks() throws Exception {
-      POIDataSamples _samples = POIDataSamples.getPOIFSInstance();
-          InputStream inp = _samples.openResourceAsStream("BlockSize4096.zvi");
-          
-          // First up, check that we can process the header properly
-      HeaderBlock header_block = new HeaderBlock(inp);
-      POIFSBigBlockSize bigBlockSize = header_block.getBigBlockSize();
-      assertEquals(4096, bigBlockSize.getBigBlockSize());
-      
-      // Check the fat info looks sane
-      assertEquals(1, header_block.getBATArray().length);
-      assertEquals(1, header_block.getBATCount());
-      assertEquals(0, header_block.getXBATCount());
-      
-      // Now check we can get the basic fat
-      RawDataBlockList data_blocks = new RawDataBlockList(inp, bigBlockSize);
+        POIDataSamples _samples = POIDataSamples.getPOIFSInstance();
+        InputStream inp = _samples.openResourceAsStream("BlockSize4096.zvi");
+        try {
+            // First up, check that we can process the header properly
+            HeaderBlock header_block = new HeaderBlock(inp);
+            POIFSBigBlockSize bigBlockSize = header_block.getBigBlockSize();
+            assertEquals(4096, bigBlockSize.getBigBlockSize());
 
-          
-          // Now try and open properly
-          POIFSFileSystem fs = new POIFSFileSystem(
-                _samples.openResourceAsStream("BlockSize4096.zvi")
-          );
-          assertTrue(fs.getRoot().getEntryCount() > 3);
-          
-          // Check we can get at all the contents
-          checkAllDirectoryContents(fs.getRoot());
-          
-          
-          // Finally, check we can do a similar 512byte one too
-          fs = new POIFSFileSystem(
-            _samples.openResourceAsStream("BlockSize512.zvi")
-      );
-      assertTrue(fs.getRoot().getEntryCount() > 3);
-      checkAllDirectoryContents(fs.getRoot());
+            // Check the fat info looks sane
+            assertEquals(1, header_block.getBATArray().length);
+            assertEquals(1, header_block.getBATCount());
+            assertEquals(0, header_block.getXBATCount());
+
+            // Now check we can get the basic fat
+            RawDataBlockList data_blocks = new RawDataBlockList(inp,
+                    bigBlockSize);
+            assertEquals(15, data_blocks.blockCount());
+
+            // Now try and open properly
+            POIFSFileSystem fs = new POIFSFileSystem(
+                    _samples.openResourceAsStream("BlockSize4096.zvi"));
+            assertTrue(fs.getRoot().getEntryCount() > 3);
+
+            // Check we can get at all the contents
+            checkAllDirectoryContents(fs.getRoot());
+
+            // Finally, check we can do a similar 512byte one too
+            fs = new POIFSFileSystem(
+                    _samples.openResourceAsStream("BlockSize512.zvi"));
+            assertTrue(fs.getRoot().getEntryCount() > 3);
+            checkAllDirectoryContents(fs.getRoot());
+        } finally {
+            inp.close();
+        }
        }
        private void checkAllDirectoryContents(DirectoryEntry dir) throws IOException {
           for(Entry entry : dir) {
@@ -283,9 +287,13 @@ public final class TestPOIFSFileSystem extends TestCase {
              } else {
                 DocumentNode doc = (DocumentNode) entry;
                 DocumentInputStream dis = new DocumentInputStream(doc);
-                int numBytes = dis.available();
-                byte[] data = new byte [numBytes];
-            dis.read(data);
+                try {
+                int numBytes = dis.available();
+                byte[] data = new byte [numBytes];
+                dis.read(data);
+                } finally {
+                    dis.close();
+                }
              }
           }
        }
index f3ffd50f068447cb2873193d32f94086c0918be2..0155cf809c16665fbf1f8b261ed27462e7633166 100644 (file)
@@ -38,44 +38,48 @@ public class TestDataSource extends TestCase
       File f = data.getFile("Notes.ole2");
       
       FileBackedDataSource ds = new FileBackedDataSource(f);
-      assertEquals(8192, ds.size());
-      
-      // Start of file
-      ByteBuffer bs; 
-      bs = ds.read(4, 0);
-      assertEquals(4, bs.capacity());
-      assertEquals(0, bs.position());
-      assertEquals(0xd0-256, bs.get(0));
-      assertEquals(0xcf-256, bs.get(1));
-      assertEquals(0x11-000, bs.get(2));
-      assertEquals(0xe0-256, bs.get(3));
-      assertEquals(0xd0-256, bs.get());
-      assertEquals(0xcf-256, bs.get());
-      assertEquals(0x11-000, bs.get());
-      assertEquals(0xe0-256, bs.get());
-      
-      // Mid way through
-      bs = ds.read(8, 0x400);
-      assertEquals(8, bs.capacity());
-      assertEquals(0, bs.position());
-      assertEquals((byte)'R', bs.get(0));
-      assertEquals(0, bs.get(1));
-      assertEquals((byte)'o', bs.get(2));
-      assertEquals(0, bs.get(3));
-      assertEquals((byte)'o', bs.get(4));
-      assertEquals(0, bs.get(5));
-      assertEquals((byte)'t', bs.get(6));
-      assertEquals(0, bs.get(7));
-      
-      // Can go to the end, but not past it
-      bs = ds.read(8, 8190);
-      assertEquals(0, bs.position()); // TODO How best to warn of a short read?
-      
-      // Can't go off the end
       try {
-         bs = ds.read(4, 8192);
-         fail("Shouldn't be able to read off the end of the file");
-      } catch(IllegalArgumentException e) {}
+          assertEquals(8192, ds.size());
+          
+          // Start of file
+          ByteBuffer bs; 
+          bs = ds.read(4, 0);
+          assertEquals(4, bs.capacity());
+          assertEquals(0, bs.position());
+          assertEquals(0xd0-256, bs.get(0));
+          assertEquals(0xcf-256, bs.get(1));
+          assertEquals(0x11-000, bs.get(2));
+          assertEquals(0xe0-256, bs.get(3));
+          assertEquals(0xd0-256, bs.get());
+          assertEquals(0xcf-256, bs.get());
+          assertEquals(0x11-000, bs.get());
+          assertEquals(0xe0-256, bs.get());
+          
+          // Mid way through
+          bs = ds.read(8, 0x400);
+          assertEquals(8, bs.capacity());
+          assertEquals(0, bs.position());
+          assertEquals((byte)'R', bs.get(0));
+          assertEquals(0, bs.get(1));
+          assertEquals((byte)'o', bs.get(2));
+          assertEquals(0, bs.get(3));
+          assertEquals((byte)'o', bs.get(4));
+          assertEquals(0, bs.get(5));
+          assertEquals((byte)'t', bs.get(6));
+          assertEquals(0, bs.get(7));
+          
+          // Can go to the end, but not past it
+          bs = ds.read(8, 8190);
+          assertEquals(0, bs.position()); // TODO How best to warn of a short read?
+          
+          // Can't go off the end
+          try {
+             bs = ds.read(4, 8192);
+             fail("Shouldn't be able to read off the end of the file");
+          } catch(IllegalArgumentException e) {}
+      } finally {
+          ds.close();
+      }
    }
    
    public void testByteArray() throws Exception {
index 1d1184a88f340c0f494f7feed964cdbf7dc1b980..d51f8e0f4cad356a7124b466c70cc114294c816f 100644 (file)
@@ -24,6 +24,9 @@ import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertSame;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+
+import java.io.IOException;
+
 import junit.framework.AssertionFailedError;
 
 import org.apache.poi.ss.ITestDataProvider;
@@ -186,51 +189,55 @@ public abstract class BaseTestWorkbook {
     }
 
     @Test
-    public void removeSheetAt() {
+    public void removeSheetAt() throws IOException {
         Workbook workbook = _testDataProvider.createWorkbook();
-        workbook.createSheet("sheet1");
-        workbook.createSheet("sheet2");
-        workbook.createSheet("sheet3");
-        assertEquals(3, workbook.getNumberOfSheets());
-
-        assertEquals(0, workbook.getActiveSheetIndex());
-
-        workbook.removeSheetAt(1);
-        assertEquals(2, workbook.getNumberOfSheets());
-        assertEquals("sheet3", workbook.getSheetName(1));
-        assertEquals(0, workbook.getActiveSheetIndex());
-
-        workbook.removeSheetAt(0);
-        assertEquals(1, workbook.getNumberOfSheets());
-        assertEquals("sheet3", workbook.getSheetName(0));
-        assertEquals(0, workbook.getActiveSheetIndex());
-
-        workbook.removeSheetAt(0);
-        assertEquals(0, workbook.getNumberOfSheets());
-        assertEquals(0, workbook.getActiveSheetIndex());
-
-        //re-create the sheets
-        workbook.createSheet("sheet1");
-        workbook.createSheet("sheet2");
-        workbook.createSheet("sheet3");
-        workbook.createSheet("sheet4");
-        assertEquals(4, workbook.getNumberOfSheets());
-
-        assertEquals(0, workbook.getActiveSheetIndex());
-        workbook.setActiveSheet(2);
-        assertEquals(2, workbook.getActiveSheetIndex());
-
-        workbook.removeSheetAt(2);
-        assertEquals(2, workbook.getActiveSheetIndex());
-
-        workbook.removeSheetAt(1);
-        assertEquals(1, workbook.getActiveSheetIndex());
-
-        workbook.removeSheetAt(0);
-        assertEquals(0, workbook.getActiveSheetIndex());
-
-        workbook.removeSheetAt(0);
-        assertEquals(0, workbook.getActiveSheetIndex());
+        try {
+            workbook.createSheet("sheet1");
+            workbook.createSheet("sheet2");
+            workbook.createSheet("sheet3");
+            assertEquals(3, workbook.getNumberOfSheets());
+    
+            assertEquals(0, workbook.getActiveSheetIndex());
+    
+            workbook.removeSheetAt(1);
+            assertEquals(2, workbook.getNumberOfSheets());
+            assertEquals("sheet3", workbook.getSheetName(1));
+            assertEquals(0, workbook.getActiveSheetIndex());
+    
+            workbook.removeSheetAt(0);
+            assertEquals(1, workbook.getNumberOfSheets());
+            assertEquals("sheet3", workbook.getSheetName(0));
+            assertEquals(0, workbook.getActiveSheetIndex());
+    
+            workbook.removeSheetAt(0);
+            assertEquals(0, workbook.getNumberOfSheets());
+            assertEquals(0, workbook.getActiveSheetIndex());
+    
+            //re-create the sheets
+            workbook.createSheet("sheet1");
+            workbook.createSheet("sheet2");
+            workbook.createSheet("sheet3");
+            workbook.createSheet("sheet4");
+            assertEquals(4, workbook.getNumberOfSheets());
+    
+            assertEquals(0, workbook.getActiveSheetIndex());
+            workbook.setActiveSheet(2);
+            assertEquals(2, workbook.getActiveSheetIndex());
+    
+            workbook.removeSheetAt(2);
+            assertEquals(2, workbook.getActiveSheetIndex());
+    
+            workbook.removeSheetAt(1);
+            assertEquals(1, workbook.getActiveSheetIndex());
+    
+            workbook.removeSheetAt(0);
+            assertEquals(0, workbook.getActiveSheetIndex());
+    
+            workbook.removeSheetAt(0);
+            assertEquals(0, workbook.getActiveSheetIndex());
+        } finally {
+            workbook.close();
+        }
     }
 
     @Test