Add missing close() of resources in both production code and tests

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
This commit is contained in:
Dominik Stadler 2014-12-28 09:16:57 +00:00
parent 7c9d23d887
commit 5c76ccba5b
27 changed files with 717 additions and 452 deletions

View File

@ -84,7 +84,8 @@ public abstract class POIXMLTextExtractor extends POITextExtractor {
if(_document != null) { if(_document != null) {
OPCPackage pkg = _document.getPackage(); OPCPackage pkg = _document.getPackage();
if(pkg != null) { 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(); super.close();

View File

@ -107,7 +107,23 @@ public class WorkbookFactory {
} catch(OfficeXmlFileException e) { } catch(OfficeXmlFileException e) {
// opening as .xls failed => try opening as .xlsx // opening as .xls failed => try opening as .xlsx
OPCPackage pkg = OPCPackage.open(file); OPCPackage pkg = OPCPackage.open(file);
try {
return new XSSFWorkbook(pkg); 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;
}
} }
} }
} }

View File

@ -69,10 +69,14 @@ import org.openxmlformats.schemas.presentationml.x2006.main.NotesMasterDocument;
throw new POIXMLException("Missing resource 'notesMaster.xml'"); throw new POIXMLException("Missing resource 'notesMaster.xml'");
} }
try {
try { try {
NotesMasterDocument doc = NotesMasterDocument.Factory.parse(is); NotesMasterDocument doc = NotesMasterDocument.Factory.parse(is);
CTNotesMaster slide = doc.getNotesMaster(); CTNotesMaster slide = doc.getNotesMaster();
return slide; return slide;
} finally {
is.close();
}
} catch (Exception e) { } catch (Exception e) {
throw new POIXMLException("Can't initialize NotesMaster", e); throw new POIXMLException("Can't initialize NotesMaster", e);
} }

View File

@ -312,7 +312,16 @@ public class SXSSFWorkbook implements Workbook
void deregisterSheetMapping(XSSFSheet xSheet) void deregisterSheetMapping(XSSFSheet xSheet)
{ {
SXSSFSheet sxSheet=getSXSSFSheet(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); _sxFromXHash.remove(sxSheet);
_xFromSxHash.remove(xSheet); _xFromSxHash.remove(xSheet);
} }
private XSSFSheet getSheetFromZipEntryName(String sheetRef) private XSSFSheet getSheetFromZipEntryName(String sheetRef)
@ -827,6 +836,17 @@ public class SXSSFWorkbook implements Workbook
*/ */
@Override @Override
public void close() throws IOException { 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 // Tell the base workbook to close, does nothing if
// it's a newly created one // it's a newly created one
_wb.close(); _wb.close();

View File

@ -19,8 +19,10 @@
package org.apache.poi; package org.apache.poi;
import java.io.InputStream;
import java.io.PushbackInputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import java.io.*;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.OPCPackage;
@ -44,17 +46,20 @@ public class TestDetectAsOOXML extends TestCase
HSSFTestDataSamples.openSampleFileStream("SampleSS.xlsx"), 10 HSSFTestDataSamples.openSampleFileStream("SampleSS.xlsx"), 10
); );
assertTrue(POIXMLDocument.hasOOXMLHeader(in)); assertTrue(POIXMLDocument.hasOOXMLHeader(in));
in.close();
// xls file isn't // xls file isn't
in = new PushbackInputStream( in = new PushbackInputStream(
HSSFTestDataSamples.openSampleFileStream("SampleSS.xls"), 10 HSSFTestDataSamples.openSampleFileStream("SampleSS.xls"), 10
); );
assertFalse(POIXMLDocument.hasOOXMLHeader(in)); assertFalse(POIXMLDocument.hasOOXMLHeader(in));
in.close();
// text file isn't // text file isn't
in = new PushbackInputStream( in = new PushbackInputStream(
HSSFTestDataSamples.openSampleFileStream("SampleSS.txt"), 10 HSSFTestDataSamples.openSampleFileStream("SampleSS.txt"), 10
); );
assertFalse(POIXMLDocument.hasOOXMLHeader(in)); assertFalse(POIXMLDocument.hasOOXMLHeader(in));
in.close();
} }
} }

View File

