* attachment.
*/
public class AttachmentChunks implements ChunkGroup {
- private static POILogger logger = POILogFactory.getLogger(AttachmentChunks.class);
+ private static final POILogger LOG = POILogFactory.getLogger(AttachmentChunks.class);
public static final String PREFIX = "__attach_version1.0_#";
- public ByteChunk attachData;
- public StringChunk attachExtension;
- public StringChunk attachFileName;
- public StringChunk attachLongFileName;
- public StringChunk attachMimeTag;
- public DirectoryChunk attachmentDirectory;
+ private ByteChunk attachData;
+ private StringChunk attachExtension;
+ private StringChunk attachFileName;
+ private StringChunk attachLongFileName;
+ private StringChunk attachMimeTag;
+ private DirectoryChunk attachmentDirectory;
/**
* This is in WMF Format. You'll probably want to pass it to Apache Batik to
return allChunks.toArray(new Chunk[allChunks.size()]);
}
+ @Override
public Chunk[] getChunks() {
return getAll();
}
return poifsName;
}
+ /**
+ * @return the ATTACH_DATA chunk
+ */
+ public ByteChunk getAttachData() {
+ return attachData;
+ }
+
+ /**
+ * @return the attachment extension
+ */
+ public StringChunk getAttachExtension() {
+ return attachExtension;
+ }
+
+ /**
+ * @return the attachment (short) filename
+ */
+ public StringChunk getAttachFileName() {
+ return attachFileName;
+ }
+
+ /**
+ * @return the attachment (long) filename
+ */
+ public StringChunk getAttachLongFileName() {
+ return attachLongFileName;
+ }
+
+ /**
+ * @return the attachment mimetag
+ */
+ public StringChunk getAttachMimeTag() {
+ return attachMimeTag;
+ }
+
+ /**
+ * @return the attachment directory
+ */
+ public DirectoryChunk getAttachmentDirectory() {
+ return attachmentDirectory;
+ }
+
+ /**
+ * @return the attachment preview bytes
+ */
+ public ByteChunk getAttachRenderingWMF() {
+ return attachRenderingWMF;
+ }
+
/**
* Called by the parser whenever a chunk is found.
*/
+ @Override
public void record(Chunk chunk) {
// TODO: add further members for other properties like:
// - ATTACH_ADDITIONAL_INFO
} else if (chunk instanceof DirectoryChunk) {
attachmentDirectory = (DirectoryChunk) chunk;
} else {
- logger.log(POILogger.ERROR, "Unexpected data chunk of type " + chunk);
+ LOG.log(POILogger.ERROR, "Unexpected data chunk of type " + chunk);
}
} else if (chunkId == ATTACH_EXTENSION.id) {
attachExtension = (StringChunk) chunk;
/**
* Used to flag that all the chunks of the attachment have now been located.
*/
+ @Override
public void chunksComplete() {
// Currently, we don't need to do anything special once
// all the chunks have been located
* Orders by the attachment number.
*/
public static class AttachmentChunksSorter
- implements Comparator<AttachmentChunks>, Serializable {
+ implements Comparator<AttachmentChunks>, Serializable {
+ @Override
public int compare(AttachmentChunks a, AttachmentChunks b) {
return a.poifsName.compareTo(b.poifsName);
}
super(chunkId, type);
}
+ @Override
public void readValue(InputStream value) throws IOException {
this.value = IOUtils.toByteArray(value);
}
+ @Override
public void writeValue(OutputStream out) throws IOException {
out.write(value);
}
/**
* Returns the data in a debug-friendly string format
*/
+ @Override
public String toString() {
return toDebugFriendlyString(value);
}
* array, and the start of a longer one.
*/
protected static String toDebugFriendlyString(byte[] value) {
- if (value == null)
+ if (value == null) {
return "(Null Byte Array)";
+ }
StringBuffer text = new StringBuffer();
text.append("Bytes len=").append(value.length);
limit = 12;
}
for (int i = 0; i < limit; i++) {
- if (i > 0)
+ if (i > 0) {
text.append(',');
+ }
text.append(value[i]);
}
if (value.length > 16) {
public abstract class Chunk {
public static final String DEFAULT_NAME_PREFIX = "__substg1.0_";
- protected int chunkId;
- protected MAPIType type;
- protected String namePrefix;
+ private int chunkId;
+ private MAPIType type;
+ private String namePrefix;
protected Chunk(String namePrefix, int chunkId, MAPIType type) {
this.namePrefix = namePrefix;
String type = this.type.asFileEnding();
String chunkId = Integer.toHexString(this.chunkId);
- while (chunkId.length() < 4)
+ while (chunkId.length() < 4) {
chunkId = "0" + chunkId;
+ }
return this.namePrefix
+ chunkId.toUpperCase(Locale.ROOT)
* TODO Deprecate the public Chunks in favour of Property Lookups
*/
public final class Chunks implements ChunkGroupWithProperties {
- private static POILogger logger = POILogFactory.getLogger(Chunks.class);
+ private static final POILogger LOG = POILogFactory.getLogger(Chunks.class);
/**
* Holds all the chunks that were found, indexed by their MAPIProperty.
private Map<MAPIProperty, List<Chunk>> allChunks = new HashMap<MAPIProperty, List<Chunk>>();
/** Type of message that the MSG represents (ie. IPM.Note) */
- public StringChunk messageClass;
+ private StringChunk messageClass;
/** BODY Chunk, for plain/text messages */
- public StringChunk textBodyChunk;
+ private StringChunk textBodyChunk;
/** BODY Html Chunk, for html messages */
- public StringChunk htmlBodyChunkString;
- public ByteChunk htmlBodyChunkBinary;
+ private StringChunk htmlBodyChunkString;
+ private ByteChunk htmlBodyChunkBinary;
/** BODY Rtf Chunk, for Rtf (Rich) messages */
- public ByteChunk rtfBodyChunk;
+ private ByteChunk rtfBodyChunk;
/** Subject link chunk, in plain/text */
- public StringChunk subjectChunk;
+ private StringChunk subjectChunk;
/**
* Value that is in the TO field (not actually the addresses as they are
* stored in recip directory nodes
*/
- public StringChunk displayToChunk;
+ private StringChunk displayToChunk;
/** Value that is in the FROM field */
- public StringChunk displayFromChunk;
+ private StringChunk displayFromChunk;
/** value that shows in the CC field */
- public StringChunk displayCCChunk;
+ private StringChunk displayCCChunk;
/** Value that shows in the BCC field */
- public StringChunk displayBCCChunk;
+ private StringChunk displayBCCChunk;
/** Sort of like the subject line, but without the RE: and FWD: parts. */
- public StringChunk conversationTopic;
+ private StringChunk conversationTopic;
/** Type of server that the message originated from (SMTP, etc). */
- public StringChunk sentByServerType;
+ private StringChunk sentByServerType;
/** The email headers */
- public StringChunk messageHeaders;
+ private StringChunk messageHeaders;
/** TODO */
- public MessageSubmissionChunk submissionChunk;
+ private MessageSubmissionChunk submissionChunk;
/** TODO */
- public StringChunk emailFromChunk;
+ private StringChunk emailFromChunk;
/** The message ID */
- public StringChunk messageId;
+ private StringChunk messageId;
/** The message properties */
private MessagePropertiesChunk messageProperties;
+ @Override
public Map<MAPIProperty, List<PropertyValue>> getProperties() {
if (messageProperties != null) {
return messageProperties.getProperties();
- } else
+ } else {
return Collections.emptyMap();
+ }
}
public Map<MAPIProperty, PropertyValue> getRawProperties() {
if (messageProperties != null) {
return messageProperties.getRawProperties();
- } else
+ } else {
return Collections.emptyMap();
+ }
}
public Map<MAPIProperty, List<Chunk>> getAll() {
return allChunks;
}
+ @Override
public Chunk[] getChunks() {
ArrayList<Chunk> chunks = new ArrayList<Chunk>(allChunks.size());
for (List<Chunk> c : allChunks.values()) {
return chunks.toArray(new Chunk[chunks.size()]);
}
+ public StringChunk getMessageClass() {
+ return messageClass;
+ }
+
+ public StringChunk getTextBodyChunk() {
+ return textBodyChunk;
+ }
+
+ public StringChunk getHtmlBodyChunkString() {
+ return htmlBodyChunkString;
+ }
+
+ public ByteChunk getHtmlBodyChunkBinary() {
+ return htmlBodyChunkBinary;
+ }
+
+ public ByteChunk getRtfBodyChunk() {
+ return rtfBodyChunk;
+ }
+
+ public StringChunk getSubjectChunk() {
+ return subjectChunk;
+ }
+
+ public StringChunk getDisplayToChunk() {
+ return displayToChunk;
+ }
+
+ public StringChunk getDisplayFromChunk() {
+ return displayFromChunk;
+ }
+
+ public StringChunk getDisplayCCChunk() {
+ return displayCCChunk;
+ }
+
+ public StringChunk getDisplayBCCChunk() {
+ return displayBCCChunk;
+ }
+
+ public StringChunk getConversationTopic() {
+ return conversationTopic;
+ }
+
+ public StringChunk getSentByServerType() {
+ return sentByServerType;
+ }
+
+ public StringChunk getMessageHeaders() {
+ return messageHeaders;
+ }
+
+ public MessageSubmissionChunk getSubmissionChunk() {
+ return submissionChunk;
+ }
+
+ public StringChunk getEmailFromChunk() {
+ return emailFromChunk;
+ }
+
+ public StringChunk getMessageId() {
+ return messageId;
+ }
+
+ public MessagePropertiesChunk getMessageProperties() {
+ return messageProperties;
+ }
+
/**
* Called by the parser whenever a chunk is found.
*/
+ @Override
public void record(Chunk chunk) {
// Work out what MAPIProperty this corresponds to
MAPIProperty prop = MAPIProperty.get(chunk.getChunkId());
allChunks.get(prop).add(chunk);
}
+ @Override
public void chunksComplete() {
if (messageProperties != null) {
messageProperties.matchVariableSizedPropertiesToChunks();
} else {
- logger.log(POILogger.WARN,
+ LOG.log(POILogger.WARN,
"Message didn't contain a root list of properties!");
}
}
return str + usualType.asFileEnding();
}
+ @Override
public String toString() {
StringBuffer str = new StringBuffer();
str.append(name);
* used if you want to cancel a message or similar
*/
public class MessageSubmissionChunk extends Chunk {
- private static POILogger logger = POILogFactory
- .getLogger(MessageSubmissionChunk.class);
+ private static final POILogger LOG = POILogFactory.getLogger(MessageSubmissionChunk.class);
private String rawId;
private Calendar date;
super(chunkId, type);
}
+ @Override
public void readValue(InputStream value) throws IOException {
// Stored in the file as us-ascii
byte[] data = IOUtils.toByteArray(value);
date.set(Calendar.SECOND, Integer.parseInt(m.group(6)));
date.clear(Calendar.MILLISECOND);
} else {
- logger.log(POILogger.WARN,
+ LOG.log(POILogger.WARN,
"Warning - unable to make sense of date "
+ dateS);
}
}
}
+ @Override
public void writeValue(OutputStream out) throws IOException {
byte[] data = rawId.getBytes(Charset.forName("ASCII"));
out.write(data);
return allChunks.toArray(new Chunk[allChunks.size()]);
}
+ @Override
public Chunk[] getChunks() {
return getAll();
}
/**
* Called by the parser whenever a chunk is found.
*/
+ @Override
public void record(Chunk chunk) {
allChunks.add(chunk);
}
/**
* Used to flag that all the chunks of the NameID have now been located.
*/
+ @Override
public void chunksComplete() {
// Currently, we don't need to do anything special once
// all the chunks have been located
// TODO Is this the right way?
Map<Integer, Chunk> chunks = new HashMap<Integer, Chunk>();
for (Chunk chunk : parentGroup.getChunks()) {
- chunks.put(chunk.chunkId, chunk);
+ chunks.put(chunk.getChunkId(), chunk);
}
// Loop over our values, looking for chunk based ones
this.data = value;
}
+ @Override
public String toString() {
Object v = getValue();
- if (v == null)
+ if (v == null) {
return "(No value available)";
+ }
if (v instanceof byte[]) {
return ByteChunk.toDebugFriendlyString((byte[]) v);
super(property, flags, data);
}
+ @Override
public Void getValue() {
return null;
}
super(property, flags, data);
}
+ @Override
public Boolean getValue() {
short val = LittleEndian.getShort(data);
return val > 0;
super(property, flags, data);
}
+ @Override
public Short getValue() {
return LittleEndian.getShort(data);
}
super(property, flags, data);
}
+ @Override
public Integer getValue() {
return LittleEndian.getInt(data);
}
super(property, flags, data);
}
+ @Override
public Long getValue() {
return LittleEndian.getLong(data);
}
super(property, flags, data);
}
+ @Override
public Float getValue() {
return LittleEndian.getFloat(data);
}
super(property, flags, data);
}
+ @Override
public Double getValue() {
return LittleEndian.getDouble(data);
}
super(property, flags, data);
}
+ @Override
public BigInteger getValue() {
long unshifted = LittleEndian.getLong(data);
return BigInteger.valueOf(unshifted).divide(SHIFT);
super(property, flags, data);
}
+ @Override
public Calendar getValue() {
long time = LittleEndian.getLong(data);
time = (time / 10 / 1000) - OFFSET;
* If a message has multiple recipients, there will be several of these.
*/
public final class RecipientChunks implements ChunkGroupWithProperties {
- private static POILogger logger = POILogFactory.getLogger(RecipientChunks.class);
+ private static final POILogger LOG = POILogFactory.getLogger(RecipientChunks.class);
public static final String PREFIX = "__recip_version1.0_#";
try {
recipientNumber = Integer.parseInt(number, 16);
} catch (NumberFormatException e) {
- logger.log(POILogger.ERROR,
+ LOG.log(POILogger.ERROR,
"Invalid recipient number in name " + name);
}
}
/** Holds all the chunks that were found. */
private List<Chunk> allChunks = new ArrayList<Chunk>();
+ @Override
public Map<MAPIProperty, List<PropertyValue>> getProperties() {
if (recipientProperties != null) {
return recipientProperties.getProperties();
- } else
+ } else {
return Collections.emptyMap();
+ }
}
public Chunk[] getAll() {
return allChunks.toArray(new Chunk[allChunks.size()]);
}
+ @Override
public Chunk[] getChunks() {
return getAll();
}
/**
* Called by the parser whenever a chunk is found.
*/
+ @Override
public void record(Chunk chunk) {
if (chunk.getChunkId() == RECIPIENT_SEARCH.id) {
// TODO - parse
allChunks.add(chunk);
}
+ @Override
public void chunksComplete() {
if (recipientProperties != null) {
recipientProperties.matchVariableSizedPropertiesToChunks();
} else {
- logger.log(POILogger.WARN, "Recipeints Chunk didn't contain a list of properties!");
+ LOG.log(POILogger.WARN, "Recipeints Chunk didn't contain a list of properties!");
}
}
*/
public static class RecipientChunksSorter
implements Comparator<RecipientChunks>, Serializable {
+ @Override
public int compare(RecipientChunks a, RecipientChunks b) {
- if (a.recipientNumber < b.recipientNumber)
+ if (a.recipientNumber < b.recipientNumber) {
return -1;
- if (a.recipientNumber > b.recipientNumber)
+ }
+ if (a.recipientNumber > b.recipientNumber) {
return +1;
+ }
return 0;
}
}
this.encoding7Bit = encoding;
// Re-read the String if we're a 7 bit one
- if (type == Types.ASCII_STRING) {
+ if (getType() == Types.ASCII_STRING) {
parseString();
}
}
+ @Override
public void readValue(InputStream value) throws IOException {
rawValue = IOUtils.toByteArray(value);
parseString();
private void parseString() {
String tmpValue;
- if (type == Types.ASCII_STRING) {
+ if (getType() == Types.ASCII_STRING) {
tmpValue = parseAs7BitData(rawValue, encoding7Bit);
- } else if (type == Types.UNICODE_STRING) {
+ } else if (getType() == Types.UNICODE_STRING) {
tmpValue = StringUtil.getFromUnicodeLE(rawValue);
} else {
- throw new IllegalArgumentException("Invalid type " + type + " for String Chunk");
+ throw new IllegalArgumentException("Invalid type " + getType() + " for String Chunk");
}
// Clean up
this.value = tmpValue.replace("\0", "");
}
+ @Override
public void writeValue(OutputStream out) throws IOException {
out.write(rawValue);
}
private void storeString() {
- if (type == Types.ASCII_STRING) {
+ if (getType() == Types.ASCII_STRING) {
rawValue = value.getBytes(Charset.forName(encoding7Bit));
- } else if (type == Types.UNICODE_STRING) {
+ } else if (getType() == Types.UNICODE_STRING) {
rawValue = StringUtil.getToUnicodeLE(value);
} else {
- throw new IllegalArgumentException("Invalid type " + type + " for String Chunk");
+ throw new IllegalArgumentException("Invalid type " + getType() + " for String Chunk");
}
}
storeString();
}
+ @Override
public String toString() {
return this.value;
}
return name;
}
+ @Override
public String toString() {
return id + " / 0x" + asFileEnding() + " - " + name + " @ "
+ length;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Section;
-public final class QuickTest
-{
- public QuickTest()
- {
- }
-
- public static void main(String[] args) throws IOException
- {
- HWPFDocument doc = new HWPFDocument (new FileInputStream (args[0]));
- Range r = doc.getRange();
-
- System.out.println("Example you supplied:");
- System.out.println("---------------------");
- for (int x = 0; x < r.numSections(); x++)
- {
- Section s = r.getSection(x);
- for (int y = 0; y < s.numParagraphs(); y++)
- {
- Paragraph p = s.getParagraph(y);
- for (int z = 0; z < p.numCharacterRuns(); z++)
- {
- //character run
- CharacterRun run = p.getCharacterRun(z);
- //character run text
- String text = run.text();
- // show us the text
- System.out.print(text);
- }
- // use a new line at the paragraph break
- System.out.println();
+public final class QuickTest {
+ public QuickTest() {
+ }
+
+ public static void main(String[] args) throws IOException {
+ HWPFDocument doc = new HWPFDocument(new FileInputStream(args[0]));
+ Range r = doc.getRange();
+
+ System.out.println("Example you supplied:");
+ System.out.println("---------------------");
+ for (int x = 0; x < r.numSections(); x++) {
+ Section s = r.getSection(x);
+ for (int y = 0; y < s.numParagraphs(); y++) {
+ Paragraph p = s.getParagraph(y);
+ for (int z = 0; z < p.numCharacterRuns(); z++) {
+ // character run
+ CharacterRun run = p.getCharacterRun(z);
+ // character run text
+ String text = run.text();
+ // show us the text
+ System.out.print(text);
+ }
+ // use a new line at the paragraph break
+ System.out.println();
+ }
}
- }
-
-
-// System.out.println("\n\nExample using new method:");
-// System.out.println("-------------------------");
-// for (int x = 0; x < r.numSections(); x++)
-// {
-// Section s = r.getSection(x);
-// for (int y = 0; y < s.numParagraphs(); y++)
-// {
-// Paragraph p = s.getParagraph(y);
-// for (int z = 0; z < p.numCharacterRuns(); z++)
-// {
-// //character run
-// CharacterRun run = p.getCharacterRun(z);
-// //** get character run/paragraph common text **
-// String text = run.commonText(p);
-// // show us the text
-// System.out.print(text);
-// }
-// // use a new line at the paragraph break
-// System.out.println();
-// }
-// }
- }
-
+ doc.close();
+ }
}
// Basic checks
for (AttachmentChunks attachment : attachments) {
- assertTrue(attachment.attachFileName.getValue().length() > 0);
- assertTrue(attachment.attachLongFileName.getValue().length() > 0);
- assertTrue(attachment.attachExtension.getValue().length() > 0);
- if(attachment.attachMimeTag != null) {
- assertTrue(attachment.attachMimeTag.getValue().length() > 0);
+ assertTrue(attachment.getAttachFileName().getValue().length() > 0);
+ assertTrue(attachment.getAttachLongFileName().getValue().length() > 0);
+ assertTrue(attachment.getAttachExtension().getValue().length() > 0);
+ if(attachment.getAttachMimeTag() != null) {
+ assertTrue(attachment.getAttachMimeTag().getValue().length() > 0);
}
}
// Now check in detail
attachment = twoSimpleAttachments.getAttachmentFiles()[0];
- assertEquals("TEST-U~1.DOC", attachment.attachFileName.toString());
- assertEquals("test-unicode.doc", attachment.attachLongFileName.toString());
- assertEquals(".doc", attachment.attachExtension.getValue());
- assertEquals(null, attachment.attachMimeTag);
- assertEquals(24064, attachment.attachData.getValue().length);
+ assertEquals("TEST-U~1.DOC", attachment.getAttachFileName().toString());
+ assertEquals("test-unicode.doc", attachment.getAttachLongFileName().toString());
+ assertEquals(".doc", attachment.getAttachExtension().getValue());
+ assertEquals(null, attachment.getAttachMimeTag());
+ assertEquals(24064, attachment.getAttachData().getValue().length);
attachment = twoSimpleAttachments.getAttachmentFiles()[1];
- assertEquals("pj1.txt", attachment.attachFileName.toString());
- assertEquals("pj1.txt", attachment.attachLongFileName.toString());
- assertEquals(".txt", attachment.attachExtension.getValue());
- assertEquals(null, attachment.attachMimeTag);
- assertEquals(89, attachment.attachData.getValue().length);
+ assertEquals("pj1.txt", attachment.getAttachFileName().toString());
+ assertEquals("pj1.txt", attachment.getAttachLongFileName().toString());
+ assertEquals(".txt", attachment.getAttachExtension().getValue());
+ assertEquals(null, attachment.getAttachMimeTag());
+ assertEquals(89, attachment.getAttachData().getValue().length);
}
/**
// Second is a PDF
attachment = pdfMsgAttachments.getAttachmentFiles()[1];
- assertEquals("smbprn~1.pdf", attachment.attachFileName.toString());
- assertEquals("smbprn.00009008.KdcPjl.pdf", attachment.attachLongFileName.toString());
- assertEquals(".pdf", attachment.attachExtension.getValue());
- assertEquals(null, attachment.attachMimeTag);
- assertEquals(null, attachment.attachmentDirectory);
- assertEquals(13539, attachment.attachData.getValue().length);
+ assertEquals("smbprn~1.pdf", attachment.getAttachFileName().toString());
+ assertEquals("smbprn.00009008.KdcPjl.pdf", attachment.getAttachLongFileName().toString());
+ assertEquals(".pdf", attachment.getAttachExtension().getValue());
+ assertEquals(null, attachment.getAttachMimeTag());
+ assertEquals(null, attachment.getAttachmentDirectory());
+ assertEquals(13539, attachment.getAttachData().getValue().length);
// First in a nested message
attachment = pdfMsgAttachments.getAttachmentFiles()[0];
- assertEquals("Test Attachment", attachment.attachFileName.toString());
- assertEquals(null, attachment.attachLongFileName);
- assertEquals(null, attachment.attachExtension);
- assertEquals(null, attachment.attachMimeTag);
- assertEquals(null, attachment.attachData);
- assertNotNull(attachment.attachmentDirectory);
+ assertEquals("Test Attachment", attachment.getAttachFileName().toString());
+ assertEquals(null, attachment.getAttachLongFileName());
+ assertEquals(null, attachment.getAttachExtension());
+ assertEquals(null, attachment.getAttachMimeTag());
+ assertEquals(null, attachment.getAttachData());
+ assertNotNull(attachment.getAttachmentDirectory());
// Check we can see some bits of it
- MAPIMessage nested = attachment.attachmentDirectory.getAsEmbededMessage();
+ MAPIMessage nested = attachment.getAttachmentDirectory().getAsEmbededMessage();
assertEquals(1, nested.getRecipientNamesList().length);
assertEquals("Nick Booth", nested.getRecipientNames());
assertEquals("Test Attachment", nested.getConversationTopic());
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import junit.framework.TestCase;
-
-public abstract class HWPFTestCase extends TestCase {
- protected HWPFDocFixture _hWPFDocFixture;
-
- protected HWPFTestCase() {
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- /** @todo verify the constructors */
- _hWPFDocFixture = new HWPFDocFixture(this, getTestFile());
-
- _hWPFDocFixture.setUp();
- }
-
- protected String getTestFile()
- {
- return HWPFDocFixture.DEFAULT_TEST_FILE;
- }
-
- @Override
- protected void tearDown() throws Exception {
- if (_hWPFDocFixture != null) {
- _hWPFDocFixture.tearDown();
- }
-
- _hWPFDocFixture = null;
- super.tearDown();
- }
-
- public HWPFDocument writeOutAndRead(HWPFDocument doc) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- HWPFDocument newDoc;
- try {
- doc.write(baos);
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- newDoc = new HWPFDocument(bais);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- return newDoc;
- }
+import org.junit.After;
+import org.junit.Before;
+
+public abstract class HWPFTestCase {
+ protected HWPFDocFixture _hWPFDocFixture;
+
+ @Before
+ public void setUp() throws Exception {
+ /** @todo verify the constructors */
+ _hWPFDocFixture = new HWPFDocFixture(this, getTestFile());
+
+ _hWPFDocFixture.setUp();
+ }
+
+ protected String getTestFile() {
+ return HWPFDocFixture.DEFAULT_TEST_FILE;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ if (_hWPFDocFixture != null) {
+ _hWPFDocFixture.tearDown();
+ }
+
+ _hWPFDocFixture = null;
+ }
+
+ public HWPFDocument writeOutAndRead(HWPFDocument doc) {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ HWPFDocument newDoc;
+ try {
+ doc.write(baos);
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ newDoc = new HWPFDocument(bais);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return newDoc;
+ }
}
package org.apache.poi.hwpf;
+import static org.junit.Assert.assertEquals;
+
import java.util.ArrayList;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.model.FieldsTables;
import org.apache.poi.hwpf.model.FileInformationBlock;
import org.apache.poi.hwpf.model.PlexOfField;
+import org.junit.Test;
/**
* Test case for the fields tables, this test is based on the test-fields.doc
* file instead of the usual test.doc.
- *
- * @author Cedric Bosdonnat <cbosdonnat@novell.com>
- *
*/
-public class TestFieldsTables extends HWPFTestCase
-{
+public class TestFieldsTables extends HWPFTestCase {
private static final String EXPECTED[] = {
+ "[19, 43) - FLD - 0x13; 0x1f\n" + "[43, 54) - FLD - 0x14; 0xff\n"
+ + "[54, 59) - FLD - 0x15; 0x81\n",
- "[19, 43) - FLD - 0x13; 0x1f\n" + "[43, 54) - FLD - 0x14; 0xff\n"
- + "[54, 59) - FLD - 0x15; 0x81\n",
-
- "[31, 59) - FLD - 0x13; 0x45\n" + "[59, 61) - FLD - 0x14; 0xff\n"
- + "[61, 66) - FLD - 0x15; 0x80\n",
-
- "[23, 49) - FLD - 0x13; 0x11\n" + "[49, 64) - FLD - 0x14; 0xff\n"
- + "[64, 69) - FLD - 0x15; 0x80\n",
+ "[31, 59) - FLD - 0x13; 0x45\n" + "[59, 61) - FLD - 0x14; 0xff\n"
+ + "[61, 66) - FLD - 0x15; 0x80\n",
- "[18, 42) - FLD - 0x13; 0x21\n" + "[42, 44) - FLD - 0x14; 0xff\n"
- + "[44, 47) - FLD - 0x15; 0x81\n"
- + "[47, 75) - FLD - 0x13; 0x1d\n"
- + "[75, 85) - FLD - 0x14; 0xff\n"
- + "[85, 91) - FLD - 0x15; 0x81\n",
+ "[23, 49) - FLD - 0x13; 0x11\n" + "[49, 64) - FLD - 0x14; 0xff\n"
+ + "[64, 69) - FLD - 0x15; 0x80\n",
- "[30, 54) - FLD - 0x13; 0x20\n" + "[54, 62) - FLD - 0x14; 0xff\n"
- + "[62, 68) - FLD - 0x15; 0x81\n",
+ "[18, 42) - FLD - 0x13; 0x21\n" + "[42, 44) - FLD - 0x14; 0xff\n"
+ + "[44, 47) - FLD - 0x15; 0x81\n"
+ + "[47, 75) - FLD - 0x13; 0x1d\n"
+ + "[75, 85) - FLD - 0x14; 0xff\n"
+ + "[85, 91) - FLD - 0x15; 0x81\n",
- "[1, 31) - FLD - 0x13; 0x15\n" + "[31, 51) - FLD - 0x14; 0xff\n"
- + "[51, 541) - FLD - 0x15; 0x81\n",
+ "[30, 54) - FLD - 0x13; 0x20\n" + "[54, 62) - FLD - 0x14; 0xff\n"
+ + "[62, 68) - FLD - 0x15; 0x81\n",
- "[19, 47) - FLD - 0x13; 0x19\n" + "[47, 49) - FLD - 0x14; 0xff\n"
- + "[49, 55) - FLD - 0x15; 0x81\n"
+ "[1, 31) - FLD - 0x13; 0x15\n" + "[31, 51) - FLD - 0x14; 0xff\n"
+ + "[51, 541) - FLD - 0x15; 0x81\n",
+ "[19, 47) - FLD - 0x13; 0x19\n" + "[47, 49) - FLD - 0x14; 0xff\n"
+ + "[49, 55) - FLD - 0x15; 0x81\n"
};
- public TestFieldsTables()
- {
- }
-
@Override
- protected String getTestFile()
- {
+ protected String getTestFile() {
return "test-fields.doc";
}
- public void testReadFields()
- {
+ @Test
+ public void testReadFields() {
FileInformationBlock fib = _hWPFDocFixture._fib;
byte[] tableStream = _hWPFDocFixture._tableStream;
- FieldsTables fieldsTables = new FieldsTables( tableStream, fib );
-
- for ( int i = 0; i < FieldsDocumentPart.values().length; i++ )
- {
- FieldsDocumentPart part = FieldsDocumentPart.values()[i];
+ FieldsTables fieldsTables = new FieldsTables(tableStream, fib);
- ArrayList<PlexOfField> fieldsPlexes = fieldsTables
- .getFieldsPLCF( part );
- String result = dumpPlexes( fieldsPlexes );
- assertEquals( EXPECTED[i], result );
+ int i = 0;
+ for (FieldsDocumentPart part : FieldsDocumentPart.values()) {
+ String result = dumpPlexes(fieldsTables.getFieldsPLCF(part));
+ assertEquals(EXPECTED[i++], result);
}
}
- private String dumpPlexes( ArrayList<PlexOfField> fieldsPlexes )
- {
+ private String dumpPlexes(ArrayList<PlexOfField> fieldsPlexes) {
StringBuilder dump = new StringBuilder();
- for ( int i = 0; i < fieldsPlexes.size(); i++ )
- {
- final PlexOfField flds = fieldsPlexes.get( i );
- dump.append( flds.toString() + "\n" );
+ for (PlexOfField flds : fieldsPlexes) {
+ dump.append(flds.toString() + "\n");
}
return dump.toString();
}
package org.apache.poi.hwpf.model;
-import org.apache.poi.hwpf.*;
-import org.apache.poi.hwpf.model.io.*;
-
-
-public final class TestListTables
- extends HWPFTestCase
-{
-
- public TestListTables()
- {
- }
-
- public void testReadWrite()
- throws Exception
- {
- FileInformationBlock fib = _hWPFDocFixture._fib;
- byte[] tableStream = _hWPFDocFixture._tableStream;
-
- int listOffset = fib.getFcPlfLst();
- int lfoOffset = fib.getFcPlfLfo();
- if (listOffset != 0 && fib.getLcbPlfLst() != 0)
- {
- ListTables listTables = new ListTables (tableStream, fib.getFcPlfLst(),
- fib.getFcPlfLfo (), fib.getLcbPlfLfo());
- HWPFFileSystem fileSys = new HWPFFileSystem ();
-
- HWPFOutputStream tableOut = fileSys.getStream ("1Table");
-
- listTables.writeListDataTo (fib, tableOut);
- listTables.writeListOverridesTo( fib, tableOut);
-
- ListTables newTables = new ListTables (tableOut.toByteArray (), fib.getFcPlfLst(),
- fib.getFcPlfLfo (), fib.getLcbPlfLfo());
-
- assertEquals(listTables, newTables);
-
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+
+import org.apache.poi.hwpf.HWPFTestCase;
+import org.apache.poi.hwpf.model.io.HWPFFileSystem;
+import org.apache.poi.hwpf.model.io.HWPFOutputStream;
+import org.junit.Test;
+
+public final class TestListTables extends HWPFTestCase {
+
+ @Test
+ public void testReadWrite() throws IOException {
+ FileInformationBlock fib = _hWPFDocFixture._fib;
+ byte[] tableStream = _hWPFDocFixture._tableStream;
+
+ int listOffset = fib.getFcPlfLst();
+ int lfoOffset = fib.getFcPlfLfo();
+ int bLfoOffset = fib.getLcbPlfLfo();
+
+ if (listOffset != 0 && bLfoOffset != 0) {
+ // TODO: this is actually never executed ...
+
+ ListTables listTables = new ListTables(tableStream, listOffset, lfoOffset, bLfoOffset);
+ HWPFFileSystem fileSys = new HWPFFileSystem();
+
+ HWPFOutputStream tableOut = fileSys.getStream("1Table");
+
+ listTables.writeListDataTo(fib, tableOut);
+ listTables.writeListOverridesTo(fib, tableOut);
+
+ ListTables newTables = new ListTables(tableOut.toByteArray(),
+ fib.getFcPlfLst(), fib.getFcPlfLfo(), fib.getLcbPlfLfo());
+
+ assertEquals(listTables, newTables);
+ }
}
- }
-
}
package org.apache.poi.hwpf.model;
-import java.io.*;
+import static org.junit.Assert.assertEquals;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
-import junit.framework.TestCase;
-
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.HWPFTestDataSamples;
+import org.junit.Test;
/**
* Unit test for {@link SavedByTable} and {@link SavedByEntry}.
- *
- * @author Daniel Noll
*/
-public final class TestSavedByTable
- extends TestCase
-{
+public final class TestSavedByTable {
- /** The expected entries in the test document. */
- private final List expected = Arrays.asList(new Object[] {
- new SavedByEntry("cic22", "C:\\DOCUME~1\\phamill\\LOCALS~1\\Temp\\AutoRecovery save of Iraq - security.asd"),
- new SavedByEntry("cic22", "C:\\DOCUME~1\\phamill\\LOCALS~1\\Temp\\AutoRecovery save of Iraq - security.asd"),
- new SavedByEntry("cic22", "C:\\DOCUME~1\\phamill\\LOCALS~1\\Temp\\AutoRecovery save of Iraq - security.asd"),
- new SavedByEntry("JPratt", "C:\\TEMP\\Iraq - security.doc"),
- new SavedByEntry("JPratt", "A:\\Iraq - security.doc"),
- new SavedByEntry("ablackshaw", "C:\\ABlackshaw\\Iraq - security.doc"),
- new SavedByEntry("ablackshaw", "C:\\ABlackshaw\\A;Iraq - security.doc"),
- new SavedByEntry("ablackshaw", "A:\\Iraq - security.doc"),
- new SavedByEntry("MKhan", "C:\\TEMP\\Iraq - security.doc"),
- new SavedByEntry("MKhan", "C:\\WINNT\\Profiles\\mkhan\\Desktop\\Iraq.doc")
- });
+ /** The expected entries in the test document. */
+ private final List<SavedByEntry> expected = Arrays.asList(
+ new SavedByEntry("cic22", "C:\\DOCUME~1\\phamill\\LOCALS~1\\Temp\\AutoRecovery save of Iraq - security.asd"),
+ new SavedByEntry("cic22", "C:\\DOCUME~1\\phamill\\LOCALS~1\\Temp\\AutoRecovery save of Iraq - security.asd"),
+ new SavedByEntry("cic22", "C:\\DOCUME~1\\phamill\\LOCALS~1\\Temp\\AutoRecovery save of Iraq - security.asd"),
+ new SavedByEntry("JPratt", "C:\\TEMP\\Iraq - security.doc"),
+ new SavedByEntry("JPratt", "A:\\Iraq - security.doc"),
+ new SavedByEntry("ablackshaw", "C:\\ABlackshaw\\Iraq - security.doc"),
+ new SavedByEntry("ablackshaw", "C:\\ABlackshaw\\A;Iraq - security.doc"),
+ new SavedByEntry("ablackshaw", "A:\\Iraq - security.doc"),
+ new SavedByEntry("MKhan", "C:\\TEMP\\Iraq - security.doc"),
+ new SavedByEntry("MKhan", "C:\\WINNT\\Profiles\\mkhan\\Desktop\\Iraq.doc")
+ );
- /**
- * Tests reading in the entries, comparing them against the expected entries.
- * Then tests writing the document out and reading the entries yet again.
- *
- * @throws Exception if an unexpected error occurs.
- */
- public void testReadWrite()
- throws Exception
- {
- // This document is widely available on the internet as "blair.doc".
- // I tried stripping the content and saving the document but my version
- // of Word (from Office XP) strips this table out.
- HWPFDocument doc = HWPFTestDataSamples.openSampleFile("saved-by-table.doc");
+ /**
+ * Tests reading in the entries, comparing them against the expected
+ * entries. Then tests writing the document out and reading the entries yet
+ * again.
+ *
+ * @throws Exception if an unexpected error occurs.
+ */
+ @Test
+ public void testReadWrite() throws IOException {
+ // This document is widely available on the internet as "blair.doc".
+ // I tried stripping the content and saving the document but my version
+ // of Word (from Office XP) strips this table out.
+ HWPFDocument doc = HWPFTestDataSamples.openSampleFile("saved-by-table.doc");
- // Check what we just read.
- assertEquals("List of saved-by entries was not as expected",
- expected, doc.getSavedByTable().getEntries());
+ // Check what we just read.
+ assertEquals("List of saved-by entries was not as expected", expected,
+ doc.getSavedByTable().getEntries());
- // Now write the entire document out, and read it back in...
- ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
- doc.write(byteStream);
- InputStream copyStream = new ByteArrayInputStream(byteStream.toByteArray());
- HWPFDocument copy = new HWPFDocument(copyStream);
+ // Now write the entire document out, and read it back in...
+ ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
+ doc.write(byteStream);
+ InputStream copyStream = new ByteArrayInputStream(byteStream.toByteArray());
+ doc.close();
+ HWPFDocument copy = new HWPFDocument(copyStream);
- // And check again.
- assertEquals("List of saved-by entries was incorrect after writing",
- expected, copy.getSavedByTable().getEntries());
- }
+ // And check again.
+ assertEquals("List of saved-by entries was incorrect after writing",
+ expected, copy.getSavedByTable().getEntries());
+
+ copy.close();
+ }
}