eclipse warnings - close resources

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1773910 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2016-12-13 00:36:03 +00:00
parent 4aaef1761d
commit 4cc6e093f4
19 changed files with 913 additions and 835 deletions

View File

@ -36,8 +36,6 @@ import org.apache.poi.hwpf.usermodel.Range;
/** /**
* Demonstrates how you can extract misc embedded data from a ppt file * Demonstrates how you can extract misc embedded data from a ppt file
*
* @author Yegor Kozlov
*/ */
public final class DataExtraction { public final class DataExtraction {
@ -93,6 +91,7 @@ public final class DataExtraction {
FileOutputStream out = new FileOutputStream(name + "-("+(oleIdx)+").doc"); FileOutputStream out = new FileOutputStream(name + "-("+(oleIdx)+").doc");
doc.write(out); doc.write(out);
out.close(); out.close();
doc.close();
} else { } else {
FileOutputStream out = new FileOutputStream(ole.getProgID() + "-"+(oleIdx+1)+".dat"); FileOutputStream out = new FileOutputStream(ole.getProgID() + "-"+(oleIdx+1)+".dat");
InputStream dis = data.getData(); InputStream dis = data.getData();
@ -117,8 +116,8 @@ public final class DataExtraction {
out.close(); out.close();
} }
} }
} }
ppt.close();
} }
private static void usage(){ private static void usage(){

View File

@ -131,16 +131,16 @@ public class Msg2txt {
*/ */
public void processAttachment(AttachmentChunks attachment, public void processAttachment(AttachmentChunks attachment,
File dir) throws IOException { File dir) throws IOException {
String fileName = attachment.attachFileName.toString(); String fileName = attachment.getAttachFileName().toString();
if(attachment.attachLongFileName != null) { if(attachment.getAttachLongFileName() != null) {
fileName = attachment.attachLongFileName.toString(); fileName = attachment.getAttachLongFileName().toString();
} }
File f = new File(dir, fileName); File f = new File(dir, fileName);
OutputStream fileOut = null; OutputStream fileOut = null;
try { try {
fileOut = new FileOutputStream(f); fileOut = new FileOutputStream(f);
fileOut.write(attachment.attachData.getValue()); fileOut.write(attachment.getAttachData().getValue());
} finally { } finally {
if(fileOut != null) { if(fileOut != null) {
fileOut.close(); fileOut.close();

View File

@ -32,8 +32,6 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
/** /**
* A simple WOrdprocessingML document created by POI XWPF API * A simple WOrdprocessingML document created by POI XWPF API
*
* @author Yegor Kozlov
*/ */
public class SimpleDocument { public class SimpleDocument {
@ -71,18 +69,18 @@ public class SimpleDocument {
XWPFRun r2 = p2.createRun(); XWPFRun r2 = p2.createRun();
r2.setText("jumped over the lazy dog"); r2.setText("jumped over the lazy dog");
r2.setStrike(true); r2.setStrikeThrough(true);
r2.setFontSize(20); r2.setFontSize(20);
XWPFRun r3 = p2.createRun(); XWPFRun r3 = p2.createRun();
r3.setText("and went away"); r3.setText("and went away");
r3.setStrike(true); r3.setStrikeThrough(true);
r3.setFontSize(20); r3.setFontSize(20);
r3.setSubscript(VerticalAlign.SUPERSCRIPT); r3.setSubscript(VerticalAlign.SUPERSCRIPT);
XWPFParagraph p3 = doc.createParagraph(); XWPFParagraph p3 = doc.createParagraph();
p3.setWordWrap(true); p3.setWordWrapped(true);
p3.setPageBreak(true); p3.setPageBreak(true);
//p3.setAlignment(ParagraphAlignment.DISTRIBUTE); //p3.setAlignment(ParagraphAlignment.DISTRIBUTE);
@ -127,6 +125,6 @@ public class SimpleDocument {
FileOutputStream out = new FileOutputStream("simple.docx"); FileOutputStream out = new FileOutputStream("simple.docx");
doc.write(out); doc.write(out);
out.close(); out.close();
doc.close();
} }
} }

View File

@ -18,23 +18,23 @@
*/ */
package org.apache.poi.xwpf.usermodel.examples; package org.apache.poi.xwpf.usermodel.examples;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units; import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.BreakType; import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/** /**
* Demonstrates how to add pictures in a .docx document * Demonstrates how to add pictures in a .docx document
*
* @author Yegor Kozlov
*/ */
public class SimpleImages { public class SimpleImages {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws IOException, InvalidFormatException {
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
XWPFParagraph p = doc.createParagraph(); XWPFParagraph p = doc.createParagraph();
@ -69,6 +69,7 @@ public class SimpleImages {
FileOutputStream out = new FileOutputStream("images.docx"); FileOutputStream out = new FileOutputStream("images.docx");
doc.write(out); doc.write(out);
out.close(); out.close();
doc.close();
} }

View File

@ -38,7 +38,7 @@ public class HSMFFileHandler extends POIFSFileHandler {
for(AttachmentChunks attachment : attachments) { for(AttachmentChunks attachment : attachments) {
DirectoryChunk chunkDirectory = attachment.attachmentDirectory; DirectoryChunk chunkDirectory = attachment.getAttachmentDirectory();
if(chunkDirectory != null) { if(chunkDirectory != null) {
MAPIMessage attachmentMSG = chunkDirectory.getAsEmbededMessage(); MAPIMessage attachmentMSG = chunkDirectory.getAsEmbededMessage();
assertNotNull(attachmentMSG); assertNotNull(attachmentMSG);

View File

@ -420,6 +420,7 @@ public abstract class POIDocument implements Closeable {
* *
* @return {@code true} if dummy directory was created, {@code false} otherwise * @return {@code true} if dummy directory was created, {@code false} otherwise
*/ */
@SuppressWarnings("resource")
@Internal @Internal
protected boolean initDirectory() { protected boolean initDirectory() {
if (directory == null) { if (directory == null) {

View File

@ -17,14 +17,10 @@
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.HexDump; import org.apache.poi.util.HexDump;
import org.apache.poi.util.HexRead; import org.apache.poi.util.HexRead;
import org.apache.poi.util.LittleEndianByteArrayInputStream; import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndianInput; import org.apache.poi.util.LittleEndianInput;
import org.apache.poi.util.LittleEndianOutput; import org.apache.poi.util.LittleEndianOutput;
import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogFactory;
@ -107,15 +103,14 @@ public final class HyperlinkRecord extends StandardRecord implements Cloneable {
} }
public long getD4() { public long getD4() {
// byte[] result = new byte[Long.SIZE/Byte.SIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream(8); long l = _d4;
try { for (int i = result.length-1; i >= 0; i--) {
new DataOutputStream(baos).writeLong(_d4); result[i] = (byte)(l & 0xFF);
} catch (IOException e) { l >>= 8;
throw new RuntimeException(e); }
}
byte[] buf = baos.toByteArray(); return LittleEndian.getLong(result, 0);
return new LittleEndianByteArrayInputStream(buf).readLong();
} }
public String formatAsString() { public String formatAsString() {

View File

@ -64,11 +64,15 @@ public final class FileHelper {
* If an I/O error occur. * If an I/O error occur.
*/ */
public static void copyFile(File in, File out) throws IOException { public static void copyFile(File in, File out) throws IOException {
FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileInputStream fis = new FileInputStream(in);
FileChannel destinationChannel = new FileOutputStream(out).getChannel(); FileOutputStream fos = new FileOutputStream(out);
FileChannel sourceChannel = fis.getChannel();
FileChannel destinationChannel = fos.getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
sourceChannel.close(); sourceChannel.close();
destinationChannel.close(); destinationChannel.close();
fos.close();
fis.close();
} }
/** /**

View File

@ -17,24 +17,26 @@
package org.apache.poi.openxml4j.opc; package org.apache.poi.openxml4j.opc;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Iterator;
import java.util.Set; import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import junit.framework.Assert; import org.junit.Assert;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
/** /**
* Compare the contents of 2 zip files. * Compare the contents of 2 zip files.
*
* @author CDubettier
*/ */
public class ZipFileAssert { public class ZipFileAssert {
private ZipFileAssert() { private ZipFileAssert() {
@ -42,55 +44,31 @@ public class ZipFileAssert {
static final int BUFFER_SIZE = 2048; static final int BUFFER_SIZE = 2048;
protected static boolean equals( protected static void equals(
TreeMap<String, ByteArrayOutputStream> file1, TreeMap<String, ByteArrayOutputStream> file1,
TreeMap<String, ByteArrayOutputStream> file2) { TreeMap<String, ByteArrayOutputStream> file2) {
Set listFile1 = file1.keySet(); Set<String> listFile1 = file1.keySet();
if (listFile1.size() == file2.keySet().size()) { Assert.assertEquals("not the same number of files in zip:", listFile1.size(), file2.keySet().size());
for (Iterator iter = listFile1.iterator(); iter.hasNext();) {
String fileName = (String) iter.next(); for (String fileName : listFile1) {
// extract the contents for both // extract the contents for both
ByteArrayOutputStream contain2 = file2.get(fileName); ByteArrayOutputStream contain2 = file2.get(fileName);
ByteArrayOutputStream contain1 = file1.get(fileName); ByteArrayOutputStream contain1 = file1.get(fileName);
if (contain2 == null) { assertNotNull(fileName + " not found in 2nd zip", contain2);
// file not found in archive 2 // no need to check for contain1. The key come from it
Assert.fail(fileName + " not found in 2nd zip");
return false;
}
// no need to check for contain1. The key come from it
if ((fileName.endsWith(".xml")) || fileName.endsWith(".rels")) { if ((fileName.endsWith(".xml")) || fileName.endsWith(".rels")) {
// we have a xml file // we have a xml file
// TODO // TODO
// YK: the original OpenXML4J version attempted to compare xml using xmlunit (http://xmlunit.sourceforge.net), // YK: the original OpenXML4J version attempted to compare xml using xmlunit (http://xmlunit.sourceforge.net),
// but POI does not depend on this library // but POI does not depend on this library
} else { } else {
// not xml, may be an image or other binary format // not xml, may be an image or other binary format
if (contain2.size() != contain1.size()) { Assert.assertEquals(fileName + " does not have the same size in both zip:", contain2.size(), contain1.size());
// not the same size assertArrayEquals("contents differ", contain1.toByteArray(), contain2.toByteArray());
Assert.fail(fileName
+ " does not have the same size in both zip:"
+ contain2.size() + "!=" + contain1.size());
return false;
}
byte array1[] = contain1.toByteArray();
byte array2[] = contain2.toByteArray();
for (int i = 0; i < array1.length; i++) {
if (array1[i] != array2[i]) {
Assert.fail(fileName + " differ at index:" + i);
return false;
}
}
}
} }
} else {
// not the same number of files -> cannot be equals
Assert.fail("not the same number of files in zip:"
+ listFile1.size() + "!=" + file2.keySet().size());
return false;
} }
return true;
} }
protected static TreeMap<String, ByteArrayOutputStream> decompress( protected static TreeMap<String, ByteArrayOutputStream> decompress(
@ -139,16 +117,16 @@ public class ZipFileAssert {
* *
*/ */
public static void assertEquals(File expected, File actual) { public static void assertEquals(File expected, File actual) {
Assert.assertNotNull(expected); assertNotNull(expected);
Assert.assertNotNull(actual); assertNotNull(actual);
Assert.assertTrue("File does not exist [" + expected.getAbsolutePath() assertTrue("File does not exist [" + expected.getAbsolutePath()
+ "]", expected.exists()); + "]", expected.exists());
Assert.assertTrue("File does not exist [" + actual.getAbsolutePath() assertTrue("File does not exist [" + actual.getAbsolutePath()
+ "]", actual.exists()); + "]", actual.exists());
Assert.assertTrue("Expected file not readable", expected.canRead()); assertTrue("Expected file not readable", expected.canRead());
Assert.assertTrue("Actual file not readable", actual.canRead()); assertTrue("Actual file not readable", actual.canRead());
try { try {
TreeMap<String, ByteArrayOutputStream> file1 = decompress(expected); TreeMap<String, ByteArrayOutputStream> file1 = decompress(expected);

View File

@ -133,11 +133,11 @@ public class OLE2ScratchpadExtractorFactory {
// Stored in the Attachment blocks // Stored in the Attachment blocks
MAPIMessage msg = ((OutlookTextExtactor)ext).getMAPIMessage(); MAPIMessage msg = ((OutlookTextExtactor)ext).getMAPIMessage();
for (AttachmentChunks attachment : msg.getAttachmentFiles()) { for (AttachmentChunks attachment : msg.getAttachmentFiles()) {
if (attachment.attachData != null) { if (attachment.getAttachData() != null) {
byte[] data = attachment.attachData.getValue(); byte[] data = attachment.getAttachData().getValue();
nonPOIFS.add( new ByteArrayInputStream(data) ); nonPOIFS.add( new ByteArrayInputStream(data) );
} else if (attachment.attachmentDirectory != null) { } else if (attachment.getAttachmentDirectory() != null) {
dirs.add(attachment.attachmentDirectory.getDirectory()); dirs.add(attachment.getAttachmentDirectory().getDirectory());
} }
} }
} }

View File

@ -17,159 +17,171 @@
package org.apache.poi.hpbf.extractor; package org.apache.poi.hpbf.extractor;
import java.io.File; import static org.junit.Assert.assertEquals;
import java.io.FileInputStream; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import junit.framework.TestCase; import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.hpbf.HPBFDocument; import org.apache.poi.hpbf.HPBFDocument;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
import org.junit.Test;
public final class TestPublisherTextExtractor extends TestCase { public final class TestPublisherTextExtractor {
private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance();
private static final String SAMPLE_TEXT = private static final String SAMPLE_TEXT =
"This is some text on the first page\n" + "This is some text on the first page\n" +
"It\u2019s in times new roman, font size 10, all normal\n" + "It\u2019s in times new roman, font size 10, all normal\n" +
"" + "" +
"This is in bold and italic\n" + "This is in bold and italic\n" +
"It\u2019s Arial, 20 point font\n" + "It\u2019s Arial, 20 point font\n" +
"It\u2019s in the second textbox on the first page\n" + "It\u2019s in the second textbox on the first page\n" +
"" + "" +
"This is the second page\n\n" + "This is the second page\n\n" +
"" + "" +
"It is also times new roman, 10 point\n" + "It is also times new roman, 10 point\n" +
"" + "" +
"Table on page 2\nTop right\n" + "Table on page 2\nTop right\n" +
"P2 table left\nP2 table right\n" + "P2 table left\nP2 table right\n" +
"Bottom Left\nBottom Right\n" + "Bottom Left\nBottom Right\n" +
"" + "" +
"This text is on page two\n" + "This text is on page two\n" +
"#This is a link to Apache POI\n" + "#This is a link to Apache POI\n" +
"More normal text\n" + "More normal text\n" +
"Link to a file\n" + "Link to a file\n" +
"" + "" +
"More text, more hyperlinks\n" + "More text, more hyperlinks\n" +
"email link\n" + "email link\n" +
"Final hyperlink\n" + "Final hyperlink\n" +
"Within doc to page 1\n"; "Within doc to page 1\n";
private static final String SIMPLE_TEXT = private static final String SIMPLE_TEXT =
"0123456789\n" + "0123456789\n" +
"0123456789abcdef\n" + "0123456789abcdef\n" +
"0123456789abcdef0123456789abcdef\n" + "0123456789abcdef0123456789abcdef\n" +
"0123456789\n" + "0123456789\n" +
"0123456789abcdef\n" + "0123456789abcdef\n" +
"0123456789abcdef0123456789abcdef\n" + "0123456789abcdef0123456789abcdef\n" +
"0123456789abcdef0123456789abcdef0123456789abcdef\n"; "0123456789abcdef0123456789abcdef0123456789abcdef\n";
public void testBasics() throws Exception { @Test
HPBFDocument doc = new HPBFDocument( public void testBasics() throws IOException {
_samples.openResourceAsStream("Sample.pub") InputStream sample = _samples.openResourceAsStream("Sample.pub");
); HPBFDocument doc = new HPBFDocument(sample);
PublisherTextExtractor ext = new PublisherTextExtractor(doc);
assertNotNull(ext.getText());
ext.close();
doc.close();
sample.close();
PublisherTextExtractor ext = InputStream simple = _samples.openResourceAsStream("Simple.pub");
new PublisherTextExtractor(doc); ext = new PublisherTextExtractor(simple);
ext.getText(); assertNotNull(ext.getText());
ext.close();
simple.close();
}
ext = new PublisherTextExtractor( @Test
_samples.openResourceAsStream("Simple.pub") public void testContents() throws IOException {
); // Check this complicated file using POIFS
ext.getText(); InputStream sample = _samples.openResourceAsStream("Sample.pub");
} HPBFDocument docOPOIFS = new HPBFDocument(sample);
PublisherTextExtractor ext = new PublisherTextExtractor(docOPOIFS);
assertEquals(SAMPLE_TEXT, ext.getText());
ext.close();
docOPOIFS.close();
sample.close();
public void testContents() throws Exception { // And with NPOIFS
PublisherTextExtractor ext; sample = _samples.openResourceAsStream("Sample.pub");
File sample = _samples.getFile("Sample.pub"); NPOIFSFileSystem fs = new NPOIFSFileSystem(sample);
File simple = _samples.getFile("Simple.pub"); HPBFDocument docNPOIFS = new HPBFDocument(fs);
ext = new PublisherTextExtractor(docNPOIFS);
// Check this complicated file using POIFS assertEquals(SAMPLE_TEXT, ext.getText());
HPBFDocument docOPOIFS = new HPBFDocument( ext.close();
new FileInputStream(sample) docNPOIFS.close();
); fs.close();
ext = new PublisherTextExtractor(docOPOIFS); sample.close();
assertEquals( SAMPLE_TEXT, ext.getText() );
// And with NPOIFS // Now a simpler file
NPOIFSFileSystem fs = new NPOIFSFileSystem(sample); InputStream simple = _samples.openResourceAsStream("Simple.pub");
HPBFDocument docNPOIFS = new HPBFDocument( ext = new PublisherTextExtractor(simple);
fs assertEquals(SIMPLE_TEXT, ext.getText());
); ext.close();
ext = new PublisherTextExtractor(docNPOIFS); }
assertEquals( SAMPLE_TEXT, ext.getText() );
/**
// Now a simpler file * We have the same file saved for Publisher 98, Publisher 2000 and
ext = new PublisherTextExtractor( * Publisher 2007. Check they all agree.
new FileInputStream(simple) *
); * @throws Exception
assertEquals( SIMPLE_TEXT, ext.getText() ); */
fs.close(); @Test
} public void testMultipleVersions() throws Exception {
InputStream sample = _samples.openResourceAsStream("Sample.pub");
HPBFDocument doc = new HPBFDocument(sample);
PublisherTextExtractor ext = new PublisherTextExtractor(doc);
String s2007 = ext.getText();
ext.close();
doc.close();
sample.close();
/** InputStream sample2000 = _samples.openResourceAsStream("Sample2000.pub");
* We have the same file saved for Publisher 98, Publisher doc = new HPBFDocument(sample2000);
* 2000 and Publisher 2007. Check they all agree. ext = new PublisherTextExtractor(doc);
* @throws Exception String s2000 = ext.getText();
*/ ext.close();
public void testMultipleVersions() throws Exception { doc.close();
File f; sample2000.close();
HPBFDocument doc;
doc = new HPBFDocument( InputStream sample98 = _samples.openResourceAsStream("Sample98.pub");
_samples.openResourceAsStream("Sample.pub") doc = new HPBFDocument(sample98);
); ext = new PublisherTextExtractor(doc);
String s2007 = (new PublisherTextExtractor(doc)).getText(); String s98 = ext.getText();
ext.close();
doc.close();
sample98.close();
doc = new HPBFDocument( // Check they all agree
_samples.openResourceAsStream("Sample2000.pub") assertEquals(s2007, s2000);
); assertEquals(s2007, s98);
String s2000 = (new PublisherTextExtractor(doc)).getText(); }
doc = new HPBFDocument( /**
_samples.openResourceAsStream("Sample98.pub") * Test that the hyperlink extraction stuff works as well as we can hope it
); * to.
String s98 = (new PublisherTextExtractor(doc)).getText(); */
@Test
public void testWithHyperlinks() throws Exception {
InputStream linkAt = _samples.openResourceAsStream("LinkAt10.pub");
HPBFDocument doc = new HPBFDocument(linkAt);
// Check they all agree PublisherTextExtractor ext = new PublisherTextExtractor(doc);
assertEquals(s2007, s2000);
assertEquals(s2007, s98);
}
/** // Default is no hyperlinks
* Test that the hyperlink extraction stuff works as well assertEquals("1234567890LINK\n", ext.getText());
* as we can hope it to.
*/
public void testWithHyperlinks() throws Exception {
HPBFDocument doc = new HPBFDocument(
_samples.openResourceAsStream("LinkAt10.pub")
);
PublisherTextExtractor ext = // Turn on
new PublisherTextExtractor(doc); ext.setHyperlinksByDefault(true);
ext.getText(); assertEquals("1234567890LINK\n<http://poi.apache.org/>\n", ext.getText());
ext.close();
doc.close();
linkAt.close();
// Default is no hyperlinks // Now a much more complex document
assertEquals("1234567890LINK\n", ext.getText()); InputStream sample = _samples.openResourceAsStream("Sample.pub");
ext = new PublisherTextExtractor(sample);
ext.setHyperlinksByDefault(true);
String text = ext.getText();
ext.close();
sample.close();
// Turn on assertTrue(text.endsWith("<http://poi.apache.org/>\n"
ext.setHyperlinksByDefault(true); + "<C:\\Documents and Settings\\Nick\\My Documents\\Booleans.xlsx>\n"
assertEquals("1234567890LINK\n<http://poi.apache.org/>\n", ext.getText()); + "<>\n" + "<mailto:dev@poi.apache.org?subject=HPBF>\n"
+ "<mailto:dev@poi.apache.org?subject=HPBF>\n"));
}
// Now a much more complex document
ext = new PublisherTextExtractor(
_samples.openResourceAsStream("Sample.pub")
);
ext.setHyperlinksByDefault(true);
String text = ext.getText();
assertTrue(text.endsWith(
"<http://poi.apache.org/>\n" +
"<C:\\Documents and Settings\\Nick\\My Documents\\Booleans.xlsx>\n" +
"<>\n" +
"<mailto:dev@poi.apache.org?subject=HPBF>\n" +
"<mailto:dev@poi.apache.org?subject=HPBF>\n"
));
}
} }

View File

@ -17,20 +17,27 @@
package org.apache.poi.hpbf.model; package org.apache.poi.hpbf.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hpbf.HPBFDocument; import org.apache.poi.hpbf.HPBFDocument;
import org.apache.poi.hpbf.model.qcbits.QCTextBit;
import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type12;
import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type0; import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type0;
import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type12;
import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type4; import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type4;
import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type8; import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type8;
import org.apache.poi.POIDataSamples; import org.apache.poi.hpbf.model.qcbits.QCTextBit;
import org.junit.Test;
import junit.framework.TestCase; public final class TestQuillContents {
public final class TestQuillContents extends TestCase {
private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance();
public void testBasics() throws Exception { @Test
public void testBasics() throws IOException {
HPBFDocument doc = new HPBFDocument( HPBFDocument doc = new HPBFDocument(
_samples.openResourceAsStream("Sample.pub") _samples.openResourceAsStream("Sample.pub")
); );
@ -59,9 +66,12 @@ public final class TestQuillContents extends TestCase {
assertEquals("STSH", qc.getBits()[3].getThingType()); assertEquals("STSH", qc.getBits()[3].getThingType());
assertEquals("STSH", qc.getBits()[3].getBitType()); assertEquals("STSH", qc.getBits()[3].getBitType());
assertEquals(2, qc.getBits()[3].getOptA()); assertEquals(2, qc.getBits()[3].getOptA());
doc.close();
} }
public void testText() throws Exception { @Test
public void testText() throws IOException {
HPBFDocument doc = new HPBFDocument( HPBFDocument doc = new HPBFDocument(
_samples.openResourceAsStream("Sample.pub") _samples.openResourceAsStream("Sample.pub")
); );
@ -73,9 +83,12 @@ public final class TestQuillContents extends TestCase {
String t = text.getText(); String t = text.getText();
assertTrue(t.startsWith("This is some text on the first page")); assertTrue(t.startsWith("This is some text on the first page"));
assertTrue(t.endsWith("Within doc to page 1\r")); assertTrue(t.endsWith("Within doc to page 1\r"));
doc.close();
} }
public void testPLC() throws Exception { @Test
public void testPLC() throws IOException {
HPBFDocument doc = new HPBFDocument( HPBFDocument doc = new HPBFDocument(
_samples.openResourceAsStream("Simple.pub") _samples.openResourceAsStream("Simple.pub")
); );
@ -133,9 +146,13 @@ public final class TestQuillContents extends TestCase {
assertEquals(0x22000000, plc12.getPlcValB()[0]); assertEquals(0x22000000, plc12.getPlcValB()[0]);
assertEquals(0x05, plc12.getPlcValA()[1]); assertEquals(0x05, plc12.getPlcValA()[1]);
assertEquals(0x04, plc12.getPlcValB()[1]); assertEquals(0x04, plc12.getPlcValB()[1]);
doc.close();
} }
public void testComplexPLC() throws Exception { @SuppressWarnings("unused")
@Test
public void testComplexPLC() throws IOException {
HPBFDocument doc = new HPBFDocument( HPBFDocument doc = new HPBFDocument(
_samples.openResourceAsStream("Sample.pub") _samples.openResourceAsStream("Sample.pub")
); );
@ -234,9 +251,12 @@ public final class TestQuillContents extends TestCase {
assertEquals(0x000004, plc16.getPlcValB()[4]); assertEquals(0x000004, plc16.getPlcValB()[4]);
assertEquals(0x000004, plc16.getPlcValA()[5]); assertEquals(0x000004, plc16.getPlcValA()[5]);
assertEquals(0x000004, plc16.getPlcValB()[5]); assertEquals(0x000004, plc16.getPlcValB()[5]);
doc.close();
} }
public void testNoHyperlinks() throws Exception { @Test
public void testNoHyperlinks() throws IOException {
HPBFDocument doc = new HPBFDocument( HPBFDocument doc = new HPBFDocument(
_samples.openResourceAsStream("SampleNewsletter.pub") _samples.openResourceAsStream("SampleNewsletter.pub")
); );
@ -250,9 +270,12 @@ public final class TestQuillContents extends TestCase {
assertEquals(0, plc18.getNumberOfHyperlinks()); assertEquals(0, plc18.getNumberOfHyperlinks());
assertEquals(0, plc18.getTextStartAt(0)); assertEquals(0, plc18.getTextStartAt(0));
assertEquals(601, plc18.getAllTextEndAt()); assertEquals(601, plc18.getAllTextEndAt());
doc.close();
} }
public void testSimpleHyperlink() throws Exception { @Test
public void testSimpleHyperlink() throws IOException {
HPBFDocument doc; HPBFDocument doc;
QuillContents qc; QuillContents qc;
Type12 hlBit; Type12 hlBit;
@ -270,6 +293,7 @@ public final class TestQuillContents extends TestCase {
assertEquals(10, hlBit.getTextStartAt(0)); assertEquals(10, hlBit.getTextStartAt(0));
assertEquals(15, hlBit.getAllTextEndAt()); assertEquals(15, hlBit.getAllTextEndAt());
assertEquals("http://poi.apache.org/", hlBit.getHyperlink(0)); assertEquals("http://poi.apache.org/", hlBit.getHyperlink(0));
doc.close();
// Longer link at 10 // Longer link at 10
doc = new HPBFDocument( doc = new HPBFDocument(
@ -284,6 +308,7 @@ public final class TestQuillContents extends TestCase {
assertEquals(10, hlBit.getTextStartAt(0)); assertEquals(10, hlBit.getTextStartAt(0));
assertEquals(15, hlBit.getAllTextEndAt()); assertEquals(15, hlBit.getAllTextEndAt());
assertEquals("http://poi.apache.org/hpbf/", hlBit.getHyperlink(0)); assertEquals("http://poi.apache.org/hpbf/", hlBit.getHyperlink(0));
doc.close();
// Link at 20 // Link at 20
doc = new HPBFDocument( doc = new HPBFDocument(
@ -298,9 +323,11 @@ public final class TestQuillContents extends TestCase {
assertEquals(20, hlBit.getTextStartAt(0)); assertEquals(20, hlBit.getTextStartAt(0));
assertEquals(25, hlBit.getAllTextEndAt()); assertEquals(25, hlBit.getAllTextEndAt());
assertEquals("http://poi.apache.org/", hlBit.getHyperlink(0)); assertEquals("http://poi.apache.org/", hlBit.getHyperlink(0));
doc.close();
} }
public void testManyHyperlinks() throws Exception { @Test
public void testManyHyperlinks() throws IOException {
HPBFDocument doc; HPBFDocument doc;
QuillContents qc; QuillContents qc;
Type12 hlBit; Type12 hlBit;
@ -318,10 +345,12 @@ public final class TestQuillContents extends TestCase {
assertEquals(10, hlBit.getTextStartAt(0)); assertEquals(10, hlBit.getTextStartAt(0));
assertEquals(15, hlBit.getAllTextEndAt()); assertEquals(15, hlBit.getAllTextEndAt());
assertEquals("http://poi.apache.org/", hlBit.getHyperlink(0)); assertEquals("http://poi.apache.org/", hlBit.getHyperlink(0));
doc.close();
} }
public void testHyperlinkDifferentVersions() throws Exception { @Test
public void testHyperlinkDifferentVersions() throws IOException {
HPBFDocument doc; HPBFDocument doc;
QuillContents qc; QuillContents qc;
Type12 hlBitA; Type12 hlBitA;
@ -354,6 +383,7 @@ public final class TestQuillContents extends TestCase {
assertEquals("", hlBitB.getHyperlink(0)); assertEquals("", hlBitB.getHyperlink(0));
assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(1)); assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(1));
assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(2)); assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(2));
doc.close();
// 2000 version // 2000 version
doc = new HPBFDocument( doc = new HPBFDocument(
@ -382,6 +412,7 @@ public final class TestQuillContents extends TestCase {
assertEquals("", hlBitB.getHyperlink(0)); assertEquals("", hlBitB.getHyperlink(0));
assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(1)); assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(1));
assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(2)); assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(2));
doc.close();
// 98 version // 98 version
doc = new HPBFDocument( doc = new HPBFDocument(
@ -410,5 +441,6 @@ public final class TestQuillContents extends TestCase {
assertEquals("", hlBitB.getHyperlink(0)); assertEquals("", hlBitB.getHyperlink(0));
assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(1)); assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(1));
assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(2)); assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(2));
} doc.close();
}
} }

View File

@ -18,46 +18,58 @@
package org.apache.poi.hslf; package org.apache.poi.hslf;
import junit.framework.TestCase; import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
import org.apache.poi.POIDataSamples; import org.junit.Test;
/** /**
* Tests that HSLFSlideShow does the right thing with an encrypted file * Tests that HSLFSlideShow does the right thing with an encrypted file
*
* @author Nick Burch (nick at torchbox dot com)
*/ */
public final class TestEncryptedFile extends TestCase { public final class TestEncryptedFile {
private static POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
public void testLoadNonEncrypted() throws Exception {
HSLFSlideShowImpl hss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt"));
@Test
public void testLoadNonEncrypted() throws IOException {
InputStream is = slTests.openResourceAsStream("basic_test_ppt_file.ppt");
HSLFSlideShowImpl hss = new HSLFSlideShowImpl(is);
assertNotNull(hss); assertNotNull(hss);
hss.close();
is.close();
} }
public void testLoadEncrypted() throws Exception { @Test(expected=EncryptedPowerPointFileException.class)
public void testLoadEncrypted1() throws IOException {
InputStream is = slTests.openResourceAsStream("Password_Protected-hello.ppt");
try { try {
new HSLFSlideShowImpl(slTests.openResourceAsStream("Password_Protected-hello.ppt")); new HSLFSlideShowImpl(is).close();
fail(); } finally {
} catch(EncryptedPowerPointFileException e) { is.close();
// Good
} }
}
@Test(expected=EncryptedPowerPointFileException.class)
public void testLoadEncrypted2() throws IOException {
InputStream is = slTests.openResourceAsStream("Password_Protected-np-hello.ppt");
try { try {
new HSLFSlideShowImpl(slTests.openResourceAsStream("Password_Protected-np-hello.ppt")); new HSLFSlideShowImpl(is).close();
fail(); } finally {
} catch(EncryptedPowerPointFileException e) { is.close();
// Good
} }
}
@Test(expected=EncryptedPowerPointFileException.class)
public void testLoadEncrypted3() throws IOException {
InputStream is = slTests.openResourceAsStream("Password_Protected-56-hello.ppt");
try { try {
new HSLFSlideShowImpl(slTests.openResourceAsStream("Password_Protected-56-hello.ppt")); new HSLFSlideShowImpl(is).close();
fail(); } finally {
} catch(EncryptedPowerPointFileException e) { is.close();
// Good
} }
} }
} }

View File

@ -77,7 +77,7 @@ public class TestDocumentEncryption {
try { try {
NPOIFSFileSystem fs = new NPOIFSFileSystem(slTests.getFile(pptFile), true); NPOIFSFileSystem fs = new NPOIFSFileSystem(slTests.getFile(pptFile), true);
HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs); HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs);
new HSLFSlideShow(hss); new HSLFSlideShow(hss).close();
fs.close(); fs.close();
} catch (EncryptedPowerPointFileException e) { } catch (EncryptedPowerPointFileException e) {
fail(pptFile+" can't be decrypted"); fail(pptFile+" can't be decrypted");
@ -99,17 +99,19 @@ public class TestDocumentEncryption {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
hss.write(bos); hss.write(bos);
hss.close();
fs.close(); fs.close();
fs = new NPOIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); fs = new NPOIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
hss = new HSLFSlideShowImpl(fs); hss = new HSLFSlideShowImpl(fs);
List<HSLFPictureData> picsActual = hss.getPictureData(); List<HSLFPictureData> picsActual = hss.getPictureData();
fs.close();
assertEquals(picsExpected.size(), picsActual.size()); assertEquals(picsExpected.size(), picsActual.size());
for (int i=0; i<picsExpected.size(); i++) { for (int i=0; i<picsExpected.size(); i++) {
assertArrayEquals(picsExpected.get(i).getRawData(), picsActual.get(i).getRawData()); assertArrayEquals(picsExpected.get(i).getRawData(), picsActual.get(i).getRawData());
} }
hss.close();
fs.close();
} }
@Test @Test
@ -128,6 +130,7 @@ public class TestDocumentEncryption {
Biff8EncryptionKey.setCurrentUserPassword("hello"); Biff8EncryptionKey.setCurrentUserPassword("hello");
ByteArrayOutputStream encrypted = new ByteArrayOutputStream(); ByteArrayOutputStream encrypted = new ByteArrayOutputStream();
hss.write(encrypted); hss.write(encrypted);
hss.close();
fs.close(); fs.close();
// decrypted // decrypted
@ -137,6 +140,7 @@ public class TestDocumentEncryption {
Biff8EncryptionKey.setCurrentUserPassword(null); Biff8EncryptionKey.setCurrentUserPassword(null);
ByteArrayOutputStream actual = new ByteArrayOutputStream(); ByteArrayOutputStream actual = new ByteArrayOutputStream();
hss.write(actual); hss.write(actual);
hss.close();
fs.close(); fs.close();
assertArrayEquals(expected.toByteArray(), actual.toByteArray()); assertArrayEquals(expected.toByteArray(), actual.toByteArray());
@ -184,6 +188,7 @@ 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());
ss.close();
fs.close(); fs.close();
fs2.close(); fs2.close();
} }

View File

@ -847,7 +847,6 @@ public final class TestBugs {
} }
@Test @Test
@SuppressWarnings("resource")
public void bug57796() throws IOException { public void bug57796() throws IOException {
HSLFSlideShow ppt = open("WithLinks.ppt"); HSLFSlideShow ppt = open("WithLinks.ppt");
HSLFSlide slide = ppt.getSlides().get(0); HSLFSlide slide = ppt.getSlides().get(0);
@ -859,7 +858,7 @@ public final class TestBugs {
assertEquals(hlRun.getId(), hlShape.getId()); assertEquals(hlRun.getId(), hlShape.getId());
assertEquals(hlRun.getAddress(), hlShape.getAddress()); assertEquals(hlRun.getAddress(), hlShape.getAddress());
assertEquals(hlRun.getLabel(), hlShape.getLabel()); assertEquals(hlRun.getLabel(), hlShape.getLabel());
assertEquals(hlRun.getType(), hlShape.getType()); assertEquals(hlRun.getTypeEnum(), hlShape.getTypeEnum());
assertEquals(hlRun.getStartIndex(), hlShape.getStartIndex()); assertEquals(hlRun.getStartIndex(), hlShape.getStartIndex());
assertEquals(hlRun.getEndIndex(), hlShape.getEndIndex()); assertEquals(hlRun.getEndIndex(), hlShape.getEndIndex());
@ -999,9 +998,16 @@ public final class TestBugs {
long persistId = vbaAtom.getPersistIdRef(); long persistId = vbaAtom.getPersistIdRef();
for (HSLFObjectData objData : ppt.getEmbeddedObjects()) { for (HSLFObjectData objData : ppt.getEmbeddedObjects()) {
if (objData.getExOleObjStg().getPersistId() == persistId) { if (objData.getExOleObjStg().getPersistId() == persistId) {
return new VBAMacroReader(objData.getData()).readMacros(); VBAMacroReader mr = new VBAMacroReader(objData.getData());
try {
return mr.readMacros();
} finally {
mr.close();
}
} }
} }
ppt.close();
} finally { } finally {
IOUtils.closeQuietly(npoifs); IOUtils.closeQuietly(npoifs);

View File

@ -260,14 +260,14 @@ public final class TestPOIFSChunkParser {
assertTrue(groups[4] instanceof NameIdChunks); assertTrue(groups[4] instanceof NameIdChunks);
attachment = (AttachmentChunks)groups[2]; attachment = (AttachmentChunks)groups[2];
assertEquals("TEST-U~1.DOC", attachment.attachFileName.toString()); assertEquals("TEST-U~1.DOC", attachment.getAttachFileName().toString());
assertEquals("test-unicode.doc", attachment.attachLongFileName.toString()); assertEquals("test-unicode.doc", attachment.getAttachLongFileName().toString());
assertEquals(24064, attachment.attachData.getValue().length); assertEquals(24064, attachment.getAttachData().getValue().length);
attachment = (AttachmentChunks)groups[3]; attachment = (AttachmentChunks)groups[3];
assertEquals("pj1.txt", attachment.attachFileName.toString()); assertEquals("pj1.txt", attachment.getAttachFileName().toString());
assertEquals("pj1.txt", attachment.attachLongFileName.toString()); assertEquals("pj1.txt", attachment.getAttachLongFileName().toString());
assertEquals(89, attachment.attachData.getValue().length); assertEquals(89, attachment.getAttachData().getValue().length);
// Check raw details on one without // Check raw details on one without
@ -279,14 +279,14 @@ public final class TestPOIFSChunkParser {
assertEquals(2, msgWith.getAttachmentFiles().length); assertEquals(2, msgWith.getAttachmentFiles().length);
attachment = msgWith.getAttachmentFiles()[0]; attachment = msgWith.getAttachmentFiles()[0];
assertEquals("TEST-U~1.DOC", attachment.attachFileName.toString()); assertEquals("TEST-U~1.DOC", attachment.getAttachFileName().toString());
assertEquals("test-unicode.doc", attachment.attachLongFileName.toString()); assertEquals("test-unicode.doc", attachment.getAttachLongFileName().toString());
assertEquals(24064, attachment.attachData.getValue().length); assertEquals(24064, attachment.getAttachData().getValue().length);
attachment = msgWith.getAttachmentFiles()[1]; attachment = msgWith.getAttachmentFiles()[1];
assertEquals("pj1.txt", attachment.attachFileName.toString()); assertEquals("pj1.txt", attachment.getAttachFileName().toString());
assertEquals("pj1.txt", attachment.attachLongFileName.toString()); assertEquals("pj1.txt", attachment.getAttachLongFileName().toString());
assertEquals(89, attachment.attachData.getValue().length); assertEquals(89, attachment.getAttachData().getValue().length);
// Plus check core details are there // Plus check core details are there
assertEquals("'nicolas1.23456@free.fr'", msgWith.getDisplayTo()); assertEquals("'nicolas1.23456@free.fr'", msgWith.getDisplayTo());

View File

@ -17,126 +17,130 @@
package org.apache.poi.hwpf.usermodel; package org.apache.poi.hwpf.usermodel;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.poi.OldFileFormatException; import org.apache.poi.OldFileFormatException;
import org.apache.poi.hwpf.HWPFOldDocument; import org.apache.poi.hwpf.HWPFOldDocument;
import org.apache.poi.hwpf.HWPFTestCase; import org.apache.poi.hwpf.HWPFTestCase;
import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.HWPFTestDataSamples;
import org.junit.Test;
/** /**
* Tests for Word 6 and Word 95 support * Tests for Word 6 and Word 95 support
*/ */
public final class TestHWPFOldDocument extends HWPFTestCase { public final class TestHWPFOldDocument extends HWPFTestCase {
/** /**
* Test a simple Word 6 document * Test a simple Word 6 document
*/ */
public void testWord6() throws Exception { @Test(expected=OldFileFormatException.class)
// Can't open as HWPFDocument public void testWord6hwpf() throws IOException {
try { // Can't open as HWPFDocument
HWPFTestDataSamples.openSampleFile("Word6.doc"); HWPFTestDataSamples.openSampleFile("Word6.doc");
fail("Shouldn't be openable"); }
} catch(OldFileFormatException e) {}
@Test
// Open public void testWord6hwpfOld() throws IOException {
HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Word6.doc"); // Open
HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Word6.doc");
// Check
assertEquals(1, doc.getRange().numSections()); // Check
assertEquals(1, doc.getRange().numParagraphs()); assertEquals(1, doc.getRange().numSections());
assertEquals(1, doc.getRange().numCharacterRuns()); assertEquals(1, doc.getRange().numParagraphs());
assertEquals(1, doc.getRange().numCharacterRuns());
assertEquals(
"The quick brown fox jumps over the lazy dog\r", assertEquals("The quick brown fox jumps over the lazy dog\r",
doc.getRange().getParagraph(0).text() doc.getRange().getParagraph(0).text());
); doc.close();
} }
/**
* Test a simple Word 95 document
*/ /**
public void testWord95() throws Exception { * Test a simple Word 95 document
// Can't open as HWPFDocument */
try { @Test(expected=OldFileFormatException.class)
HWPFTestDataSamples.openSampleFile("Word95.doc"); public void testWord95hwpf() throws IOException {
fail("Shouldn't be openable"); // Can't open as HWPFDocument
} catch(OldFileFormatException e) {} HWPFTestDataSamples.openSampleFile("Word95.doc");
}
// Open
HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Word95.doc"); @Test
public void testWord95hwpfOld() throws IOException {
// Check // Open
assertEquals(1, doc.getRange().numSections()); HWPFOldDocument doc = HWPFTestDataSamples
assertEquals(7, doc.getRange().numParagraphs()); .openOldSampleFile("Word95.doc");
assertEquals( // Check
"The quick brown fox jumps over the lazy dog\r", assertEquals(1, doc.getRange().numSections());
doc.getRange().getParagraph(0).text() assertEquals(7, doc.getRange().numParagraphs());
);
assertEquals("\r", doc.getRange().getParagraph(1).text()); assertEquals("The quick brown fox jumps over the lazy dog\r",
assertEquals( doc.getRange().getParagraph(0).text());
"Paragraph 2\r", assertEquals("\r", doc.getRange().getParagraph(1).text());
doc.getRange().getParagraph(2).text() assertEquals("Paragraph 2\r", doc.getRange().getParagraph(2).text());
); assertEquals("\r", doc.getRange().getParagraph(3).text());
assertEquals("\r", doc.getRange().getParagraph(3).text()); assertEquals(
assertEquals( "Paragraph 3. Has some RED text and some "
"Paragraph 3. Has some RED text and some " + + "BLUE BOLD text in it.\r",
"BLUE BOLD text in it.\r", doc.getRange().getParagraph(4).text());
doc.getRange().getParagraph(4).text() assertEquals("\r", doc.getRange().getParagraph(5).text());
); assertEquals("Last (4th) paragraph.\r",
assertEquals("\r", doc.getRange().getParagraph(5).text()); doc.getRange().getParagraph(6).text());
assertEquals(
"Last (4th) paragraph.\r", assertEquals(1, doc.getRange().getParagraph(0).numCharacterRuns());
doc.getRange().getParagraph(6).text() assertEquals(1, doc.getRange().getParagraph(1).numCharacterRuns());
); assertEquals(1, doc.getRange().getParagraph(2).numCharacterRuns());
assertEquals(1, doc.getRange().getParagraph(3).numCharacterRuns());
assertEquals(1, doc.getRange().getParagraph(0).numCharacterRuns()); // Normal, red, normal, blue+bold, normal
assertEquals(1, doc.getRange().getParagraph(1).numCharacterRuns()); assertEquals(5, doc.getRange().getParagraph(4).numCharacterRuns());
assertEquals(1, doc.getRange().getParagraph(2).numCharacterRuns()); assertEquals(1, doc.getRange().getParagraph(5).numCharacterRuns());
assertEquals(1, doc.getRange().getParagraph(3).numCharacterRuns()); // Normal, superscript for 4th, normal
// Normal, red, normal, blue+bold, normal assertEquals(3, doc.getRange().getParagraph(6).numCharacterRuns());
assertEquals(5, doc.getRange().getParagraph(4).numCharacterRuns());
assertEquals(1, doc.getRange().getParagraph(5).numCharacterRuns()); doc.close();
// Normal, superscript for 4th, normal }
assertEquals(3, doc.getRange().getParagraph(6).numCharacterRuns());
} /**
* Test a word document that has sections, as well as the usual paragraph
/** * stuff.
* Test a word document that has sections, */
* as well as the usual paragraph stuff. @Test
*/ public void testWord6Sections() throws IOException {
public void testWord6Sections() throws Exception { HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Word6_sections.doc");
HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Word6_sections.doc");
assertEquals(3, doc.getRange().numSections());
assertEquals(3, doc.getRange().numSections()); assertEquals(6, doc.getRange().numParagraphs());
assertEquals(6, doc.getRange().numParagraphs());
assertEquals("This is a test.\r",
assertEquals( doc.getRange().getParagraph(0).text());
"This is a test.\r", assertEquals("\r", doc.getRange().getParagraph(1).text());
doc.getRange().getParagraph(0).text() // Section / line?
); assertEquals("\u000c", doc.getRange().getParagraph(2).text());
assertEquals("\r", doc.getRange().getParagraph(1).text()); assertEquals("This is a new section.\r",
assertEquals("\u000c", doc.getRange().getParagraph(2).text()); // Section line? doc.getRange().getParagraph(3).text());
assertEquals("This is a new section.\r", doc.getRange().getParagraph(3).text()); // Section / line?
assertEquals("\u000c", doc.getRange().getParagraph(4).text()); // Section line? assertEquals("\u000c", doc.getRange().getParagraph(4).text());
assertEquals("\r", doc.getRange().getParagraph(5).text()); assertEquals("\r", doc.getRange().getParagraph(5).text());
} doc.close();
}
/**
* Another word document with sections, this time with a /**
* few more section properties set on it * Another word document with sections, this time with a few more section
*/ * properties set on it
public void testWord6Sections2() throws Exception { */
HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Word6_sections2.doc"); @Test
public void testWord6Sections2() throws IOException {
assertEquals(1, doc.getRange().numSections()); HWPFOldDocument doc = HWPFTestDataSamples
assertEquals(57, doc.getRange().numParagraphs()); .openOldSampleFile("Word6_sections2.doc");
assertEquals( assertEquals(1, doc.getRange().numSections());
"\r", assertEquals(57, doc.getRange().numParagraphs());
doc.getRange().getParagraph(0).text()
); assertEquals("\r", doc.getRange().getParagraph(0).text());
assertEquals( assertEquals("STATEMENT OF INSOLVENCY PRACTICE 10 (SCOTLAND)\r",
"STATEMENT OF INSOLVENCY PRACTICE 10 (SCOTLAND)\r", doc.getRange().getParagraph(1).text());
doc.getRange().getParagraph(1).text() doc.close();
); }
}
} }

View File

@ -17,7 +17,15 @@
package org.apache.poi.hwpf.usermodel; package org.apache.poi.hwpf.usermodel;
import java.io.*; import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFDocument;
@ -28,131 +36,138 @@ import org.apache.poi.poifs.filesystem.OPOIFSFileSystem;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils; import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFile;
import org.junit.Test;
/** /**
* Test various write situations * Test various write situations
*/ */
public final class TestHWPFWrite extends HWPFTestCase { public final class TestHWPFWrite extends HWPFTestCase {
/** private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance();
* Write to a stream
*/ /**
public void testWriteStream() throws Exception { * Write to a stream
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc"); */
@Test
public void testWriteStream() throws IOException {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc");
Range r = doc.getRange(); Range r = doc.getRange();
assertEquals("I am a test document\r", r.getParagraph(0).text()); assertEquals("I am a test document\r", r.getParagraph(0).text());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.write(baos);
doc.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
doc = new HWPFDocument(bais);
r = doc.getRange();
assertEquals("I am a test document\r", r.getParagraph(0).text());
doc.close();
}
/**
* Write to a new file
*/
public void testWriteNewFile() throws Exception {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc");
Range r = doc.getRange(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
assertEquals("I am a test document\r", r.getParagraph(0).text()); doc.write(baos);
doc.close();
File file = TempFile.createTempFile("TestDocument", ".doc"); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
doc.write(file);
doc.close();
// Check reading from File and Stream doc = new HWPFDocument(bais);
doc = new HWPFDocument(new FileInputStream(file)); r = doc.getRange();
r = doc.getRange(); assertEquals("I am a test document\r", r.getParagraph(0).text());
assertEquals("I am a test document\r", r.getParagraph(0).text()); doc.close();
doc.close(); }
doc = new HWPFDocument(new POIFSFileSystem(file));
r = doc.getRange();
assertEquals("I am a test document\r", r.getParagraph(0).text());
doc.close();
}
/**
* Writing to the file we opened from - note, uses a temp file to
* avoid changing our test files!
*/
@SuppressWarnings("resource")
public void testInPlaceWrite() throws Exception {
// Setup as a copy of a known-good file
final File file = TempFile.createTempFile("TestDocument", ".doc");
InputStream inputStream = POIDataSamples.getDocumentInstance().openResourceAsStream("SampleDoc.doc");
try {
FileOutputStream outputStream = new FileOutputStream(file);
try {
IOUtils.copy(inputStream, outputStream);
} finally {
outputStream.close();
}
} finally {
inputStream.close();
}
// Open from the temp file in read-write mode /**
HWPFDocument doc = new HWPFDocument(new NPOIFSFileSystem(file, false).getRoot()); * Write to a new file
Range r = doc.getRange(); */
assertEquals("I am a test document\r", r.getParagraph(0).text()); @Test
public void testWriteNewFile() throws IOException {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc");
// Change Range r = doc.getRange();
r.replaceText("X XX a test document\r", false); assertEquals("I am a test document\r", r.getParagraph(0).text());
// Save in-place, close, re-open and check File file = TempFile.createTempFile("TestDocument", ".doc");
doc.write(); doc.write(file);
doc.close(); doc.close();
doc = new HWPFDocument(new NPOIFSFileSystem(file).getRoot()); // Check reading from File and Stream
r = doc.getRange(); doc = new HWPFDocument(new FileInputStream(file));
assertEquals("X XX a test document\r", r.getParagraph(0).text()); r = doc.getRange();
doc.close(); assertEquals("I am a test document\r", r.getParagraph(0).text());
} doc.close();
@SuppressWarnings("resource") doc = new HWPFDocument(new POIFSFileSystem(file));
public void testInvalidInPlaceWrite() throws Exception { r = doc.getRange();
HWPFDocument doc; assertEquals("I am a test document\r", r.getParagraph(0).text());
doc.close();
}
// Can't work for InputStream opened files /**
doc = new HWPFDocument( * Writing to the file we opened from - note, uses a temp file to avoid
POIDataSamples.getDocumentInstance().openResourceAsStream("SampleDoc.doc")); * changing our test files!
try { */
doc.write(); @Test
fail("Shouldn't work for InputStream"); public void testInPlaceWrite() throws Exception {
} catch (IllegalStateException e) { // Setup as a copy of a known-good file
// expected here final File file = TempFile.createTempFile("TestDocument", ".doc");
} InputStream inputStream = SAMPLES.openResourceAsStream("SampleDoc.doc");
doc.close(); try {
FileOutputStream outputStream = new FileOutputStream(file);
try {
IOUtils.copy(inputStream, outputStream);
} finally {
outputStream.close();
}
} finally {
inputStream.close();
}
// Can't work for OPOIFS // Open from the temp file in read-write mode
OPOIFSFileSystem ofs = new OPOIFSFileSystem( NPOIFSFileSystem poifs = new NPOIFSFileSystem(file, false);
POIDataSamples.getDocumentInstance().openResourceAsStream("SampleDoc.doc")); HWPFDocument doc = new HWPFDocument(poifs.getRoot());
doc = new HWPFDocument(ofs.getRoot()); Range r = doc.getRange();
try { assertEquals("I am a test document\r", r.getParagraph(0).text());
doc.write();
fail("Shouldn't work for OPOIFSFileSystem");
} catch (IllegalStateException e) {
// expected here
}
doc.close();
// Can't work for Read-Only files // Change
NPOIFSFileSystem fs = new NPOIFSFileSystem( r.replaceText("X XX a test document\r", false);
POIDataSamples.getDocumentInstance().getFile("SampleDoc.doc"), true);
doc = new HWPFDocument(fs.getRoot()); // Save in-place, close, re-open and check
try { doc.write();
doc.write(); doc.close();
fail("Shouldn't work for Read Only"); poifs.close();
} catch (IllegalStateException e) {
// expected here poifs = new NPOIFSFileSystem(file);
} doc = new HWPFDocument(poifs.getRoot());
doc.close(); r = doc.getRange();
} assertEquals("X XX a test document\r", r.getParagraph(0).text());
doc.close();
poifs.close();
}
@Test(expected=IllegalStateException.class)
public void testInvalidInPlaceWriteInputStream() throws IOException {
// Can't work for InputStream opened files
InputStream is = SAMPLES.openResourceAsStream("SampleDoc.doc");
HWPFDocument doc = new HWPFDocument(is);
is.close();
try {
doc.write();
} finally {
doc.close();
}
}
@Test(expected=IllegalStateException.class)
public void testInvalidInPlaceWriteOPOIFS() throws Exception {
// Can't work for OPOIFS
OPOIFSFileSystem ofs = new OPOIFSFileSystem(SAMPLES.openResourceAsStream("SampleDoc.doc"));
HWPFDocument doc = new HWPFDocument(ofs.getRoot());
try {
doc.write();
} finally {
doc.close();
}
}
@Test(expected=IllegalStateException.class)
public void testInvalidInPlaceWriteNPOIFS() throws Exception {
// Can't work for Read-Only files
NPOIFSFileSystem fs = new NPOIFSFileSystem(SAMPLES.getFile("SampleDoc.doc"), true);
HWPFDocument doc = new HWPFDocument(fs.getRoot());
try {
doc.write();
} finally {
doc.close();
fs.close();
}
}
} }

View File

@ -17,7 +17,10 @@
package org.apache.poi.hwpf.usermodel; package org.apache.poi.hwpf.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException; import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFDocument;
@ -25,394 +28,407 @@ import org.apache.poi.hwpf.HWPFTestCase;
import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.hwpf.HWPFTestDataSamples;
import org.apache.poi.hwpf.extractor.WordExtractor; import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.model.StyleSheet; import org.apache.poi.hwpf.model.StyleSheet;
import org.junit.Test;
/** /**
* Test various problem documents * Test various problem documents
*
* @author Nick Burch (nick at torchbox dot com)
*/ */
public final class TestProblems extends HWPFTestCase { public final class TestProblems extends HWPFTestCase {
/**
/** * ListEntry passed no ListTable
* ListEntry passed no ListTable */
*/ @Test
public void testListEntryNoListTable() { public void testListEntryNoListTable() throws IOException {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("ListEntryNoListTable.doc"); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("ListEntryNoListTable.doc");
Range r = doc.getRange(); Range r = doc.getRange();
StyleSheet styleSheet = doc.getStyleSheet(); for (int x = 0; x < r.numSections(); x++) {
for (int x = 0; x < r.numSections(); x++) { Section s = r.getSection(x);
Section s = r.getSection(x); for (int y = 0; y < s.numParagraphs(); y++) {
for (int y = 0; y < s.numParagraphs(); y++) { s.getParagraph(y);
Paragraph paragraph = s.getParagraph(y); }
// System.out.println(paragraph.getCharacterRun(0).text()); }
}
} doc.close();
} }
/** /**
* AIOOB for TableSprmUncompressor.unCompressTAPOperation * AIOOB for TableSprmUncompressor.unCompressTAPOperation
*/ */
public void testSprmAIOOB() { @Test
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("AIOOB-Tap.doc"); public void testSprmAIOOB() throws IOException {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("AIOOB-Tap.doc");
Range r = doc.getRange(); StyleSheet styleSheet = doc.getStyleSheet();
StyleSheet styleSheet = doc.getStyleSheet(); assertNotNull(styleSheet);
for (int x = 0; x < r.numSections(); x++) {
Section s = r.getSection(x); Range r = doc.getRange();
for (int y = 0; y < s.numParagraphs(); y++) { for (int x = 0; x < r.numSections(); x++) {
Paragraph paragraph = s.getParagraph(y); Section s = r.getSection(x);
// System.out.println(paragraph.getCharacterRun(0).text()); for (int y = 0; y < s.numParagraphs(); y++) {
} Paragraph paragraph = s.getParagraph(y);
} assertNotNull(paragraph);
} }
}
doc.close();
}
/** /**
* Test for TableCell not skipping the last paragraph. Bugs #45062 and * Test for TableCell not skipping the last paragraph. Bugs #45062 and
* #44292 * #44292
*/ */
public void testTableCellLastParagraph() { @Test
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug44292.doc"); public void testTableCellLastParagraph() throws IOException {
Range r = doc.getRange(); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug44292.doc");
assertEquals(6, r.numParagraphs()); Range r = doc.getRange();
assertEquals(0, r.getStartOffset()); assertEquals(6, r.numParagraphs());
assertEquals(87, r.getEndOffset()); assertEquals(0, r.getStartOffset());
assertEquals(87, r.getEndOffset());
// Paragraph with table // Paragraph with table
Paragraph p = r.getParagraph(0); Paragraph p = r.getParagraph(0);
assertEquals(0, p.getStartOffset()); assertEquals(0, p.getStartOffset());
assertEquals(20, p.getEndOffset()); assertEquals(20, p.getEndOffset());
// Check a few bits of the table directly // Check a few bits of the table directly
assertEquals("One paragraph is ok\7", r.getParagraph(0).text()); assertEquals("One paragraph is ok\7", r.getParagraph(0).text());
assertEquals("First para is ok\r", r.getParagraph(1).text()); assertEquals("First para is ok\r", r.getParagraph(1).text());
assertEquals("Second paragraph is skipped\7", r.getParagraph(2).text()); assertEquals("Second paragraph is skipped\7", r.getParagraph(2).text());
assertEquals("One paragraph is ok\7", r.getParagraph(3).text()); assertEquals("One paragraph is ok\7", r.getParagraph(3).text());
assertEquals("\7", r.getParagraph(4).text()); assertEquals("\7", r.getParagraph(4).text());
assertEquals("\r", r.getParagraph(5).text()); assertEquals("\r", r.getParagraph(5).text());
// Get the table // Get the table
Table t = r.getTable(p); Table t = r.getTable(p);
// get the only row // get the only row
assertEquals(1, t.numRows()); assertEquals(1, t.numRows());
TableRow row = t.getRow(0); TableRow row = t.getRow(0);
// sanity check our row // sanity check our row
assertEquals(5, row.numParagraphs()); assertEquals(5, row.numParagraphs());
assertEquals(0, row._parStart); assertEquals(0, row._parStart);
assertEquals(5, row._parEnd); assertEquals(5, row._parEnd);
assertEquals(0, row.getStartOffset()); assertEquals(0, row.getStartOffset());
assertEquals(86, row.getEndOffset()); assertEquals(86, row.getEndOffset());
// get the first cell
TableCell cell = row.getCell(0);
// First cell should have one paragraph
assertEquals(1, cell.numParagraphs());
assertEquals("One paragraph is ok\7", cell.getParagraph(0).text());
assertEquals(0, cell._parStart);
assertEquals(1, cell._parEnd);
assertEquals(0, cell.getStartOffset());
assertEquals(20, cell.getEndOffset());
// get the first cell // get the second
TableCell cell = row.getCell(0); cell = row.getCell(1);
// First cell should have one paragraph // Second cell should be detected as having two paragraphs
assertEquals(1, cell.numParagraphs()); assertEquals(2, cell.numParagraphs());
assertEquals("One paragraph is ok\7", cell.getParagraph(0).text()); assertEquals("First para is ok\r", cell.getParagraph(0).text());
assertEquals(0, cell._parStart); assertEquals("Second paragraph is skipped\7",
assertEquals(1, cell._parEnd); cell.getParagraph(1).text());
assertEquals(0, cell.getStartOffset()); assertEquals(1, cell._parStart);
assertEquals(20, cell.getEndOffset()); assertEquals(3, cell._parEnd);
assertEquals(20, cell.getStartOffset());
assertEquals(65, cell.getEndOffset());
// get the last cell
cell = row.getCell(2);
// Last cell should have one paragraph
assertEquals(1, cell.numParagraphs());
assertEquals("One paragraph is ok\7", cell.getParagraph(0).text());
assertEquals(3, cell._parStart);
assertEquals(4, cell._parEnd);
assertEquals(65, cell.getStartOffset());
assertEquals(85, cell.getEndOffset());
doc.close();
}
// get the second @Test
cell = row.getCell(1); public void testRangeDelete() throws IOException {
// Second cell should be detected as having two paragraphs HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug28627.doc");
assertEquals(2, cell.numParagraphs());
assertEquals("First para is ok\r", cell.getParagraph(0).text());
assertEquals("Second paragraph is skipped\7", cell.getParagraph(1).text());
assertEquals(1, cell._parStart);
assertEquals(3, cell._parEnd);
assertEquals(20, cell.getStartOffset());
assertEquals(65, cell.getEndOffset());
Range range = doc.getRange();
int numParagraphs = range.numParagraphs();
// get the last cell int totalLength = 0, deletedLength = 0;
cell = row.getCell(2);
// Last cell should have one paragraph
assertEquals(1, cell.numParagraphs());
assertEquals("One paragraph is ok\7", cell.getParagraph(0).text());
assertEquals(3, cell._parStart);
assertEquals(4, cell._parEnd);
assertEquals(65, cell.getStartOffset());
assertEquals(85, cell.getEndOffset());
}
public void testRangeDelete() { for (int i = 0; i < numParagraphs; i++) {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug28627.doc"); Paragraph para = range.getParagraph(i);
String text = para.text();
Range range = doc.getRange(); totalLength += text.length();
int numParagraphs = range.numParagraphs(); if (text.indexOf("{delete me}") > -1) {
para.delete();
deletedLength = text.length();
}
}
int totalLength = 0, deletedLength = 0; // check the text length after deletion
int newLength = 0;
range = doc.getRange();
numParagraphs = range.numParagraphs();
for (int i = 0; i < numParagraphs; i++) { for (int i = 0; i < numParagraphs; i++) {
Paragraph para = range.getParagraph(i); Paragraph para = range.getParagraph(i);
String text = para.text(); String text = para.text();
totalLength += text.length(); newLength += text.length();
if (text.indexOf("{delete me}") > -1) { }
para.delete();
deletedLength = text.length();
}
}
// check the text length after deletion assertEquals(newLength, totalLength - deletedLength);
int newLength = 0;
range = doc.getRange(); doc.close();
numParagraphs = range.numParagraphs(); }
for (int i = 0; i < numParagraphs; i++) { /**
Paragraph para = range.getParagraph(i); * With an encrypted file, we should give a suitable exception, and not OOM
String text = para.text(); */
@Test(expected=EncryptedDocumentException.class)
public void testEncryptedFile() throws IOException {
HWPFTestDataSamples.openSampleFile("PasswordProtected.doc");
}
newLength += text.length(); @Test
} public void testWriteProperties() throws IOException {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc");
assertEquals("Nick Burch", doc.getSummaryInformation().getAuthor());
assertEquals(newLength, totalLength - deletedLength); // Write and read
} HWPFDocument doc2 = writeOutAndRead(doc);
assertEquals("Nick Burch", doc2.getSummaryInformation().getAuthor());
doc2.close();
doc.close();
}
/** /**
* With an encrypted file, we should give a suitable exception, and not OOM * Test for reading paragraphs from Range after replacing some text in this
*/ * Range. Bug #45269
public void testEncryptedFile() { */
try { @Test
HWPFTestDataSamples.openSampleFile("PasswordProtected.doc"); public void testReadParagraphsAfterReplaceText() throws IOException {
fail(); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug45269.doc");
} catch (EncryptedDocumentException e) { Range range = doc.getRange();
// Good
}
}
public void testWriteProperties() { String toFind = "campo1";
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc"); String longer = " foi porraaaaa ";
assertEquals("Nick Burch", doc.getSummaryInformation().getAuthor()); String shorter = " foi ";
// Write and read // check replace with longer text
HWPFDocument doc2 = writeOutAndRead(doc); for (int x = 0; x < range.numParagraphs(); x++) {
assertEquals("Nick Burch", doc2.getSummaryInformation().getAuthor()); Paragraph para = range.getParagraph(x);
} int offset = para.text().indexOf(toFind);
if (offset >= 0) {
para.replaceText(toFind, longer, offset);
assertEquals(offset, para.text().indexOf(longer));
}
}
/** doc = HWPFTestDataSamples.openSampleFile("Bug45269.doc");
* Test for reading paragraphs from Range after replacing some range = doc.getRange();
* text in this Range.
* Bug #45269
*/
public void testReadParagraphsAfterReplaceText()throws Exception{
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug45269.doc");
Range range = doc.getRange();
String toFind = "campo1"; // check replace with shorter text
String longer = " foi porraaaaa "; for (int x = 0; x < range.numParagraphs(); x++) {
String shorter = " foi "; Paragraph para = range.getParagraph(x);
int offset = para.text().indexOf(toFind);
if (offset >= 0) {
para.replaceText(toFind, shorter, offset);
assertEquals(offset, para.text().indexOf(shorter));
}
}
doc.close();
}
//check replace with longer text /**
for (int x = 0; x < range.numParagraphs(); x++) { * Bug #49936 - Problems with reading the header out of the Header Stories
Paragraph para = range.getParagraph(x); */
int offset = para.text().indexOf(toFind); @SuppressWarnings("deprecation")
if (offset >= 0) { @Test
para.replaceText(toFind, longer, offset); public void testProblemHeaderStories49936() throws IOException {
assertEquals(offset, para.text().indexOf(longer)); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("HeaderFooterProblematic.doc");
} HeaderStories hs = new HeaderStories(doc);
}
doc = HWPFTestDataSamples.openSampleFile("Bug45269.doc"); assertEquals("", hs.getFirstHeader());
range = doc.getRange(); assertEquals("\r", hs.getEvenHeader());
assertEquals("", hs.getOddHeader());
//check replace with shorter text assertEquals("", hs.getFirstFooter());
for (int x = 0; x < range.numParagraphs(); x++) { assertEquals("", hs.getEvenFooter());
Paragraph para = range.getParagraph(x); assertEquals("", hs.getOddFooter());
int offset = para.text().indexOf(toFind);
if (offset >= 0) {
para.replaceText(toFind, shorter, offset);
assertEquals(offset, para.text().indexOf(shorter));
}
}
}
/**
* Bug #49936 - Problems with reading the header out of
* the Header Stories
*/
public void testProblemHeaderStories49936() throws Exception {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("HeaderFooterProblematic.doc");
HeaderStories hs = new HeaderStories(doc);
assertEquals("", hs.getFirstHeader());
assertEquals("\r", hs.getEvenHeader());
assertEquals("", hs.getOddHeader());
assertEquals("", hs.getFirstFooter());
assertEquals("", hs.getEvenFooter());
assertEquals("", hs.getOddFooter());
WordExtractor ext = new WordExtractor(doc);
assertEquals("\n", ext.getHeaderText());
assertEquals("", ext.getFooterText());
}
/**
* Bug #45877 - problematic PAPX with no parent set
*/
public void testParagraphPAPXNoParent45877() throws Exception {
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug45877.doc");
assertEquals(17, doc.getRange().numParagraphs());
assertEquals("First paragraph\r", doc.getRange().getParagraph(0).text());
assertEquals("After Crashing Part\r", doc.getRange().getParagraph(13).text());
}
/** WordExtractor ext = new WordExtractor(doc);
* Bug #48245 - don't include the text from the assertEquals("\n", ext.getHeaderText());
* next cell in the current one assertEquals("", ext.getFooterText());
*/ ext.close();
public void testTableIterator() throws Exception { doc.close();
HWPFDocument doc = HWPFTestDataSamples.openSampleFile("simple-table2.doc"); }
Range r = doc.getRange();
// Check the text is as we'd expect /**
assertEquals(13, r.numParagraphs()); * Bug #45877 - problematic PAPX with no parent set
assertEquals("Row 1/Cell 1\u0007", r.getParagraph(0).text()); */
assertEquals("Row 1/Cell 2\u0007", r.getParagraph(1).text()); @Test
assertEquals("Row 1/Cell 3\u0007", r.getParagraph(2).text()); public void testParagraphPAPXNoParent45877() throws IOException {
assertEquals("\u0007", r.getParagraph(3).text()); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug45877.doc");
assertEquals("Row 2/Cell 1\u0007", r.getParagraph(4).text()); assertEquals(17, doc.getRange().numParagraphs());
assertEquals("Row 2/Cell 2\u0007", r.getParagraph(5).text());
assertEquals("Row 2/Cell 3\u0007", r.getParagraph(6).text());
assertEquals("\u0007", r.getParagraph(7).text());
assertEquals("Row 3/Cell 1\u0007", r.getParagraph(8).text());
assertEquals("Row 3/Cell 2\u0007", r.getParagraph(9).text());
assertEquals("Row 3/Cell 3\u0007", r.getParagraph(10).text());
assertEquals("\u0007", r.getParagraph(11).text());
assertEquals("\r", r.getParagraph(12).text());
Paragraph p; assertEquals("First paragraph\r",
doc.getRange().getParagraph(0).text());
assertEquals("After Crashing Part\r",
doc.getRange().getParagraph(13).text());
doc.close();
}
// Take a look in detail at the first couple of /**
// paragraphs * Bug #48245 - don't include the text from the next cell in the current one
p = r.getParagraph(0); */
assertEquals(1, p.numParagraphs()); @Test
assertEquals(0, p.getStartOffset()); public void testTableIterator() throws IOException {
assertEquals(13, p.getEndOffset()); HWPFDocument doc = HWPFTestDataSamples.openSampleFile("simple-table2.doc");
assertEquals(0, p._parStart); Range r = doc.getRange();
assertEquals(1, p._parEnd);
p = r.getParagraph(1); // Check the text is as we'd expect
assertEquals(1, p.numParagraphs()); assertEquals(13, r.numParagraphs());
assertEquals(13, p.getStartOffset()); assertEquals("Row 1/Cell 1\u0007", r.getParagraph(0).text());
assertEquals(26, p.getEndOffset()); assertEquals("Row 1/Cell 2\u0007", r.getParagraph(1).text());
assertEquals(1, p._parStart); assertEquals("Row 1/Cell 3\u0007", r.getParagraph(2).text());
assertEquals(2, p._parEnd); assertEquals("\u0007", r.getParagraph(3).text());
assertEquals("Row 2/Cell 1\u0007", r.getParagraph(4).text());
assertEquals("Row 2/Cell 2\u0007", r.getParagraph(5).text());
assertEquals("Row 2/Cell 3\u0007", r.getParagraph(6).text());
assertEquals("\u0007", r.getParagraph(7).text());
assertEquals("Row 3/Cell 1\u0007", r.getParagraph(8).text());
assertEquals("Row 3/Cell 2\u0007", r.getParagraph(9).text());
assertEquals("Row 3/Cell 3\u0007", r.getParagraph(10).text());
assertEquals("\u0007", r.getParagraph(11).text());
assertEquals("\r", r.getParagraph(12).text());
p = r.getParagraph(2); Paragraph p;
assertEquals(1, p.numParagraphs());
assertEquals(26, p.getStartOffset());
assertEquals(39, p.getEndOffset());
assertEquals(2, p._parStart);
assertEquals(3, p._parEnd);
// Take a look in detail at the first couple of
// paragraphs
p = r.getParagraph(0);
assertEquals(1, p.numParagraphs());
assertEquals(0, p.getStartOffset());
assertEquals(13, p.getEndOffset());
assertEquals(0, p._parStart);
assertEquals(1, p._parEnd);
// Now look at the table p = r.getParagraph(1);
Table table = r.getTable(r.getParagraph(0)); assertEquals(1, p.numParagraphs());
assertEquals(3, table.numRows()); assertEquals(13, p.getStartOffset());
assertEquals(26, p.getEndOffset());
assertEquals(1, p._parStart);
assertEquals(2, p._parEnd);
TableRow row; p = r.getParagraph(2);
TableCell cell; assertEquals(1, p.numParagraphs());
assertEquals(26, p.getStartOffset());
assertEquals(39, p.getEndOffset());
assertEquals(2, p._parStart);
assertEquals(3, p._parEnd);
// Now look at the table
Table table = r.getTable(r.getParagraph(0));
assertEquals(3, table.numRows());
row = table.getRow(0); TableRow row;
assertEquals(0, row._parStart); TableCell cell;
assertEquals(4, row._parEnd);
cell = row.getCell(0); row = table.getRow(0);
assertEquals(1, cell.numParagraphs()); assertEquals(0, row._parStart);
assertEquals(0, cell._parStart); assertEquals(4, row._parEnd);
assertEquals(1, cell._parEnd);
assertEquals(0, cell.getStartOffset());
assertEquals(13, cell.getEndOffset());
assertEquals("Row 1/Cell 1\u0007", cell.text());
assertEquals("Row 1/Cell 1\u0007", cell.getParagraph(0).text());
cell = row.getCell(1); cell = row.getCell(0);
assertEquals(1, cell.numParagraphs()); assertEquals(1, cell.numParagraphs());
assertEquals(1, cell._parStart); assertEquals(0, cell._parStart);
assertEquals(2, cell._parEnd); assertEquals(1, cell._parEnd);
assertEquals(13, cell.getStartOffset()); assertEquals(0, cell.getStartOffset());
assertEquals(26, cell.getEndOffset()); assertEquals(13, cell.getEndOffset());
assertEquals("Row 1/Cell 2\u0007", cell.text()); assertEquals("Row 1/Cell 1\u0007", cell.text());
assertEquals("Row 1/Cell 2\u0007", cell.getParagraph(0).text()); assertEquals("Row 1/Cell 1\u0007", cell.getParagraph(0).text());
cell = row.getCell(2); cell = row.getCell(1);
assertEquals(1, cell.numParagraphs()); assertEquals(1, cell.numParagraphs());
assertEquals(2, cell._parStart); assertEquals(1, cell._parStart);
assertEquals(3, cell._parEnd); assertEquals(2, cell._parEnd);
assertEquals(26, cell.getStartOffset()); assertEquals(13, cell.getStartOffset());
assertEquals(39, cell.getEndOffset()); assertEquals(26, cell.getEndOffset());
assertEquals("Row 1/Cell 3\u0007", cell.text()); assertEquals("Row 1/Cell 2\u0007", cell.text());
assertEquals("Row 1/Cell 3\u0007", cell.getParagraph(0).text()); assertEquals("Row 1/Cell 2\u0007", cell.getParagraph(0).text());
cell = row.getCell(2);
assertEquals(1, cell.numParagraphs());
assertEquals(2, cell._parStart);
assertEquals(3, cell._parEnd);
assertEquals(26, cell.getStartOffset());
assertEquals(39, cell.getEndOffset());
assertEquals("Row 1/Cell 3\u0007", cell.text());
assertEquals("Row 1/Cell 3\u0007", cell.getParagraph(0).text());
// Onto row #2 // Onto row #2
row = table.getRow(1); row = table.getRow(1);
assertEquals(4, row._parStart); assertEquals(4, row._parStart);
assertEquals(8, row._parEnd); assertEquals(8, row._parEnd);
cell = row.getCell(0); cell = row.getCell(0);
assertEquals(1, cell.numParagraphs()); assertEquals(1, cell.numParagraphs());
assertEquals(4, cell._parStart); assertEquals(4, cell._parStart);
assertEquals(5, cell._parEnd); assertEquals(5, cell._parEnd);
assertEquals(40, cell.getStartOffset()); assertEquals(40, cell.getStartOffset());
assertEquals(53, cell.getEndOffset()); assertEquals(53, cell.getEndOffset());
assertEquals("Row 2/Cell 1\u0007", cell.text()); assertEquals("Row 2/Cell 1\u0007", cell.text());
cell = row.getCell(1); cell = row.getCell(1);
assertEquals(1, cell.numParagraphs()); assertEquals(1, cell.numParagraphs());
assertEquals(5, cell._parStart); assertEquals(5, cell._parStart);
assertEquals(6, cell._parEnd); assertEquals(6, cell._parEnd);
assertEquals(53, cell.getStartOffset()); assertEquals(53, cell.getStartOffset());
assertEquals(66, cell.getEndOffset()); assertEquals(66, cell.getEndOffset());
assertEquals("Row 2/Cell 2\u0007", cell.text()); assertEquals("Row 2/Cell 2\u0007", cell.text());
cell = row.getCell(2); cell = row.getCell(2);
assertEquals(1, cell.numParagraphs()); assertEquals(1, cell.numParagraphs());
assertEquals(6, cell._parStart); assertEquals(6, cell._parStart);
assertEquals(7, cell._parEnd); assertEquals(7, cell._parEnd);
assertEquals(66, cell.getStartOffset()); assertEquals(66, cell.getStartOffset());
assertEquals(79, cell.getEndOffset()); assertEquals(79, cell.getEndOffset());
assertEquals("Row 2/Cell 3\u0007", cell.text()); assertEquals("Row 2/Cell 3\u0007", cell.text());
// Finally row 3
row = table.getRow(2);
assertEquals(8, row._parStart);
assertEquals(12, row._parEnd);
// Finally row 3 cell = row.getCell(0);
row = table.getRow(2); assertEquals(1, cell.numParagraphs());
assertEquals(8, row._parStart); assertEquals(8, cell._parStart);
assertEquals(12, row._parEnd); assertEquals(9, cell._parEnd);
assertEquals(80, cell.getStartOffset());
assertEquals(93, cell.getEndOffset());
assertEquals("Row 3/Cell 1\u0007", cell.text());
cell = row.getCell(0); cell = row.getCell(1);
assertEquals(1, cell.numParagraphs()); assertEquals(1, cell.numParagraphs());
assertEquals(8, cell._parStart); assertEquals(9, cell._parStart);
assertEquals(9, cell._parEnd); assertEquals(10, cell._parEnd);
assertEquals(80, cell.getStartOffset()); assertEquals(93, cell.getStartOffset());
assertEquals(93, cell.getEndOffset()); assertEquals(106, cell.getEndOffset());
assertEquals("Row 3/Cell 1\u0007", cell.text()); assertEquals("Row 3/Cell 2\u0007", cell.text());
cell = row.getCell(1);
assertEquals(1, cell.numParagraphs());
assertEquals(9, cell._parStart);
assertEquals(10, cell._parEnd);
assertEquals(93, cell.getStartOffset());
assertEquals(106, cell.getEndOffset());
assertEquals("Row 3/Cell 2\u0007", cell.text());
cell = row.getCell(2);
assertEquals(1, cell.numParagraphs());
assertEquals(10, cell._parStart);
assertEquals(11, cell._parEnd);
assertEquals(106, cell.getStartOffset());
assertEquals(119, cell.getEndOffset());
assertEquals("Row 3/Cell 3\u0007", cell.text());
}
cell = row.getCell(2);
assertEquals(1, cell.numParagraphs());
assertEquals(10, cell._parStart);
assertEquals(11, cell._parEnd);
assertEquals(106, cell.getStartOffset());
assertEquals(119, cell.getEndOffset());
assertEquals("Row 3/Cell 3\u0007", cell.text());
doc.close();
}
} }