@ -105,7 +105,7 @@ public final class TestPOIXMLDocument extends TestCase {
out.close(); out.close();
OPCPackage pkg2 = OPCPackage.open(tmp.getAbsolutePath()); OPCPackage pkg2 = OPCPackage.open(tmp.getAbsolutePath());
try {
doc = new OPCParser(pkg1); doc = new OPCParser(pkg1);
doc.parse(new TestFactory()); doc.parse(new TestFactory());
context = new HashMap<String,POIXMLDocumentPart>(); context = new HashMap<String,POIXMLDocumentPart>();
@ -129,6 +129,9 @@ public final class TestPOIXMLDocument extends TestCase {
} }
assertEquals(p1.getPartName(), p2.getPartName()); assertEquals(p1.getPartName(), p2.getPartName());
} }
} finally {
pkg2.close();
}
} }
public void testPPTX() throws Exception { public void testPPTX() throws Exception {
@ -156,6 +159,7 @@ public final class TestPOIXMLDocument extends TestCase {
for(POIXMLDocumentPart rel : doc.getRelations()){ for(POIXMLDocumentPart rel : doc.getRelations()){
//TODO finish me //TODO finish me
assertNotNull(rel);
} }
} }

View File

@ -25,6 +25,7 @@ import junit.framework.TestCase;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.POIOLE2TextExtractor; import org.apache.poi.POIOLE2TextExtractor;
import org.apache.poi.POITextExtractor; import org.apache.poi.POITextExtractor;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hdgf.extractor.VisioTextExtractor; import org.apache.poi.hdgf.extractor.VisioTextExtractor;
import org.apache.poi.hpbf.extractor.PublisherTextExtractor; import org.apache.poi.hpbf.extractor.PublisherTextExtractor;
import org.apache.poi.hslf.extractor.PowerPointExtractor; 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.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException; import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.apache.poi.openxml4j.opc.OPCPackage; 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.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor; import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor;
import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor; import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor;
@ -128,22 +130,33 @@ public class TestExtractorFactory extends TestCase {
assertTrue( assertTrue(
xlsExtractor.getText().length() > 200 xlsExtractor.getText().length() > 200
); );
xlsExtractor.close();
POITextExtractor extractor = ExtractorFactory.createExtractor(xlsx);
assertTrue( assertTrue(
ExtractorFactory.createExtractor(xlsx) extractor
instanceof XSSFExcelExtractor instanceof XSSFExcelExtractor
); );
assertTrue( extractor.close();
ExtractorFactory.createExtractor(xlsx).getText().length() > 200
);
extractor = ExtractorFactory.createExtractor(xlsx);
assertTrue( assertTrue(
ExtractorFactory.createExtractor(xltx) extractor.getText().length() > 200
);
extractor.close();
extractor = ExtractorFactory.createExtractor(xltx);
assertTrue(
extractor
instanceof XSSFExcelExtractor instanceof XSSFExcelExtractor
); );
extractor.close();
extractor = ExtractorFactory.createExtractor(xltx);
assertTrue( assertTrue(
ExtractorFactory.createExtractor(xltx).getText().contains("test") extractor.getText().contains("test")
); );
extractor.close();
// Word // Word
@ -171,22 +184,29 @@ public class TestExtractorFactory extends TestCase {
ExtractorFactory.createExtractor(doc95).getText().length() > 120 ExtractorFactory.createExtractor(doc95).getText().length() > 120
); );
extractor = ExtractorFactory.createExtractor(docx);
assertTrue(
extractor instanceof XWPFWordExtractor
);
extractor.close();
extractor = ExtractorFactory.createExtractor(docx);
assertTrue( assertTrue(
ExtractorFactory.createExtractor(docx) extractor.getText().length() > 120
instanceof XWPFWordExtractor
);
assertTrue(
ExtractorFactory.createExtractor(docx).getText().length() > 120
); );
extractor.close();
extractor = ExtractorFactory.createExtractor(dotx);
assertTrue( assertTrue(
ExtractorFactory.createExtractor(dotx) extractor instanceof XWPFWordExtractor
instanceof XWPFWordExtractor
); );
extractor.close();
extractor = ExtractorFactory.createExtractor(dotx);
assertTrue( assertTrue(
ExtractorFactory.createExtractor(dotx).getText().contains("Test") extractor.getText().contains("Test")
); );
extractor.close();
// PowerPoint // PowerPoint
assertTrue( assertTrue(
@ -197,13 +217,18 @@ public class TestExtractorFactory extends TestCase {
ExtractorFactory.createExtractor(ppt).getText().length() > 120 ExtractorFactory.createExtractor(ppt).getText().length() > 120
); );
extractor = ExtractorFactory.createExtractor(pptx);
assertTrue( assertTrue(
ExtractorFactory.createExtractor(pptx) extractor
instanceof XSLFPowerPointExtractor instanceof XSLFPowerPointExtractor
); );
extractor.close();
extractor = ExtractorFactory.createExtractor(pptx);
assertTrue( assertTrue(
ExtractorFactory.createExtractor(pptx).getText().length() > 120 extractor.getText().length() > 120
); );
extractor.close();
// Visio // Visio
assertTrue( assertTrue(
@ -338,8 +363,13 @@ public class TestExtractorFactory extends TestCase {
// Text // Text
try { try {
ExtractorFactory.createExtractor(new FileInputStream(txt)); FileInputStream stream = new FileInputStream(txt);
try {
ExtractorFactory.createExtractor(stream);
fail(); fail();
} finally {
stream.close();
}
} catch(IllegalArgumentException e) { } catch(IllegalArgumentException e) {
// Good // Good
} }
@ -427,31 +457,43 @@ public class TestExtractorFactory extends TestCase {
public void testPackage() throws Exception { public void testPackage() throws Exception {
// Excel // Excel
POIXMLTextExtractor extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString(), PackageAccess.READ));
assertTrue( assertTrue(
ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())) extractor
instanceof XSSFExcelExtractor instanceof XSSFExcelExtractor
); );
assertTrue( extractor.close();
ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())).getText().length() > 200 extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString()));
); assertTrue(extractor.getText().length() > 200);
extractor.close();
// Word // Word
extractor = ExtractorFactory.createExtractor(OPCPackage.open(docx.toString()));
assertTrue( assertTrue(
ExtractorFactory.createExtractor(OPCPackage.open(docx.toString())) extractor
instanceof XWPFWordExtractor instanceof XWPFWordExtractor
); );
extractor.close();
extractor = ExtractorFactory.createExtractor(OPCPackage.open(docx.toString()));
assertTrue( assertTrue(
ExtractorFactory.createExtractor(OPCPackage.open(docx.toString())).getText().length() > 120 extractor.getText().length() > 120
); );
extractor.close();
// PowerPoint // PowerPoint
extractor = ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString()));
assertTrue( assertTrue(
ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString())) extractor
instanceof XSLFPowerPointExtractor instanceof XSLFPowerPointExtractor
); );
extractor.close();
extractor = ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString()));
assertTrue( assertTrue(
ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString())).getText().length() > 120 extractor.getText().length() > 120
); );
extractor.close();
// Text // Text
try { try {
@ -487,21 +529,27 @@ public class TestExtractorFactory extends TestCase {
// Check we get the right extractors now // Check we get the right extractors now
POITextExtractor extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)));
assertTrue( assertTrue(
ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls))) extractor
instanceof EventBasedExcelExtractor instanceof EventBasedExcelExtractor
); );
extractor.close();
extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)));
assertTrue( 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( assertTrue(
ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())) extractor.getText().length() > 200
instanceof XSSFEventBasedExcelExtractor
);
assertTrue(
ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())).getText().length() > 200
); );
extractor.close();
// Put back to normal // Put back to normal
@ -511,21 +559,29 @@ public class TestExtractorFactory extends TestCase {
assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors()); assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors());
// And back // And back
extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)));
assertTrue( assertTrue(
ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls))) extractor
instanceof ExcelExtractor instanceof ExcelExtractor
); );
extractor.close();
extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls)));
assertTrue( 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( assertTrue(
ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())) extractor
instanceof XSSFExcelExtractor instanceof XSSFExcelExtractor
); );
extractor.close();
extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString()));
assertTrue( assertTrue(
ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())).getText().length() > 200 extractor.getText().length() > 200
); );
extractor.close();
} }
/** /**

View File

@ -58,12 +58,17 @@ public final class TestPackage extends TestCase {
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx"); File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE); OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
try {
p.save(targetFile.getAbsoluteFile()); p.save(targetFile.getAbsoluteFile());
// Compare the original and newly saved document // Compare the original and newly saved document
assertTrue(targetFile.exists()); assertTrue(targetFile.exists());
ZipFileAssert.assertEquals(new File(originalFile), targetFile); ZipFileAssert.assertEquals(new File(originalFile), targetFile);
assertTrue(targetFile.delete()); 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 = PackageRelationship rel =
corePart.addRelationship(sheetPartName, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", "rSheet1"); 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"); PackagePart part = pkg.createPart(sheetPartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml");
assertNotNull(part);
// Dummy content again // Dummy content again
coreOut = corePart.getOutputStream(); coreOut = corePart.getOutputStream();
coreOut.write("<dummy-xml2 />".getBytes()); coreOut.write("<dummy-xml2 />".getBytes());
@ -189,12 +196,16 @@ public final class TestPackage extends TestCase {
// Save and re-load // Save and re-load
pkg.close(); pkg.close();
File tmp = TempFile.createTempFile("testCreatePackageWithCoreDocument", ".zip"); File tmp = TempFile.createTempFile("testCreatePackageWithCoreDocument", ".zip");
FileOutputStream fout = new FileOutputStream(tmp); OutputStream fout = new FileOutputStream(tmp);
try {
fout.write(baos.toByteArray()); fout.write(baos.toByteArray());
} finally {
fout.close(); fout.close();
}
pkg = OPCPackage.open(tmp.getPath()); pkg = OPCPackage.open(tmp.getPath());
//tmp.delete(); //tmp.delete();
try {
// Check still right // Check still right
coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
assertEquals(1, coreRels.size()); assertEquals(1, coreRels.size());
@ -211,6 +222,9 @@ public final class TestPackage extends TestCase {
assertEquals("Sheet1!A1", rel.getTargetURI().getRawFragment()); assertEquals("Sheet1!A1", rel.getTargetURI().getRawFragment());
assertMSCompatibility(pkg); assertMSCompatibility(pkg);
} finally {
pkg.close();
}
} }
private void assertMSCompatibility(OPCPackage pkg) throws Exception { private void assertMSCompatibility(OPCPackage pkg) throws Exception {
@ -297,14 +311,22 @@ public final class TestPackage extends TestCase {
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx"); File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE); OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
try {
FileOutputStream fout = new FileOutputStream(targetFile); FileOutputStream fout = new FileOutputStream(targetFile);
try {
p.save(fout); p.save(fout);
} finally {
fout.close(); fout.close();
}
// Compare the original and newly saved document // Compare the original and newly saved document
assertTrue(targetFile.exists()); assertTrue(targetFile.exists());
ZipFileAssert.assertEquals(new File(originalFile), targetFile); ZipFileAssert.assertEquals(new File(originalFile), targetFile);
assertTrue(targetFile.delete()); assertTrue(targetFile.delete());
} finally {
// use revert to not re-write the input file
p.revert();
}
} }
/** /**
@ -511,6 +533,7 @@ public final class TestPackage extends TestCase {
String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE); OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
try {
List<PackagePart> rs = pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml")); List<PackagePart> rs = pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml"));
HashMap<String, PackagePart> selected = new HashMap<String, PackagePart>(); HashMap<String, PackagePart> selected = new HashMap<String, PackagePart>();
@ -524,12 +547,16 @@ public final class TestPackage extends TestCase {
assertTrue(selected.containsKey("/word/styles.xml")); assertTrue(selected.containsKey("/word/styles.xml"));
assertTrue(selected.containsKey("/word/theme/theme1.xml")); assertTrue(selected.containsKey("/word/theme/theme1.xml"));
assertTrue(selected.containsKey("/word/webSettings.xml")); assertTrue(selected.containsKey("/word/webSettings.xml"));
} finally {
// use revert to not re-write the input file
pkg.revert();
}
} }
public void testGetPartSize() throws Exception { public void testGetPartSize() throws Exception {
String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ); OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ);
try {
int checked = 0; int checked = 0;
for (PackagePart part : pkg.getParts()) { for (PackagePart part : pkg.getParts()) {
// Can get the size of zip parts // Can get the size of zip parts
@ -553,6 +580,9 @@ public final class TestPackage extends TestCase {
} }
// Ensure we actually found the parts we want to check // Ensure we actually found the parts we want to check
assertEquals(3, checked); assertEquals(3, checked);
} finally {
pkg.close();
}
} }
public void testReplaceContentType() throws Exception { public void testReplaceContentType() throws Exception {

View File

@ -70,7 +70,7 @@ public final class TestPackageCoreProperties extends TestCase {
// Open package // Open package
OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE); OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE);
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC")); df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dateToInsert = df.parse("2007-05-12T08:00:00Z", new ParsePosition( Date dateToInsert = df.parse("2007-05-12T08:00:00Z", new ParsePosition(
@ -98,9 +98,17 @@ public final class TestPackageCoreProperties extends TestCase {
// Open the newly created file to check core properties saved values. // Open the newly created file to check core properties saved values.
OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ); OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ);
try {
compareProperties(p2); compareProperties(p2);
p2.revert(); p2.revert();
} finally {
p2.close();
}
outputFile.delete(); outputFile.delete();
} finally {
// use revert to not re-write the input file
p.revert();
}
} }
private void compareProperties(OPCPackage p) throws InvalidFormatException { private void compareProperties(OPCPackage p) throws InvalidFormatException {

View File

@ -42,16 +42,24 @@ public final class TestPackageThumbnail extends TestCase {
// Open package // Open package
OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE); OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE);
try {
p.addThumbnail(imagePath); p.addThumbnail(imagePath);
// Save the package in the output directory // Save the package in the output directory
p.save(outputFile); p.save(outputFile);
// Open the newly created file to check core properties saved values. // Open the newly created file to check core properties saved values.
OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ); OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ);
try {
if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL) if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL)
.size() == 0) .size() == 0)
fail("Thumbnail not added to the package !"); fail("Thumbnail not added to the package !");
} finally {
p2.revert(); p2.revert();
p2.close();
}
} finally {
p.revert();
outputFile.delete(); outputFile.delete();
} }
} }
}

View File

@ -188,6 +188,10 @@ public class TestRelationships extends TestCase {
// Write out and re-load // Write out and re-load
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
pkg.save(baos); pkg.save(baos);
// use revert to not re-write the input file
pkg.revert();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
pkg = OPCPackage.open(bais); pkg = OPCPackage.open(bais);
@ -280,7 +284,6 @@ public class TestRelationships extends TestCase {
public void testTargetWithSpecialChars() throws Exception{ public void testTargetWithSpecialChars() throws Exception{
OPCPackage pkg; OPCPackage pkg;
String filepath = OpenXML4JTestDataSamples.getSampleFileName("50154.xlsx"); String filepath = OpenXML4JTestDataSamples.getSampleFileName("50154.xlsx");
@ -289,6 +292,10 @@ public class TestRelationships extends TestCase {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
pkg.save(baos); pkg.save(baos);
// use revert to not re-write the input file
pkg.revert();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
pkg = OPCPackage.open(bais); pkg = OPCPackage.open(bais);

View File

@ -114,12 +114,16 @@ public class TestSignatureInfo {
@Test @Test
public void office2007prettyPrintedRels() throws Exception { public void office2007prettyPrintedRels() throws Exception {
OPCPackage pkg = OPCPackage.open(testdata.getFile("office2007prettyPrintedRels.docx"), PackageAccess.READ); OPCPackage pkg = OPCPackage.open(testdata.getFile("office2007prettyPrintedRels.docx"), PackageAccess.READ);
try {
SignatureConfig sic = new SignatureConfig(); SignatureConfig sic = new SignatureConfig();
sic.setOpcPackage(pkg); sic.setOpcPackage(pkg);
SignatureInfo si = new SignatureInfo(); SignatureInfo si = new SignatureInfo();
si.setSignatureConfig(sic); si.setSignatureConfig(sic);
boolean isValid = si.verifySignature(); boolean isValid = si.verifySignature();
assertTrue(isValid); assertTrue(isValid);
} finally {
pkg.close();
}
} }
@Test @Test

View File

@ -17,6 +17,8 @@
package org.apache.poi.ss; package org.apache.poi.ss;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
@ -47,6 +49,7 @@ public final class TestWorkbookFactory extends TestCase {
); );
assertNotNull(wb); assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook); assertTrue(wb instanceof HSSFWorkbook);
wb.close();
// Package -> xssf // Package -> xssf
wb = WorkbookFactory.create( wb = WorkbookFactory.create(
@ -55,6 +58,7 @@ public final class TestWorkbookFactory extends TestCase {
); );
assertNotNull(wb); assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook); 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); assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook); assertTrue(wb instanceof HSSFWorkbook);
wb.close();
wb = WorkbookFactory.create( wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xlsx) HSSFTestDataSamples.openSampleFileStream(xlsx)
); );
assertNotNull(wb); assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook); assertTrue(wb instanceof XSSFWorkbook);
// TODO: this re-writes the sample-file?! wb.close();
// File -> either // File -> either
wb = WorkbookFactory.create( wb = WorkbookFactory.create(
@ -84,6 +90,7 @@ public final class TestWorkbookFactory extends TestCase {
); );
assertNotNull(wb); assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook); assertTrue(wb instanceof HSSFWorkbook);
wb.close();
wb = WorkbookFactory.create( wb = WorkbookFactory.create(
HSSFTestDataSamples.getSampleFile(xlsx) HSSFTestDataSamples.getSampleFile(xlsx)
@ -91,11 +98,17 @@ public final class TestWorkbookFactory extends TestCase {
assertNotNull(wb); assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook); 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 // Invalid type -> exception
try { try {
wb = WorkbookFactory.create( InputStream stream = HSSFTestDataSamples.openSampleFileStream(txt);
HSSFTestDataSamples.openSampleFileStream(txt) try {
); wb = WorkbookFactory.create(stream);
} finally {
stream.close();
}
fail(); fail();
} catch(IllegalArgumentException e) { } catch(IllegalArgumentException e) {
// Good // Good

View File

@ -22,6 +22,8 @@ package org.apache.poi.xssf.streaming;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.IOException;
import org.apache.poi.ss.usermodel.BaseTestSheet; import org.apache.poi.ss.usermodel.BaseTestSheet;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
@ -94,8 +96,9 @@ public class TestSXSSFSheet extends BaseTestSheet {
} }
@Test @Test
public void overrideFlushedRows() { public void overrideFlushedRows() throws IOException {
Workbook wb = new SXSSFWorkbook(3); Workbook wb = new SXSSFWorkbook(3);
try {
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
sheet.createRow(1); sheet.createRow(1);
@ -106,14 +109,18 @@ public class TestSXSSFSheet extends BaseTestSheet {
thrown.expect(Throwable.class); thrown.expect(Throwable.class);
thrown.expectMessage("Attempting to write a row[1] in the range [0,1] that is already written to disk."); thrown.expectMessage("Attempting to write a row[1] in the range [0,1] that is already written to disk.");
sheet.createRow(1); sheet.createRow(1);
} finally {
wb.close();
}
} }
@Test @Test
public void overrideRowsInTemplate() { public void overrideRowsInTemplate() throws IOException {
XSSFWorkbook template = new XSSFWorkbook(); XSSFWorkbook template = new XSSFWorkbook();
template.createSheet().createRow(1); template.createSheet().createRow(1);
Workbook wb = new SXSSFWorkbook(template); Workbook wb = new SXSSFWorkbook(template);
try {
Sheet sheet = wb.getSheetAt(0); Sheet sheet = wb.getSheetAt(0);
try { try {
@ -129,6 +136,9 @@ public class TestSXSSFSheet extends BaseTestSheet {
assertEquals("Attempting to write a row[0] in the range [0,1] that is already written to disk.", e.getMessage()); assertEquals("Attempting to write a row[0] in the range [0,1] that is already written to disk.", e.getMessage());
} }
sheet.createRow(2); sheet.createRow(2);
} finally {
wb.close();
}
} }
} }

View File

@ -28,6 +28,7 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@ -1188,7 +1189,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
} }
@Test @Test
public void bug54607() { public void bug54607() throws IOException {
// run with the file provided in the Bug-Report // run with the file provided in the Bug-Report
runGetTopRow("54607.xlsx", true, 1, 0, 0); runGetTopRow("54607.xlsx", true, 1, 0, 0);
runGetLeftCol("54607.xlsx", true, 0, 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); 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; final Workbook wb;
if(isXSSF) { if(isXSSF) {
wb = XSSFTestDataSamples.openSampleWorkbook(file); wb = XSSFTestDataSamples.openSampleWorkbook(file);
@ -1218,15 +1219,19 @@ public final class TestXSSFSheet extends BaseTestSheet {
// for XSSF also test with SXSSF // for XSSF also test with SXSSF
if(isXSSF) { if(isXSSF) {
Workbook swb = new SXSSFWorkbook((XSSFWorkbook) wb); Workbook swb = new SXSSFWorkbook((XSSFWorkbook) wb);
try {
for (int si = 0; si < swb.getNumberOfSheets(); si++) { for (int si = 0; si < swb.getNumberOfSheets(); si++) {
Sheet sh = swb.getSheetAt(si); Sheet sh = swb.getSheetAt(si);
assertNotNull(sh.getSheetName()); assertNotNull(sh.getSheetName());
assertEquals("Did not match for sheet " + si, topRows[si], sh.getTopRow()); 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; final Workbook wb;
if(isXSSF) { if(isXSSF) {
wb = XSSFTestDataSamples.openSampleWorkbook(file); wb = XSSFTestDataSamples.openSampleWorkbook(file);
@ -1247,6 +1252,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertNotNull(sh.getSheetName()); assertNotNull(sh.getSheetName());
assertEquals("Did not match for sheet " + si, topRows[si], sh.getLeftCol()); assertEquals("Did not match for sheet " + si, topRows[si], sh.getLeftCol());
} }
swb.close();
} }
} }

View File

@ -18,6 +18,7 @@ package org.apache.poi.xssf.usermodel;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.List; import java.util.List;
@ -25,6 +26,7 @@ import junit.framework.TestCase;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlObject;
import schemasMicrosoftComVml.*; import schemasMicrosoftComVml.*;
import schemasMicrosoftComOfficeOffice.CTShapeLayout; import schemasMicrosoftComOfficeOffice.CTShapeLayout;
import schemasMicrosoftComOfficeOffice.STConnectType; import schemasMicrosoftComOfficeOffice.STConnectType;
@ -95,7 +97,12 @@ public class TestXSSFVMLDrawing extends TestCase {
public void testFindCommentShape() throws Exception { public void testFindCommentShape() throws Exception {
XSSFVMLDrawing vml = new XSSFVMLDrawing(); 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); CTShape sh_a1 = vml.findCommentShape(0, 0);
assertNotNull(sh_a1); assertNotNull(sh_a1);
@ -127,7 +134,12 @@ public class TestXSSFVMLDrawing extends TestCase {
public void testRemoveCommentShape() throws Exception { public void testRemoveCommentShape() throws Exception {
XSSFVMLDrawing vml = new XSSFVMLDrawing(); 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); CTShape sh_a1 = vml.findCommentShape(0, 0);
assertNotNull(sh_a1); assertNotNull(sh_a1);

View File

@ -178,5 +178,6 @@ public class TestDocumentEncryption {
ps = PropertySetFactory.create(fs2.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); ps = PropertySetFactory.create(fs2.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
assertTrue(ps.isDocumentSummaryInformation()); assertTrue(ps.isDocumentSummaryInformation());
assertEquals("On-screen Show (4:3)", ps.getProperties()[1].getValue()); assertEquals("On-screen Show (4:3)", ps.getProperties()[1].getValue());
fs.close();
} }
} }

View File

@ -25,8 +25,8 @@ import java.io.InputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.List; import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.HPSFException; import org.apache.poi.hpsf.HPSFException;
@ -95,7 +95,7 @@ public final class TestBasic extends TestCase {
{ {
String[] expected = POI_FILES; String[] expected = POI_FILES;
for (int i = 0; i < expected.length; i++) 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() public void testCreatePropertySets()
throws UnsupportedEncodingException, IOException throws UnsupportedEncodingException, IOException
{ {
Class[] expected = new Class[] Class<?>[] expected = new Class[]
{ {
SummaryInformation.class, SummaryInformation.class,
DocumentSummaryInformation.class, DocumentSummaryInformation.class,
@ -140,7 +140,7 @@ public final class TestBasic extends TestCase {
o = ex; o = ex;
} }
in.close(); 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(); byte[] b = poiFiles[i].getBytes();
PropertySet ps = PropertySet ps =
PropertySetFactory.create(new ByteArrayInputStream(b)); PropertySetFactory.create(new ByteArrayInputStream(b));
Assert.assertEquals(ps.getByteOrder(), BYTE_ORDER); assertEquals(ps.getByteOrder(), BYTE_ORDER);
Assert.assertEquals(ps.getFormat(), FORMAT); assertEquals(ps.getFormat(), FORMAT);
Assert.assertEquals(ps.getOSVersion(), OS_VERSION); assertEquals(ps.getOSVersion(), OS_VERSION);
Assert.assertEquals(new String(ps.getClassID().getBytes()), assertEquals(new String(ps.getClassID().getBytes()),
new String(CLASS_ID)); new String(CLASS_ID));
Assert.assertEquals(ps.getSectionCount(), SECTION_COUNT[i]); assertEquals(ps.getSectionCount(), SECTION_COUNT[i]);
Assert.assertEquals(ps.isSummaryInformation(), assertEquals(ps.isSummaryInformation(),
IS_SUMMARY_INFORMATION[i]); IS_SUMMARY_INFORMATION[i]);
Assert.assertEquals(ps.isDocumentSummaryInformation(), assertEquals(ps.isDocumentSummaryInformation(),
IS_DOCUMENT_SUMMARY_INFORMATION[i]); IS_DOCUMENT_SUMMARY_INFORMATION[i]);
} }
} }
@ -186,13 +186,13 @@ public final class TestBasic extends TestCase {
final SummaryInformation si = (SummaryInformation) final SummaryInformation si = (SummaryInformation)
PropertySetFactory.create(new ByteArrayInputStream PropertySetFactory.create(new ByteArrayInputStream
(poiFiles[0].getBytes())); (poiFiles[0].getBytes()));
final List sections = si.getSections(); final List<Section> sections = si.getSections();
final Section s = (Section) sections.get(0); final Section s = sections.get(0);
Assert.assertTrue(org.apache.poi.hpsf.Util.equal assertTrue(org.apache.poi.hpsf.Util.equal
(s.getFormatID().getBytes(), SectionIDMap.SUMMARY_INFORMATION_ID)); (s.getFormatID().getBytes(), SectionIDMap.SUMMARY_INFORMATION_ID));
Assert.assertNotNull(s.getProperties()); assertNotNull(s.getProperties());
Assert.assertEquals(17, s.getPropertyCount()); assertEquals(17, s.getPropertyCount());
Assert.assertEquals("Titel", s.getProperty(2)); assertEquals("Titel", s.getProperty(2));
Assert.assertEquals(1764, s.getSize()); assertEquals(1764, s.getSize());
} }
} }

View File

@ -24,9 +24,9 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import junit.framework.Assert;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.HPSFException; import org.apache.poi.hpsf.HPSFException;
import org.apache.poi.hpsf.MarkUnsupportedException; 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.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.Variant; 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 * <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; String[] expected = POI_FILES;
for (int i = 0; i < expected.length; i++) 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() public void testCreatePropertySets()
throws UnsupportedEncodingException, IOException throws UnsupportedEncodingException, IOException
{ {
Class[] expected = new Class[] Class<?>[] expected = new Class[]
{ {
NoPropertySetStreamException.class, NoPropertySetStreamException.class,
SummaryInformation.class, SummaryInformation.class,
@ -127,7 +126,7 @@ public final class TestEmptyProperties extends TestCase {
o = ex; o = ex;
} }
in.close(); in.close();
Assert.assertEquals(o.getClass(), expected[i]); assertEquals(o.getClass(), expected[i]);
} }
} }

View File

@ -22,7 +22,6 @@ import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import junit.framework.Assert;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
@ -78,18 +77,18 @@ public class TestUnicode extends TestCase {
byte[] b = poiFile.getBytes(); byte[] b = poiFile.getBytes();
PropertySet ps = PropertySet ps =
PropertySetFactory.create(new ByteArrayInputStream(b)); PropertySetFactory.create(new ByteArrayInputStream(b));
Assert.assertTrue(ps.isDocumentSummaryInformation()); assertTrue(ps.isDocumentSummaryInformation());
Assert.assertEquals(ps.getSectionCount(), 2); assertEquals(ps.getSectionCount(), 2);
Section s = (Section) ps.getSections().get(1); Section s = ps.getSections().get(1);
Assert.assertEquals(s.getProperty(1), assertEquals(s.getProperty(1),
Integer.valueOf(CodePageUtil.CP_UTF16)); Integer.valueOf(CodePageUtil.CP_UTF16));
Assert.assertEquals(s.getProperty(2), assertEquals(s.getProperty(2),
Integer.valueOf(-96070278)); Integer.valueOf(-96070278));
Assert.assertEquals(s.getProperty(3), assertEquals(s.getProperty(3),
"MCon_Info zu Office bei Schreiner"); "MCon_Info zu Office bei Schreiner");
Assert.assertEquals(s.getProperty(4), assertEquals(s.getProperty(4),
"petrovitsch@schreiner-online.de"); "petrovitsch@schreiner-online.de");
Assert.assertEquals(s.getProperty(5), assertEquals(s.getProperty(5),
"Petrovitsch, Wilhelm"); "Petrovitsch, Wilhelm");
} }
} }

View File

@ -167,7 +167,12 @@ final class Util {
r.registerListener(pfl, poiFiles[i]); r.registerListener(pfl, poiFiles[i]);
/* Read the POI filesystem. */ /* 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()]; POIFile[] result = new POIFile[files.size()];
for (int i = 0; i < result.length; i++) for (int i = 0; i < result.length; i++)
result[i] = files.get(i); result[i] = files.get(i);
@ -238,7 +243,7 @@ final class Util {
POIFile[] result = new POIFile[files.size()]; POIFile[] result = new POIFile[files.size()];
for (int i = 0; i < result.length; i++) for (int i = 0; i < result.length; i++)
result[i] = (POIFile) files.get(i); result[i] = files.get(i);
return result; return result;
} }
@ -250,14 +255,14 @@ final class Util {
public static void printSystemProperties() public static void printSystemProperties()
{ {
final Properties p = System.getProperties(); final Properties p = System.getProperties();
final List names = new LinkedList(); final List<String> names = new LinkedList<String>();
for (Iterator i = p.keySet().iterator(); i.hasNext();) for (Iterator<String> i = p.stringPropertyNames().iterator(); i.hasNext();)
names.add(i.next()); names.add(i.next());
Collections.sort(names); 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 name = i.next();
String value = (String) p.get(name); String value = p.getProperty(name);
System.out.println(name + ": " + value); System.out.println(name + ": " + value);
} }
System.out.println("Current directory: " + System.out.println("Current directory: " +

View File

@ -850,12 +850,21 @@ public final class TestFormulas extends TestCase {
/** test for bug 34021*/ /** test for bug 34021*/
public void testComplexSheetRefs () throws IOException { public void testComplexSheetRefs () throws IOException {
HSSFWorkbook sb = new HSSFWorkbook(); HSSFWorkbook sb = new HSSFWorkbook();
try {
HSSFSheet s1 = sb.createSheet("Sheet a.1"); HSSFSheet s1 = sb.createSheet("Sheet a.1");
HSSFSheet s2 = sb.createSheet("Sheet.A"); HSSFSheet s2 = sb.createSheet("Sheet.A");
s2.createRow(1).createCell(2).setCellFormula("'Sheet a.1'!A1"); s2.createRow(1).createCell(2).setCellFormula("'Sheet a.1'!A1");
s1.createRow(1).createCell(2).setCellFormula("'Sheet.A'!A1"); s1.createRow(1).createCell(2).setCellFormula("'Sheet.A'!A1");
File file = TempFile.createTempFile("testComplexSheetRefs",".xls"); File file = TempFile.createTempFile("testComplexSheetRefs",".xls");
sb.write(new FileOutputStream(file)); FileOutputStream stream = new FileOutputStream(file);
try {
sb.write(stream);
} finally {
stream.close();
}
} finally {
sb.close();
}
} }
/** Unknown Ptg 3C*/ /** Unknown Ptg 3C*/
@ -864,7 +873,12 @@ public final class TestFormulas extends TestCase {
wb.getSheetAt(0); wb.getSheetAt(0);
assertEquals("Reference for named range ", "Compliance!#REF!",wb.getNameAt(0).getRefersToFormula()); assertEquals("Reference for named range ", "Compliance!#REF!",wb.getNameAt(0).getRefersToFormula());
File outF = TempFile.createTempFile("bug27272_1",".xls"); 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"); System.out.println("Open "+outF.getAbsolutePath()+" in Excel");
} }
/** Unknown Ptg 3D*/ /** Unknown Ptg 3D*/
@ -872,15 +886,25 @@ public final class TestFormulas extends TestCase {
HSSFWorkbook wb = openSample("27272_2.xls"); HSSFWorkbook wb = openSample("27272_2.xls");
assertEquals("Reference for named range ", "LOAD.POD_HISTORIES!#REF!",wb.getNameAt(0).getRefersToFormula()); assertEquals("Reference for named range ", "LOAD.POD_HISTORIES!#REF!",wb.getNameAt(0).getRefersToFormula());
File outF = TempFile.createTempFile("bug27272_2",".xls"); File outF = TempFile.createTempFile("bug27272_2",".xls");
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"); System.out.println("Open "+outF.getAbsolutePath()+" in Excel");
} }
/** MissingArgPtg */ /** MissingArgPtg
public void testMissingArgPtg() { * @throws IOException */
public void testMissingArgPtg() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
try {
HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell(0); HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell(0);
cell.setCellFormula("IF(A1=\"A\",1,)"); cell.setCellFormula("IF(A1=\"A\",1,)");
} finally {
wb.close();
}
} }
public void testSharedFormula() { public void testSharedFormula() {
@ -942,9 +966,11 @@ public final class TestFormulas extends TestCase {
/** /**
* Verify that FormulaParser handles defined names beginning with underscores, * Verify that FormulaParser handles defined names beginning with underscores,
* see Bug #49640 * see Bug #49640
* @throws IOException
*/ */
public void testFormulasWithUnderscore(){ public void testFormulasWithUnderscore() throws IOException{
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
try {
Name nm1 = wb.createName(); Name nm1 = wb.createName();
nm1.setNameName("_score1"); nm1.setNameName("_score1");
nm1.setRefersToFormula("A1"); nm1.setRefersToFormula("A1");
@ -957,5 +983,8 @@ public final class TestFormulas extends TestCase {
Cell cell = sheet.createRow(0).createCell(2); Cell cell = sheet.createRow(0).createCell(2);
cell.setCellFormula("_score1*SUM(_score1+_score2)"); cell.setCellFormula("_score1*SUM(_score1+_score2)");
assertEquals("_score1*SUM(_score1+_score2)", cell.getCellFormula()); assertEquals("_score1*SUM(_score1+_score2)", cell.getCellFormula());
} finally {
wb.close();
}
} }
} }

View File

@ -513,6 +513,7 @@ public final class TestDocumentInputStream extends TestCase {
DocumentInputStream stream; DocumentInputStream stream;
NPOIFSFileSystem npoifs = new NPOIFSFileSystem(sample); NPOIFSFileSystem npoifs = new NPOIFSFileSystem(sample);
try {
POIFSFileSystem opoifs = new POIFSFileSystem(new FileInputStream(sample)); POIFSFileSystem opoifs = new POIFSFileSystem(new FileInputStream(sample));
// Ensure we have what we expect on the root // Ensure we have what we expect on the root
@ -544,5 +545,8 @@ public final class TestDocumentInputStream extends TestCase {
stream = quillSub.createDocumentInputStream(two); stream = quillSub.createDocumentInputStream(two);
stream.read(); stream.read();
} }
} finally {
npoifs.close();
}
} }
} }

View File

@ -18,6 +18,7 @@
package org.apache.poi.poifs.filesystem; package org.apache.poi.poifs.filesystem;
import junit.framework.TestCase; import junit.framework.TestCase;
import java.io.*; import java.io.*;
import org.apache.poi.hssf.HSSFTestDataSamples; 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 // ooxml file isn't
confirmIsPOIFS("SampleSS.xlsx", false); confirmIsPOIFS("SampleSS.xlsx", false);
@ -57,8 +58,9 @@ public class TestOffice2007XMLException extends TestCase {
// text file isn't // text file isn't
confirmIsPOIFS("SampleSS.txt", false); 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); InputStream in = new PushbackInputStream(openSampleStream(sampleFileName), 10);
try {
boolean actualResult; boolean actualResult;
try { try {
actualResult = POIFSFileSystem.hasPOIFSHeader(in); actualResult = POIFSFileSystem.hasPOIFSHeader(in);
@ -66,5 +68,8 @@ public class TestOffice2007XMLException extends TestCase {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
assertEquals(expectedResult, actualResult); assertEquals(expectedResult, actualResult);
} finally {
in.close();
}
} }
} }

View File

@ -165,10 +165,13 @@ public final class TestPOIFSFileSystem extends TestCase {
public void testFATandDIFATsectors() throws Exception { public void testFATandDIFATsectors() throws Exception {
// Open the file up // Open the file up
try { try {
POIFSFileSystem fs = new POIFSFileSystem( InputStream stream = _samples.openResourceAsStream("ReferencesInvalidSectors.mpp");
_samples.openResourceAsStream("ReferencesInvalidSectors.mpp") try {
); new POIFSFileSystem(stream);
fail("File is corrupt and shouldn't have been opened"); fail("File is corrupt and shouldn't have been opened");
} finally {
stream.close();
}
} catch (IOException e) { } catch (IOException e) {
String msg = e.getMessage(); String msg = e.getMessage();
assertTrue(msg.startsWith("Your file contains 695 sectors")); assertTrue(msg.startsWith("Your file contains 695 sectors"));
@ -244,7 +247,7 @@ public final class TestPOIFSFileSystem extends TestCase {
public void test4KBlocks() throws Exception { public void test4KBlocks() throws Exception {
POIDataSamples _samples = POIDataSamples.getPOIFSInstance(); POIDataSamples _samples = POIDataSamples.getPOIFSInstance();
InputStream inp = _samples.openResourceAsStream("BlockSize4096.zvi"); InputStream inp = _samples.openResourceAsStream("BlockSize4096.zvi");
try {
// First up, check that we can process the header properly // First up, check that we can process the header properly
HeaderBlock header_block = new HeaderBlock(inp); HeaderBlock header_block = new HeaderBlock(inp);
POIFSBigBlockSize bigBlockSize = header_block.getBigBlockSize(); POIFSBigBlockSize bigBlockSize = header_block.getBigBlockSize();
@ -256,25 +259,26 @@ public final class TestPOIFSFileSystem extends TestCase {
assertEquals(0, header_block.getXBATCount()); assertEquals(0, header_block.getXBATCount());
// Now check we can get the basic fat // Now check we can get the basic fat
RawDataBlockList data_blocks = new RawDataBlockList(inp, bigBlockSize); RawDataBlockList data_blocks = new RawDataBlockList(inp,
bigBlockSize);
assertEquals(15, data_blocks.blockCount());
// Now try and open properly // Now try and open properly
POIFSFileSystem fs = new POIFSFileSystem( POIFSFileSystem fs = new POIFSFileSystem(
_samples.openResourceAsStream("BlockSize4096.zvi") _samples.openResourceAsStream("BlockSize4096.zvi"));
);
assertTrue(fs.getRoot().getEntryCount() > 3); assertTrue(fs.getRoot().getEntryCount() > 3);
// Check we can get at all the contents // Check we can get at all the contents
checkAllDirectoryContents(fs.getRoot()); checkAllDirectoryContents(fs.getRoot());
// Finally, check we can do a similar 512byte one too // Finally, check we can do a similar 512byte one too
fs = new POIFSFileSystem( fs = new POIFSFileSystem(
_samples.openResourceAsStream("BlockSize512.zvi") _samples.openResourceAsStream("BlockSize512.zvi"));
);
assertTrue(fs.getRoot().getEntryCount() > 3); assertTrue(fs.getRoot().getEntryCount() > 3);
checkAllDirectoryContents(fs.getRoot()); checkAllDirectoryContents(fs.getRoot());
} finally {
inp.close();
}
} }
private void checkAllDirectoryContents(DirectoryEntry dir) throws IOException { private void checkAllDirectoryContents(DirectoryEntry dir) throws IOException {
for(Entry entry : dir) { for(Entry entry : dir) {
@ -283,9 +287,13 @@ public final class TestPOIFSFileSystem extends TestCase {
} else { } else {
DocumentNode doc = (DocumentNode) entry; DocumentNode doc = (DocumentNode) entry;
DocumentInputStream dis = new DocumentInputStream(doc); DocumentInputStream dis = new DocumentInputStream(doc);
try {
int numBytes = dis.available(); int numBytes = dis.available();
byte[] data = new byte [numBytes]; byte[] data = new byte [numBytes];
dis.read(data); dis.read(data);
} finally {
dis.close();
}
} }
} }
} }

View File

@ -38,6 +38,7 @@ public class TestDataSource extends TestCase
File f = data.getFile("Notes.ole2"); File f = data.getFile("Notes.ole2");
FileBackedDataSource ds = new FileBackedDataSource(f); FileBackedDataSource ds = new FileBackedDataSource(f);
try {
assertEquals(8192, ds.size()); assertEquals(8192, ds.size());
// Start of file // Start of file
@ -76,6 +77,9 @@ public class TestDataSource extends TestCase
bs = ds.read(4, 8192); bs = ds.read(4, 8192);
fail("Shouldn't be able to read off the end of the file"); fail("Shouldn't be able to read off the end of the file");
} catch(IllegalArgumentException e) {} } catch(IllegalArgumentException e) {}
} finally {
ds.close();
}
} }
public void testByteArray() throws Exception { public void testByteArray() throws Exception {

View File

@ -24,6 +24,9 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.IOException;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
@ -186,8 +189,9 @@ public abstract class BaseTestWorkbook {
} }
@Test @Test
public void removeSheetAt() { public void removeSheetAt() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
try {
workbook.createSheet("sheet1"); workbook.createSheet("sheet1");
workbook.createSheet("sheet2"); workbook.createSheet("sheet2");
workbook.createSheet("sheet3"); workbook.createSheet("sheet3");
@ -231,6 +235,9 @@ public abstract class BaseTestWorkbook {
workbook.removeSheetAt(0); workbook.removeSheetAt(0);
assertEquals(0, workbook.getActiveSheetIndex()); assertEquals(0, workbook.getActiveSheetIndex());
} finally {
workbook.close();
}
} }
@Test @Test