fix eclipse warnings

close resources

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1735912 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2016-03-21 00:14:21 +00:00
parent 8be67e1910
commit e9f333827d
32 changed files with 897 additions and 2155 deletions

View File

@ -28,7 +28,6 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import org.apache.poi.hpsf.HPSFRuntimeException; import org.apache.poi.hpsf.HPSFRuntimeException;
@ -109,20 +108,15 @@ public class CopyCompare
String copyFileName = null; String copyFileName = null;
/* Check the command-line arguments. */ /* Check the command-line arguments. */
if (args.length == 1) if (args.length == 1) {
{
originalFileName = args[0]; originalFileName = args[0];
File f = TempFile.createTempFile("CopyOfPOIFileSystem-", ".ole2"); File f = TempFile.createTempFile("CopyOfPOIFileSystem-", ".ole2");
f.deleteOnExit(); f.deleteOnExit();
copyFileName = f.getAbsolutePath(); copyFileName = f.getAbsolutePath();
} } else if (args.length == 2) {
else if (args.length == 2)
{
originalFileName = args[0]; originalFileName = args[0];
copyFileName = args[1]; copyFileName = args[1];
} } else {
else
{
System.err.println("Usage: " + CopyCompare.class.getName() + System.err.println("Usage: " + CopyCompare.class.getName() +
"originPOIFS [copyPOIFS]"); "originPOIFS [copyPOIFS]");
System.exit(1); System.exit(1);
@ -133,26 +127,29 @@ public class CopyCompare
final POIFSReader r = new POIFSReader(); final POIFSReader r = new POIFSReader();
final CopyFile cf = new CopyFile(copyFileName); final CopyFile cf = new CopyFile(copyFileName);
r.registerListener(cf); r.registerListener(cf);
r.read(new FileInputStream(originalFileName)); FileInputStream fis = new FileInputStream(originalFileName);
r.read(fis);
fis.close();
/* Write the new POIFS to disk. */ /* Write the new POIFS to disk. */
cf.close(); cf.close();
/* Read all documents from the original POI file system and compare them /* Read all documents from the original POI file system and compare them
* with the equivalent document from the copy. */ * with the equivalent document from the copy. */
final POIFSFileSystem opfs = final POIFSFileSystem opfs = new POIFSFileSystem(new File(originalFileName));
new POIFSFileSystem(new FileInputStream(originalFileName)); final POIFSFileSystem cpfs = new POIFSFileSystem(new File(copyFileName));
final POIFSFileSystem cpfs =
new POIFSFileSystem(new FileInputStream(copyFileName));
final DirectoryEntry oRoot = opfs.getRoot(); final DirectoryEntry oRoot = opfs.getRoot();
final DirectoryEntry cRoot = cpfs.getRoot(); final DirectoryEntry cRoot = cpfs.getRoot();
final StringBuffer messages = new StringBuffer(); final StringBuffer messages = new StringBuffer();
if (equal(oRoot, cRoot, messages)) if (equal(oRoot, cRoot, messages)) {
System.out.println("Equal"); System.out.println("Equal");
else } else {
System.out.println("Not equal: " + messages.toString()); System.out.println("Not equal: " + messages.toString());
} }
cpfs.close();
opfs.close();
}
@ -183,29 +180,23 @@ public class CopyCompare
{ {
boolean equal = true; boolean equal = true;
/* Iterate over d1 and compare each entry with its counterpart in d2. */ /* Iterate over d1 and compare each entry with its counterpart in d2. */
for (final Iterator i = d1.getEntries(); equal && i.hasNext();) for (final Entry e1 : d1) {
{
final Entry e1 = (Entry) i.next();
final String n1 = e1.getName(); final String n1 = e1.getName();
Entry e2 = null; Entry e2 = null;
try try {
{
e2 = d2.getEntry(n1); e2 = d2.getEntry(n1);
} } catch (FileNotFoundException ex) {
catch (FileNotFoundException ex)
{
msg.append("Document \"" + e1 + "\" exists, document \"" + msg.append("Document \"" + e1 + "\" exists, document \"" +
e2 + "\" does not.\n"); e2 + "\" does not.\n");
equal = false; equal = false;
break; break;
} }
if (e1.isDirectoryEntry() && e2.isDirectoryEntry()) if (e1.isDirectoryEntry() && e2.isDirectoryEntry()) {
equal = equal((DirectoryEntry) e1, (DirectoryEntry) e2, msg); equal = equal((DirectoryEntry) e1, (DirectoryEntry) e2, msg);
else if (e1.isDocumentEntry() && e2.isDocumentEntry()) } else if (e1.isDocumentEntry() && e2.isDocumentEntry()) {
equal = equal((DocumentEntry) e1, (DocumentEntry) e2, msg); equal = equal((DocumentEntry) e1, (DocumentEntry) e2, msg);
else } else {
{
msg.append("One of \"" + e1 + "\" and \"" + e2 + "\" is a " + msg.append("One of \"" + e1 + "\" and \"" + e2 + "\" is a " +
"document while the other one is a directory.\n"); "document while the other one is a directory.\n");
equal = false; equal = false;
@ -214,17 +205,12 @@ public class CopyCompare
/* Iterate over d2 just to make sure that there are no entries in d2 /* Iterate over d2 just to make sure that there are no entries in d2
* that are not in d1. */ * that are not in d1. */
for (final Iterator i = d2.getEntries(); equal && i.hasNext();) for (final Entry e2 : d2) {
{
final Entry e2 = (Entry) i.next();
final String n2 = e2.getName(); final String n2 = e2.getName();
Entry e1 = null; Entry e1 = null;
try try {
{
e1 = d1.getEntry(n2); e1 = d1.getEntry(n2);
} } catch (FileNotFoundException ex) {
catch (FileNotFoundException ex)
{
msg.append("Document \"" + e2 + "\" exitsts, document \"" + msg.append("Document \"" + e2 + "\" exitsts, document \"" +
e1 + "\" does not.\n"); e1 + "\" does not.\n");
equal = false; equal = false;
@ -263,34 +249,32 @@ public class CopyCompare
boolean equal = true; boolean equal = true;
final DocumentInputStream dis1 = new DocumentInputStream(d1); final DocumentInputStream dis1 = new DocumentInputStream(d1);
final DocumentInputStream dis2 = new DocumentInputStream(d2); final DocumentInputStream dis2 = new DocumentInputStream(d2);
try {
if (PropertySet.isPropertySetStream(dis1) && if (PropertySet.isPropertySetStream(dis1) &&
PropertySet.isPropertySetStream(dis2)) PropertySet.isPropertySetStream(dis2)) {
{
final PropertySet ps1 = PropertySetFactory.create(dis1); final PropertySet ps1 = PropertySetFactory.create(dis1);
final PropertySet ps2 = PropertySetFactory.create(dis2); final PropertySet ps2 = PropertySetFactory.create(dis2);
equal = ps1.equals(ps2); equal = ps1.equals(ps2);
if (!equal) if (!equal) {
{
msg.append("Property sets are not equal.\n"); msg.append("Property sets are not equal.\n");
return equal; return equal;
} }
} } else {
else
{
int i1; int i1;
int i2; int i2;
do do {
{
i1 = dis1.read(); i1 = dis1.read();
i2 = dis2.read(); i2 = dis2.read();
if (i1 != i2) if (i1 != i2) {
{
equal = false; equal = false;
msg.append("Documents are not equal.\n"); msg.append("Documents are not equal.\n");
break; break;
} }
} while (equal && i1 == -1);
} }
while (equal && i1 == -1); } finally {
dis2.close();
dis1.close();
} }
return true; return true;
} }
@ -306,8 +290,7 @@ public class CopyCompare
* original property set by using the {@link * original property set by using the {@link
* MutablePropertySet#MutablePropertySet(PropertySet)} constructor.</p> * MutablePropertySet#MutablePropertySet(PropertySet)} constructor.</p>
*/ */
static class CopyFile implements POIFSReaderListener static class CopyFile implements POIFSReaderListener {
{
String dstName; String dstName;
OutputStream out; OutputStream out;
POIFSFileSystem poiFs; POIFSFileSystem poiFs;
@ -321,8 +304,7 @@ public class CopyCompare
* @param dstName The name of the disk file the destination POIFS is to * @param dstName The name of the disk file the destination POIFS is to
* be written to. * be written to.
*/ */
public CopyFile(final String dstName) public CopyFile(final String dstName) {
{
this.dstName = dstName; this.dstName = dstName;
poiFs = new POIFSFileSystem(); poiFs = new POIFSFileSystem();
} }
@ -332,8 +314,7 @@ public class CopyCompare
* <p>The method is called by POI's eventing API for each file in the * <p>The method is called by POI's eventing API for each file in the
* origin POIFS.</p> * origin POIFS.</p>
*/ */
public void processPOIFSReaderEvent(final POIFSReaderEvent event) public void processPOIFSReaderEvent(final POIFSReaderEvent event) {
{
/* The following declarations are shortcuts for accessing the /* The following declarations are shortcuts for accessing the
* "event" object. */ * "event" object. */
final POIFSDocumentPath path = event.getPath(); final POIFSDocumentPath path = event.getPath();
@ -342,21 +323,16 @@ public class CopyCompare
Throwable t = null; Throwable t = null;
try try {
{
/* Find out whether the current document is a property set /* Find out whether the current document is a property set
* stream or not. */ * stream or not. */
if (PropertySet.isPropertySetStream(stream)) if (PropertySet.isPropertySetStream(stream)) {
{
/* Yes, the current document is a property set stream. /* Yes, the current document is a property set stream.
* Let's create a PropertySet instance from it. */ * Let's create a PropertySet instance from it. */
PropertySet ps = null; PropertySet ps = null;
try try {
{
ps = PropertySetFactory.create(stream); ps = PropertySetFactory.create(stream);
} } catch (NoPropertySetStreamException ex) {
catch (NoPropertySetStreamException ex)
{
/* This exception will not be thrown because we already /* This exception will not be thrown because we already
* checked above. */ * checked above. */
} }
@ -364,22 +340,16 @@ public class CopyCompare
/* Copy the property set to the destination POI file /* Copy the property set to the destination POI file
* system. */ * system. */
copy(poiFs, path, name, ps); copy(poiFs, path, name, ps);
} } else {
else
/* No, the current document is not a property set stream. We /* No, the current document is not a property set stream. We
* copy it unmodified to the destination POIFS. */ * copy it unmodified to the destination POIFS. */
copy(poiFs, event.getPath(), event.getName(), stream); copy(poiFs, event.getPath(), event.getName(), stream);
} }
catch (MarkUnsupportedException ex) } catch (MarkUnsupportedException ex) {
{
t = ex; t = ex;
} } catch (IOException ex) {
catch (IOException ex)
{
t = ex; t = ex;
} } catch (WritingNotSupportedException ex) {
catch (WritingNotSupportedException ex)
{
t = ex; t = ex;
} }
@ -388,8 +358,7 @@ public class CopyCompare
* lines check whether a checked exception occured and throws an * lines check whether a checked exception occured and throws an
* unchecked exception. The message of that exception is that of * unchecked exception. The message of that exception is that of
* the underlying checked exception. */ * the underlying checked exception. */
if (t != null) if (t != null) {
{
throw new HPSFRuntimeException throw new HPSFRuntimeException
("Could not read file \"" + path + "/" + name + ("Could not read file \"" + path + "/" + name +
"\". Reason: " + Util.toString(t)); "\". Reason: " + Util.toString(t));
@ -412,8 +381,7 @@ public class CopyCompare
final POIFSDocumentPath path, final POIFSDocumentPath path,
final String name, final String name,
final PropertySet ps) final PropertySet ps)
throws WritingNotSupportedException, IOException throws WritingNotSupportedException, IOException {
{
final DirectoryEntry de = getPath(poiFs, path); final DirectoryEntry de = getPath(poiFs, path);
final MutablePropertySet mps = new MutablePropertySet(ps); final MutablePropertySet mps = new MutablePropertySet(ps);
de.createDocument(name, mps.toInputStream()); de.createDocument(name, mps.toInputStream());
@ -434,13 +402,14 @@ public class CopyCompare
public void copy(final POIFSFileSystem poiFs, public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path, final POIFSDocumentPath path,
final String name, final String name,
final DocumentInputStream stream) throws IOException final DocumentInputStream stream)
{ throws IOException {
final DirectoryEntry de = getPath(poiFs, path); final DirectoryEntry de = getPath(poiFs, path);
final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayOutputStream out = new ByteArrayOutputStream();
int c; int c;
while ((c = stream.read()) != -1) while ((c = stream.read()) != -1) {
out.write(c); out.write(c);
}
stream.close(); stream.close();
out.close(); out.close();
final InputStream in = final InputStream in =
@ -455,8 +424,7 @@ public class CopyCompare
* @throws FileNotFoundException * @throws FileNotFoundException
* @throws IOException * @throws IOException
*/ */
public void close() throws FileNotFoundException, IOException public void close() throws FileNotFoundException, IOException {
{
out = new FileOutputStream(dstName); out = new FileOutputStream(dstName);
poiFs.writeFilesystem(out); poiFs.writeFilesystem(out);
out.close(); out.close();
@ -467,7 +435,7 @@ public class CopyCompare
/** Contains the directory paths that have already been created in the /** Contains the directory paths that have already been created in the
* output POI filesystem and maps them to their corresponding * output POI filesystem and maps them to their corresponding
* {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */ * {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */
private final Map paths = new HashMap(); private final Map<String,DirectoryEntry> paths = new HashMap<String,DirectoryEntry>();
@ -495,13 +463,11 @@ public class CopyCompare
* should use this {@link DirectoryEntry} to create documents in it. * should use this {@link DirectoryEntry} to create documents in it.
*/ */
public DirectoryEntry getPath(final POIFSFileSystem poiFs, public DirectoryEntry getPath(final POIFSFileSystem poiFs,
final POIFSDocumentPath path) final POIFSDocumentPath path) {
{ try {
try
{
/* Check whether this directory has already been created. */ /* Check whether this directory has already been created. */
final String s = path.toString(); final String s = path.toString();
DirectoryEntry de = (DirectoryEntry) paths.get(s); DirectoryEntry de = paths.get(s);
if (de != null) if (de != null)
/* Yes: return the corresponding DirectoryEntry. */ /* Yes: return the corresponding DirectoryEntry. */
return de; return de;
@ -509,12 +475,11 @@ public class CopyCompare
/* No: We have to create the directory - or return the root's /* No: We have to create the directory - or return the root's
* DirectoryEntry. */ * DirectoryEntry. */
int l = path.length(); int l = path.length();
if (l == 0) if (l == 0) {
/* Get the root directory. It does not have to be created /* Get the root directory. It does not have to be created
* since it always exists in a POIFS. */ * since it always exists in a POIFS. */
de = poiFs.getRoot(); de = poiFs.getRoot();
else } else {
{
/* Create a subordinate directory. The first step is to /* Create a subordinate directory. The first step is to
* ensure that the parent directory exists: */ * ensure that the parent directory exists: */
de = getPath(poiFs, path.getParent()); de = getPath(poiFs, path.getParent());
@ -524,9 +489,7 @@ public class CopyCompare
} }
paths.put(s, de); paths.put(s, de);
return de; return de;
} } catch (IOException ex) {
catch (IOException ex)
{
/* This exception will be thrown if the directory already /* This exception will be thrown if the directory already
* exists. However, since we have full control about directory * exists. However, since we have full control about directory
* creation we can ensure that this will never happen. */ * creation we can ensure that this will never happen. */

View File

@ -114,7 +114,9 @@ public class WriteAuthorAndTitle
final POIFSReader r = new POIFSReader(); final POIFSReader r = new POIFSReader();
final ModifySICopyTheRest msrl = new ModifySICopyTheRest(dstName); final ModifySICopyTheRest msrl = new ModifySICopyTheRest(dstName);
r.registerListener(msrl); r.registerListener(msrl);
r.read(new FileInputStream(srcName)); FileInputStream fis = new FileInputStream(srcName);
r.read(fis);
fis.close();
/* Write the new POIFS to disk. */ /* Write the new POIFS to disk. */
msrl.close(); msrl.close();

View File

@ -201,6 +201,8 @@ public class BusinessPlan {
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
wb.write(out); wb.write(out);
out.close(); out.close();
wb.close();
} }
/** /**

View File

@ -80,6 +80,8 @@ public class CellStyleDetails {
System.out.println(); System.out.println();
} }
wb.close();
} }
private static String renderColor(Color color) { private static String renderColor(Color color) {

View File

@ -91,6 +91,8 @@ public class BigGridDemo {
FileOutputStream out = new FileOutputStream("big-grid.xlsx"); FileOutputStream out = new FileOutputStream("big-grid.xlsx");
substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out); substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out);
out.close(); out.close();
wb.close();
} }
/** /**

View File

@ -89,6 +89,7 @@ public abstract class AbstractFileHandler implements FileHandler {
assertNotNull(extractor.getText()); assertNotNull(extractor.getText());
// also try metadata // also try metadata
@SuppressWarnings("resource")
POITextExtractor metadataExtractor = extractor.getMetadataTextExtractor(); POITextExtractor metadataExtractor = extractor.getMetadataTextExtractor();
assertNotNull(metadataExtractor.getText()); assertNotNull(metadataExtractor.getText());

View File

@ -32,7 +32,6 @@ import org.apache.poi.hssf.model.InternalWorkbook;
import org.apache.poi.hssf.record.DrawingGroupRecord; import org.apache.poi.hssf.record.DrawingGroupRecord;
import org.apache.poi.hssf.usermodel.HSSFPatriarch; import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
import org.apache.poi.util.StringUtil; import org.apache.poi.util.StringUtil;
/** /**
@ -133,16 +132,15 @@ public class BiffDrawingToXml {
} }
public static void writeToFile(OutputStream fos, InputStream xlsWorkbook, boolean excludeWorkbookRecords, String[] params) throws IOException { public static void writeToFile(OutputStream fos, InputStream xlsWorkbook, boolean excludeWorkbookRecords, String[] params) throws IOException {
NPOIFSFileSystem fs = new NPOIFSFileSystem(xlsWorkbook); HSSFWorkbook workbook = new HSSFWorkbook(xlsWorkbook);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
InternalWorkbook internalWorkbook = workbook.getInternalWorkbook(); InternalWorkbook internalWorkbook = workbook.getInternalWorkbook();
DrawingGroupRecord r = (DrawingGroupRecord) internalWorkbook.findFirstRecordBySid(DrawingGroupRecord.sid); DrawingGroupRecord r = (DrawingGroupRecord) internalWorkbook.findFirstRecordBySid(DrawingGroupRecord.sid);
r.decode();
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append("<workbook>\n"); builder.append("<workbook>\n");
String tab = "\t"; String tab = "\t";
if (!excludeWorkbookRecords) { if (!excludeWorkbookRecords && r != null) {
r.decode();
List<EscherRecord> escherRecords = r.getEscherRecords(); List<EscherRecord> escherRecords = r.getEscherRecords();
for (EscherRecord record : escherRecords) { for (EscherRecord record : escherRecords) {
builder.append(record.toXml(tab)); builder.append(record.toXml(tab));
@ -160,6 +158,7 @@ public class BiffDrawingToXml {
builder.append("</workbook>\n"); builder.append("</workbook>\n");
fos.write(builder.toString().getBytes(StringUtil.UTF8)); fos.write(builder.toString().getBytes(StringUtil.UTF8));
fos.close(); fos.close();
workbook.close();
} }
} }

View File

@ -116,6 +116,7 @@ public class BinaryRC4Decryptor extends Decryptor {
return skey; return skey;
} }
@SuppressWarnings("resource")
public InputStream getDataStream(DirectoryNode dir) throws IOException, public InputStream getDataStream(DirectoryNode dir) throws IOException,
GeneralSecurityException { GeneralSecurityException {
DocumentInputStream dis = dir.createDocumentInputStream(DEFAULT_POIFS_ENTRY); DocumentInputStream dis = dir.createDocumentInputStream(DEFAULT_POIFS_ENTRY);

View File

@ -57,13 +57,13 @@ public class CryptoAPIDecryptor extends Decryptor {
Cipher cipher; Cipher cipher;
byte oneByte[] = { 0 }; byte oneByte[] = { 0 };
public void seek(int pos) { public void seek(int newpos) {
if (pos > count) { if (newpos > count) {
throw new ArrayIndexOutOfBoundsException(pos); throw new ArrayIndexOutOfBoundsException(newpos);
} }
this.pos = pos; this.pos = newpos;
mark = pos; mark = newpos;
} }
public void setBlock(int block) throws GeneralSecurityException { public void setBlock(int block) throws GeneralSecurityException {
@ -233,9 +233,11 @@ public class CryptoAPIDecryptor extends Decryptor {
sbis.setBlock(entry.block); sbis.setBlock(entry.block);
InputStream is = new BoundedInputStream(sbis, entry.streamSize); InputStream is = new BoundedInputStream(sbis, entry.streamSize);
fsOut.createDocument(is, entry.streamName); fsOut.createDocument(is, entry.streamName);
is.close();
} }
leis.close(); leis.close();
sbis.close();
sbis = null; sbis = null;
bos.reset(); bos.reset();
fsOut.writeFilesystem(bos); fsOut.writeFilesystem(bos);

View File

@ -122,6 +122,7 @@ public class StandardDecryptor extends Decryptor {
return CryptoFunctions.getCipher(key, em.getCipherAlgorithm(), cm, null, Cipher.DECRYPT_MODE); return CryptoFunctions.getCipher(key, em.getCipherAlgorithm(), cm, null, Cipher.DECRYPT_MODE);
} }
@SuppressWarnings("resource")
public InputStream getDataStream(DirectoryNode dir) throws IOException { public InputStream getDataStream(DirectoryNode dir) throws IOException {
DocumentInputStream dis = dir.createDocumentInputStream(DEFAULT_POIFS_ENTRY); DocumentInputStream dis = dir.createDocumentInputStream(DEFAULT_POIFS_ENTRY);

View File

@ -124,13 +124,8 @@ public class StandardEncryptor extends Encryptor {
protected final File fileOut; protected final File fileOut;
protected final DirectoryNode dir; protected final DirectoryNode dir;
protected StandardCipherOutputStream(DirectoryNode dir) throws IOException { @SuppressWarnings("resource")
super(null); private StandardCipherOutputStream(DirectoryNode dir, File fileOut) throws IOException {
this.dir = dir;
fileOut = TempFile.createTempFile("encrypted_package", "crypt");
FileOutputStream rawStream = new FileOutputStream(fileOut);
// although not documented, we need the same padding as with agile encryption // although not documented, we need the same padding as with agile encryption
// and instead of calculating the missing bytes for the block size ourselves // and instead of calculating the missing bytes for the block size ourselves
// we leave it up to the CipherOutputStream, which generates/saves them on close() // we leave it up to the CipherOutputStream, which generates/saves them on close()
@ -141,9 +136,15 @@ public class StandardEncryptor extends Encryptor {
// KeyData.blockSize value. Any padding bytes can be used. Note that the StreamSize // KeyData.blockSize value. Any padding bytes can be used. Note that the StreamSize
// field of the EncryptedPackage field specifies the number of bytes of // field of the EncryptedPackage field specifies the number of bytes of
// unencrypted data as specified in section 2.3.4.4. // unencrypted data as specified in section 2.3.4.4.
CipherOutputStream cryptStream = new CipherOutputStream(rawStream, getCipher(getSecretKey(), "PKCS5Padding")); super(
new CipherOutputStream(new FileOutputStream(fileOut), getCipher(getSecretKey(), "PKCS5Padding"))
);
this.fileOut = fileOut;
this.dir = dir;
}
this.out = cryptStream; protected StandardCipherOutputStream(DirectoryNode dir) throws IOException {
this(dir, TempFile.createTempFile("encrypted_package", "crypt"));
} }
@Override @Override

View File

@ -212,13 +212,13 @@ public class POIFSReader
private void processProperties(final BlockList small_blocks, private void processProperties(final BlockList small_blocks,
final BlockList big_blocks, final BlockList big_blocks,
final Iterator properties, final Iterator<Property> properties,
final POIFSDocumentPath path) final POIFSDocumentPath path)
throws IOException throws IOException
{ {
while (properties.hasNext()) while (properties.hasNext())
{ {
Property property = ( Property ) properties.next(); Property property = properties.next();
String name = property.getName(); String name = property.getName();
if (property.isDirectory()) if (property.isDirectory())
@ -236,7 +236,7 @@ public class POIFSReader
else else
{ {
int startBlock = property.getStartBlock(); int startBlock = property.getStartBlock();
Iterator listeners = registry.getListeners(path, name); Iterator<POIFSReaderListener> listeners = registry.getListeners(path, name);
if (listeners.hasNext()) if (listeners.hasNext())
{ {
@ -257,8 +257,7 @@ public class POIFSReader
} }
while (listeners.hasNext()) while (listeners.hasNext())
{ {
POIFSReaderListener listener = POIFSReaderListener listener = listeners.next();
( POIFSReaderListener ) listeners.next();
listener.processPOIFSReaderEvent( listener.processPOIFSReaderEvent(
new POIFSReaderEvent( new POIFSReaderEvent(
@ -303,6 +302,7 @@ public class POIFSReader
public void processPOIFSReaderEvent(final POIFSReaderEvent event) public void processPOIFSReaderEvent(final POIFSReaderEvent event)
{ {
@SuppressWarnings("resource")
DocumentInputStream istream = event.getStream(); DocumentInputStream istream = event.getStream();
POIFSDocumentPath path = event.getPath(); POIFSDocumentPath path = event.getPath();
String name = event.getName(); String name = event.getName();

View File

@ -205,6 +205,7 @@ public final class CellUtil {
* @since POI 3.14 beta 2 * @since POI 3.14 beta 2
*/ */
public static void setCellStyleProperties(Cell cell, Map<String, Object> properties) { public static void setCellStyleProperties(Cell cell, Map<String, Object> properties) {
@SuppressWarnings("resource")
Workbook workbook = cell.getSheet().getWorkbook(); Workbook workbook = cell.getSheet().getWorkbook();
CellStyle originalStyle = cell.getCellStyle(); CellStyle originalStyle = cell.getCellStyle();
CellStyle newStyle = null; CellStyle newStyle = null;

View File

@ -19,6 +19,8 @@ package org.apache.poi.ss.usermodel;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.xssf.streaming.SXSSFCell; import org.apache.poi.xssf.streaming.SXSSFCell;
@ -38,17 +40,19 @@ public abstract class BaseTestXCell extends BaseTestCell {
} }
@Test @Test
public void testXmlEncoding(){ public void testXmlEncoding() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sh = wb.createSheet(); Sheet sh = wb1.createSheet();
Row row = sh.createRow(0); Row row = sh.createRow(0);
Cell cell = row.createCell(0); Cell cell = row.createCell(0);
String sval = "\u0000\u0002\u0012<>\t\n\u00a0 &\"POI\'\u2122"; String sval = "\u0000\u0002\u0012<>\t\n\u00a0 &\"POI\'\u2122";
cell.setCellValue(sval); cell.setCellValue(sval);
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
// invalid characters are replaced with question marks // invalid characters are replaced with question marks
assertEquals("???<>\t\n\u00a0 &\"POI\'\u2122", wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); assertEquals("???<>\t\n\u00a0 &\"POI\'\u2122", wb2.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
wb2.close();
} }
} }

View File

@ -20,9 +20,6 @@ package org.apache.poi.xssf.usermodel;
import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.ss.usermodel.BaseTestSheetHiding; import org.apache.poi.ss.usermodel.BaseTestSheetHiding;
/**
* @author Yegor Kozlov
*/
public final class TestSheetHiding extends BaseTestSheetHiding { public final class TestSheetHiding extends BaseTestSheetHiding {
public TestSheetHiding() { public TestSheetHiding() {
super(XSSFITestDataProvider.instance, super(XSSFITestDataProvider.instance,

View File

@ -66,7 +66,7 @@ public final class TestXSSFCell extends BaseTestXCell {
* Shared String Table * Shared String Table
*/ */
@Test @Test
public void test47026_1() throws Exception { public void test47026_1() throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook("47026.xlsm"); Workbook wb = _testDataProvider.openSampleWorkbook("47026.xlsm");
Sheet sheet = wb.getSheetAt(0); Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0); Row row = sheet.getRow(0);
@ -77,7 +77,7 @@ public final class TestXSSFCell extends BaseTestXCell {
} }
@Test @Test
public void test47026_2() throws Exception { public void test47026_2() throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook("47026.xlsm"); Workbook wb = _testDataProvider.openSampleWorkbook("47026.xlsm");
Sheet sheet = wb.getSheetAt(0); Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0); Row row = sheet.getRow(0);
@ -95,7 +95,7 @@ public final class TestXSSFCell extends BaseTestXCell {
* instead of using the shared string table. See bug 47206 * instead of using the shared string table. See bug 47206
*/ */
@Test @Test
public void testInlineString() throws Exception { public void testInlineString() throws IOException {
XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("xlsx-jdbc.xlsx"); XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("xlsx-jdbc.xlsx");
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row = sheet.getRow(1); XSSFRow row = sheet.getRow(1);
@ -121,7 +121,7 @@ public final class TestXSSFCell extends BaseTestXCell {
* Bug 47278 - xsi:nil attribute for <t> tag caused Excel 2007 to fail to open workbook * Bug 47278 - xsi:nil attribute for <t> tag caused Excel 2007 to fail to open workbook
*/ */
@Test @Test
public void test47278() throws Exception { public void test47278() throws IOException {
XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.createWorkbook(); XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
@ -187,7 +187,7 @@ public final class TestXSSFCell extends BaseTestXCell {
* Bug 47889: problems when calling XSSFCell.getStringCellValue() on a workbook created in Gnumeric * Bug 47889: problems when calling XSSFCell.getStringCellValue() on a workbook created in Gnumeric
*/ */
@Test @Test
public void test47889() throws Exception { public void test47889() throws IOException {
XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("47889.xlsx"); XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("47889.xlsx");
XSSFSheet sh = wb.getSheetAt(0); XSSFSheet sh = wb.getSheetAt(0);
@ -214,7 +214,7 @@ public final class TestXSSFCell extends BaseTestXCell {
} }
@Test @Test
public void testMissingRAttribute() throws Exception { public void testMissingRAttribute() throws IOException {
XSSFWorkbook wb1 = new XSSFWorkbook(); XSSFWorkbook wb1 = new XSSFWorkbook();
XSSFSheet sheet = wb1.createSheet(); XSSFSheet sheet = wb1.createSheet();
XSSFRow row = sheet.createRow(0); XSSFRow row = sheet.createRow(0);
@ -269,7 +269,7 @@ public final class TestXSSFCell extends BaseTestXCell {
} }
@Test @Test
public void testMissingRAttributeBug54288() throws Exception { public void testMissingRAttributeBug54288() throws IOException {
// workbook with cells missing the R attribute // workbook with cells missing the R attribute
XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("54288.xlsx"); XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("54288.xlsx");
// same workbook re-saved in Excel 2010, the R attribute is updated for every cell with the right value. // same workbook re-saved in Excel 2010, the R attribute is updated for every cell with the right value.
@ -453,7 +453,7 @@ public final class TestXSSFCell extends BaseTestXCell {
} }
@Test @Test
public void testEncodingbeloAscii() throws Exception { public void testEncodingbeloAscii() throws IOException {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
// test all possible characters // test all possible characters
for(int i = 0; i < Character.MAX_VALUE; i++) { for(int i = 0; i < Character.MAX_VALUE; i++) {

View File

@ -24,12 +24,7 @@ import org.apache.poi.xssf.XSSFITestDataProvider;
* Tests setting and evaluating user-defined functions in HSSF * Tests setting and evaluating user-defined functions in HSSF
*/ */
public final class TestXSSFExternalFunctions extends BaseTestExternalFunctions { public final class TestXSSFExternalFunctions extends BaseTestExternalFunctions {
public TestXSSFExternalFunctions() { public TestXSSFExternalFunctions() {
super(XSSFITestDataProvider.instance); super(XSSFITestDataProvider.instance, "atp.xlsx");
}
public void testATP(){
baseTestInvokeATP("atp.xlsx");
} }
} }

View File

@ -17,7 +17,10 @@
package org.apache.poi.xssf.usermodel; package org.apache.poi.xssf.usermodel;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.IOException; import java.io.IOException;
@ -27,14 +30,12 @@ import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.ss.util.CellUtil; import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test; import org.junit.Test;
/**
* @author Yegor Kozlov
*/
public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
public TestXSSFSheetShiftRows(){ public TestXSSFSheetShiftRows(){
@ -43,7 +44,8 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
@Override @Override
@Test @Test
public void testShiftRowBreaks() { // disabled test from superclass public void testShiftRowBreaks() {
// disabled test from superclass
// TODO - support shifting of page breaks // TODO - support shifting of page breaks
} }
@ -85,10 +87,10 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
// org.apache.xmlbeans.impl.values.XmlValueDisconnectedException. // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException.
// NOTE: another negative shift on another group of rows is successful, provided no new rows in // NOTE: another negative shift on another group of rows is successful, provided no new rows in
// place of previously shifted rows were attempted to be created as explained above. // place of previously shifted rows were attempted to be created as explained above.
testSheet.shiftRows(6, 7, 1); // -- CHANGE the shift to positive once the behaviour of
// the above has been tested
//saveReport(wb, new File("/tmp/53798.xlsx")); // -- CHANGE the shift to positive once the behaviour of the above has been tested
testSheet.shiftRows(6, 7, 1);
Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb);
wb.close(); wb.close();
assertNotNull(read); assertNotNull(read);
@ -131,7 +133,6 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
} }
testSheet.shiftRows(6, 6, 1); testSheet.shiftRows(6, 6, 1);
//saveReport(wb, new File("/tmp/53798.xlsx"));
Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb);
wb.close(); wb.close();
assertNotNull(read); assertNotNull(read);
@ -155,7 +156,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
Sheet sheet = wb.getSheetAt(0); Sheet sheet = wb.getSheetAt(0);
Comment comment = sheet.getCellComment(0, 0); Comment comment = sheet.getCellComment(new CellAddress(0, 0));
assertNotNull(comment); assertNotNull(comment);
assertEquals("Amdocs", comment.getAuthor()); assertEquals("Amdocs", comment.getAuthor());
assertEquals("Amdocs:\ntest\n", comment.getString().getString()); assertEquals("Amdocs:\ntest\n", comment.getString().getString());
@ -163,22 +164,15 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
sheet.shiftRows(0, 1, 1); sheet.shiftRows(0, 1, 1);
// comment in row 0 is gone // comment in row 0 is gone
comment = sheet.getCellComment(0, 0); comment = sheet.getCellComment(new CellAddress(0, 0));
assertNull(comment); assertNull(comment);
// comment is now in row 1 // comment is now in row 1
comment = sheet.getCellComment(1, 0); comment = sheet.getCellComment(new CellAddress(1, 0));
assertNotNull(comment); assertNotNull(comment);
assertEquals("Amdocs", comment.getAuthor()); assertEquals("Amdocs", comment.getAuthor());
assertEquals("Amdocs:\ntest\n", comment.getString().getString()); assertEquals("Amdocs:\ntest\n", comment.getString().getString());
// FileOutputStream outputStream = new FileOutputStream("/tmp/56017.xlsx");
// try {
// wb.write(outputStream);
// } finally {
// outputStream.close();
// }
Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
wb.close(); wb.close();
assertNotNull(wbBack); assertNotNull(wbBack);
@ -186,11 +180,11 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
Sheet sheetBack = wbBack.getSheetAt(0); Sheet sheetBack = wbBack.getSheetAt(0);
// comment in row 0 is gone // comment in row 0 is gone
comment = sheetBack.getCellComment(0, 0); comment = sheetBack.getCellComment(new CellAddress(0, 0));
assertNull(comment); assertNull(comment);
// comment is now in row 1 // comment is now in row 1
comment = sheetBack.getCellComment(1, 0); comment = sheetBack.getCellComment(new CellAddress(1, 0));
assertNotNull(comment); assertNotNull(comment);
assertEquals("Amdocs", comment.getAuthor()); assertEquals("Amdocs", comment.getAuthor());
assertEquals("Amdocs:\ntest\n", comment.getString().getString()); assertEquals("Amdocs:\ntest\n", comment.getString().getString());
@ -211,7 +205,6 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
wbRead.removeSheetAt(0); wbRead.removeSheetAt(0);
assertEquals(0, wbRead.getActiveSheetIndex()); assertEquals(0, wbRead.getActiveSheetIndex());
//wb.write(new FileOutputStream("/tmp/57171.xls"));
wbRead.close(); wbRead.close();
} }
@ -222,7 +215,6 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
wb.removeSheetAt(0); wb.removeSheetAt(0);
assertEquals(4, wb.getActiveSheetIndex()); assertEquals(4, wb.getActiveSheetIndex());
//wb.write(new FileOutputStream("/tmp/57163.xls"));
wb.close(); wb.close();
} }
@ -320,7 +312,6 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
wb.close(); wb.close();
} }
// TODO: enable when bug 57165 is fixed
@Test @Test
public void test57165() throws IOException { public void test57165() throws IOException {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx");
@ -333,20 +324,9 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
wb.setSheetName(1, "New Sheet"); wb.setSheetName(1, "New Sheet");
assertEquals(0, wb.getActiveSheetIndex()); assertEquals(0, wb.getActiveSheetIndex());
//wb.write(new FileOutputStream("/tmp/57165.xls"));
wb.close(); wb.close();
} }
// public void test57165b() throws IOException {
// Workbook wb = new XSSFWorkbook();
// try {
// wb.createSheet("New Sheet 1");
// wb.createSheet("New Sheet 2");
// } finally {
// wb.close();
// }
// }
private static void removeAllSheetsBut(int sheetIndex, Workbook wb) { private static void removeAllSheetsBut(int sheetIndex, Workbook wb) {
int sheetNb = wb.getNumberOfSheets(); int sheetNb = wb.getNumberOfSheets();
// Move this sheet at the first position // Move this sheet at the first position
@ -354,8 +334,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
// Must make this sheet active (otherwise, for XLSX, Excel might protest that active sheet no longer exists) // Must make this sheet active (otherwise, for XLSX, Excel might protest that active sheet no longer exists)
// I think POI should automatically handle this case when deleting sheets... // I think POI should automatically handle this case when deleting sheets...
// wb.setActiveSheet(0); // wb.setActiveSheet(0);
for (int sn = sheetNb - 1; sn > 0; sn--) for (int sn = sheetNb - 1; sn > 0; sn--) {
{
wb.removeSheetAt(sn); wb.removeSheetAt(sn);
} }
} }
@ -365,33 +344,26 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57828.xlsx"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57828.xlsx");
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb.getSheetAt(0);
Comment comment1 = sheet.getCellComment(2, 1); Comment comment1 = sheet.getCellComment(new CellAddress(2, 1));
assertNotNull(comment1); assertNotNull(comment1);
Comment comment2 = sheet.getCellComment(2, 2); Comment comment2 = sheet.getCellComment(new CellAddress(2, 2));
assertNotNull(comment2); assertNotNull(comment2);
Comment comment3 = sheet.getCellComment(1, 1); Comment comment3 = sheet.getCellComment(new CellAddress(1, 1));
assertNull("NO comment in (1,1) and it should be null", comment3); assertNull("NO comment in (1,1) and it should be null", comment3);
sheet.shiftRows(2, 2, -1); sheet.shiftRows(2, 2, -1);
comment3 = sheet.getCellComment(1, 1); comment3 = sheet.getCellComment(new CellAddress(1, 1));
assertNotNull("Comment in (2,1) moved to (1,1) so its not null now.", comment3); assertNotNull("Comment in (2,1) moved to (1,1) so its not null now.", comment3);
comment1 = sheet.getCellComment(2, 1); comment1 = sheet.getCellComment(new CellAddress(2, 1));
assertNull("No comment currently in (2,1) and hence it is null", comment1); assertNull("No comment currently in (2,1) and hence it is null", comment1);
comment2 = sheet.getCellComment(1, 2); comment2 = sheet.getCellComment(new CellAddress(1, 2));
assertNotNull("Comment in (2,2) should have moved as well because of shift rows. But its not", comment2); assertNotNull("Comment in (2,2) should have moved as well because of shift rows. But its not", comment2);
// OutputStream stream = new FileOutputStream("/tmp/57828.xlsx");
// try {
// wb.write(stream);
// } finally {
// stream.close();
// }
wb.close(); wb.close();
} }
} }

View File

@ -30,29 +30,37 @@ import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.util.IOUtils; import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.LocaleUtil;
import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
public class TestEscherDump { public class TestEscherDump {
static NullPrinterStream nullPS;
@BeforeClass
public static void init() throws UnsupportedEncodingException {
nullPS = new NullPrinterStream();
}
@Test @Test
public void testSimple() throws Exception { public void testSimple() throws Exception {
// simple test to at least cover some parts of the class // simple test to at least cover some parts of the class
EscherDump.main(new String[] {}, new NullPrinterStream()); EscherDump.main(new String[] {}, nullPS);
new EscherDump().dump(0, new byte[] {}, new NullPrinterStream()); new EscherDump().dump(0, new byte[] {}, nullPS);
new EscherDump().dump(new byte[] {}, 0, 0, new NullPrinterStream()); new EscherDump().dump(new byte[] {}, 0, 0, nullPS);
new EscherDump().dumpOld(0, new ByteArrayInputStream(new byte[] {}), new NullPrinterStream()); new EscherDump().dumpOld(0, new ByteArrayInputStream(new byte[] {}), nullPS);
} }
@Test @Test
public void testWithData() throws Exception { public void testWithData() throws Exception {
new EscherDump().dumpOld(8, new ByteArrayInputStream(new byte[] { 00, 00, 00, 00, 00, 00, 00, 00 }), new NullPrinterStream()); new EscherDump().dumpOld(8, new ByteArrayInputStream(new byte[] { 00, 00, 00, 00, 00, 00, 00, 00 }), nullPS);
} }
@Test @Test
public void testWithSamplefile() throws Exception { public void testWithSamplefile() throws Exception {
//InputStream stream = HSSFTestDataSamples.openSampleFileStream(") //InputStream stream = HSSFTestDataSamples.openSampleFileStream(")
byte[] data = POIDataSamples.getDDFInstance().readFile("Container.dat"); byte[] data = POIDataSamples.getDDFInstance().readFile("Container.dat");
new EscherDump().dump(data.length, data, new NullPrinterStream()); new EscherDump().dump(data.length, data, nullPS);
//new EscherDump().dumpOld(data.length, new ByteArrayInputStream(data), System.out); //new EscherDump().dumpOld(data.length, new ByteArrayInputStream(data), System.out);
data = new byte[2586114]; data = new byte[2586114];
@ -72,6 +80,7 @@ public class TestEscherDump {
* to redirect stdout to avoid spamming the console with output * to redirect stdout to avoid spamming the console with output
*/ */
private static class NullPrinterStream extends PrintStream { private static class NullPrinterStream extends PrintStream {
@SuppressWarnings("resource")
private NullPrinterStream() throws UnsupportedEncodingException { private NullPrinterStream() throws UnsupportedEncodingException {
super(new NullOutputStream(),true,LocaleUtil.CHARSET_1252.name()); super(new NullOutputStream(),true,LocaleUtil.CHARSET_1252.name());
} }

View File

@ -849,10 +849,14 @@ public class TestWrite
sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
sinf = (SummaryInformation)PropertySetFactory.create(new NDocumentInputStream(sinfDoc)); InputStream sinfStream = new NDocumentInputStream(sinfDoc);
sinf = (SummaryInformation)PropertySetFactory.create(sinfStream);
sinfStream.close();
assertEquals(131077, sinf.getOSVersion()); assertEquals(131077, sinf.getOSVersion());
dinf = (DocumentSummaryInformation)PropertySetFactory.create(new NDocumentInputStream(dinfDoc)); InputStream dinfStream = new NDocumentInputStream(dinfDoc);
dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream);
dinfStream.close();
assertEquals(131077, dinf.getOSVersion()); assertEquals(131077, dinf.getOSVersion());
@ -874,10 +878,14 @@ public class TestWrite
sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
sinf = (SummaryInformation)PropertySetFactory.create(new NDocumentInputStream(sinfDoc)); InputStream sinfStream2 = new NDocumentInputStream(sinfDoc);
sinf = (SummaryInformation)PropertySetFactory.create(sinfStream2);
sinfStream2.close();
assertEquals(131077, sinf.getOSVersion()); assertEquals(131077, sinf.getOSVersion());
dinf = (DocumentSummaryInformation)PropertySetFactory.create(new NDocumentInputStream(dinfDoc)); InputStream dinfStream2 = new NDocumentInputStream(dinfDoc);
dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream2);
dinfStream2.close();
assertEquals(131077, dinf.getOSVersion()); assertEquals(131077, dinf.getOSVersion());
@ -896,16 +904,24 @@ public class TestWrite
sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
sinf = (SummaryInformation)PropertySetFactory.create(new NDocumentInputStream(sinfDoc)); InputStream sinfStream3 = new NDocumentInputStream(sinfDoc);
sinf = (SummaryInformation)PropertySetFactory.create(sinfStream3);
sinfStream3.close();
assertEquals(131077, sinf.getOSVersion()); assertEquals(131077, sinf.getOSVersion());
dinf = (DocumentSummaryInformation)PropertySetFactory.create(new NDocumentInputStream(dinfDoc)); InputStream dinfStream3 = new NDocumentInputStream(dinfDoc);
dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream3);
dinfStream3.close();
assertEquals(131077, dinf.getOSVersion()); assertEquals(131077, dinf.getOSVersion());
// Have them write themselves in-place with no changes, as an OutputStream // Have them write themselves in-place with no changes, as an OutputStream
sinf.write(new NDocumentOutputStream(sinfDoc)); OutputStream soufStream = new NDocumentOutputStream(sinfDoc);
dinf.write(new NDocumentOutputStream(dinfDoc)); sinf.write(soufStream);
soufStream.close();
OutputStream doufStream = new NDocumentOutputStream(dinfDoc);
dinf.write(doufStream);
doufStream.close();
// And also write to some bytes for checking // And also write to some bytes for checking
ByteArrayOutputStream sinfBytes = new ByteArrayOutputStream(); ByteArrayOutputStream sinfBytes = new ByteArrayOutputStream();
@ -918,17 +934,25 @@ public class TestWrite
sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
byte[] sinfData = IOUtils.toByteArray(new NDocumentInputStream(sinfDoc)); InputStream sinfStream4 = new NDocumentInputStream(sinfDoc);
byte[] dinfData = IOUtils.toByteArray(new NDocumentInputStream(dinfDoc)); byte[] sinfData = IOUtils.toByteArray(sinfStream4);
sinfStream4.close();
InputStream dinfStream4 = new NDocumentInputStream(dinfDoc);
byte[] dinfData = IOUtils.toByteArray(dinfStream4);
dinfStream4.close();
assertThat(sinfBytes.toByteArray(), equalTo(sinfData)); assertThat(sinfBytes.toByteArray(), equalTo(sinfData));
assertThat(dinfBytes.toByteArray(), equalTo(dinfData)); assertThat(dinfBytes.toByteArray(), equalTo(dinfData));
// Read back in as-is // Read back in as-is
sinf = (SummaryInformation)PropertySetFactory.create(new NDocumentInputStream(sinfDoc)); InputStream sinfStream5 = new NDocumentInputStream(sinfDoc);
sinf = (SummaryInformation)PropertySetFactory.create(sinfStream5);
sinfStream5.close();
assertEquals(131077, sinf.getOSVersion()); assertEquals(131077, sinf.getOSVersion());
dinf = (DocumentSummaryInformation)PropertySetFactory.create(new NDocumentInputStream(dinfDoc)); InputStream dinfStream5 = new NDocumentInputStream(dinfDoc);
dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream5);
dinfStream5.close();
assertEquals(131077, dinf.getOSVersion()); assertEquals(131077, dinf.getOSVersion());
assertEquals("Reiichiro Hori", sinf.getAuthor()); assertEquals("Reiichiro Hori", sinf.getAuthor());
@ -946,17 +970,25 @@ public class TestWrite
// Save this into the filesystem // Save this into the filesystem
sinf.write(new NDocumentOutputStream(sinfDoc)); OutputStream soufStream2 = new NDocumentOutputStream(sinfDoc);
dinf.write(new NDocumentOutputStream(dinfDoc)); sinf.write(soufStream2);
soufStream2.close();
OutputStream doufStream2 = new NDocumentOutputStream(dinfDoc);
dinf.write(doufStream2);
doufStream2.close();
// Read them back in again // Read them back in again
sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
sinf = (SummaryInformation)PropertySetFactory.create(new NDocumentInputStream(sinfDoc)); InputStream sinfStream6 = new NDocumentInputStream(sinfDoc);
sinf = (SummaryInformation)PropertySetFactory.create(sinfStream6);
sinfStream6.close();
assertEquals(131077, sinf.getOSVersion()); assertEquals(131077, sinf.getOSVersion());
dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
dinf = (DocumentSummaryInformation)PropertySetFactory.create(new NDocumentInputStream(dinfDoc)); InputStream dinfStream6 = new NDocumentInputStream(dinfDoc);
dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream6);
dinfStream6.close();
assertEquals(131077, dinf.getOSVersion()); assertEquals(131077, dinf.getOSVersion());
assertEquals("Changed Author", sinf.getAuthor()); assertEquals("Changed Author", sinf.getAuthor());
@ -976,11 +1008,15 @@ public class TestWrite
// Re-check on load // Re-check on load
sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
sinf = (SummaryInformation)PropertySetFactory.create(new NDocumentInputStream(sinfDoc)); InputStream sinfStream7 = new NDocumentInputStream(sinfDoc);
sinf = (SummaryInformation)PropertySetFactory.create(sinfStream7);
sinfStream7.close();
assertEquals(131077, sinf.getOSVersion()); assertEquals(131077, sinf.getOSVersion());
dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
dinf = (DocumentSummaryInformation)PropertySetFactory.create(new NDocumentInputStream(dinfDoc)); InputStream dinfStream7 = new NDocumentInputStream(dinfDoc);
dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream7);
dinfStream7.close();
assertEquals(131077, dinf.getOSVersion()); assertEquals(131077, dinf.getOSVersion());
assertEquals("Changed Author", sinf.getAuthor()); assertEquals("Changed Author", sinf.getAuthor());

View File

@ -97,15 +97,20 @@ public abstract class BaseXLSIteratingTest {
// try to read it in HSSFWorkbook to quickly fail if we cannot read the file there at all and thus probably should use EXCLUDED instead // try to read it in HSSFWorkbook to quickly fail if we cannot read the file there at all and thus probably should use EXCLUDED instead
FileInputStream stream = new FileInputStream(file); FileInputStream stream = new FileInputStream(file);
HSSFWorkbook wb = null;
try { try {
assertNotNull(new HSSFWorkbook(stream)); wb = new HSSFWorkbook(stream);
assertNotNull(wb);
} finally { } finally {
if (wb != null) {
wb.close();
}
stream.close(); stream.close();
} }
} }
} }
abstract void runOneFile(File file) throws Exception; abstract void runOneFile(File pFile) throws Exception;
/** /**
* Implementation of an OutputStream which does nothing, used * Implementation of an OutputStream which does nothing, used

View File

@ -21,33 +21,30 @@ import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.PrintStream; import java.io.PrintStream;
import org.junit.Ignore;
import org.junit.Test;
public class TestBiffDrawingToXml extends BaseXLSIteratingTest { public class TestBiffDrawingToXml extends BaseXLSIteratingTest {
static { static {
// TODO: is it ok to fail these? EXCLUDED.add("35897-type4.xls"); // unsupported crypto api header
// Look at the output of the test for the detailed stacktrace of the failures... EXCLUDED.add("43493.xls"); // HSSFWorkbook cannot open it as well
// EXCLUDED.add("password.xls"); EXCLUDED.add("46904.xls");
// EXCLUDED.add("XRefCalc.xls"); EXCLUDED.add("44958_1.xls");
// EXCLUDED.add("43493.xls"); EXCLUDED.add("51832.xls");
// EXCLUDED.add("51832.xls"); EXCLUDED.add("59074.xls");
EXCLUDED.add("password.xls");
EXCLUDED.add("testEXCEL_2.xls"); // Biff 2 / Excel 2, pre-OLE2
EXCLUDED.add("testEXCEL_3.xls"); // Biff 3 / Excel 3, pre-OLE2
EXCLUDED.add("testEXCEL_4.xls"); // Biff 4 / Excel 4, pre-OLE2
EXCLUDED.add("testEXCEL_5.xls"); // Biff 5 / Excel 5
EXCLUDED.add("testEXCEL_95.xls"); // Biff 5 / Excel 95
EXCLUDED.add("xor-encryption-abc.xls");
} }
@Override @Override
@Ignore("Not yet done, nearly all files fail with various errors, remove this method when done to use the one from the abstract base class!...") void runOneFile(File pFile) throws Exception {
@Test
public void testMain() throws Exception {
}
@Override
void runOneFile(File file)
throws Exception {
PrintStream save = System.out; PrintStream save = System.out;
try { try {
//System.setOut(new PrintStream(TestBiffViewer.NULL_OUTPUT_STREAM)); //System.setOut(new PrintStream(TestBiffViewer.NULL_OUTPUT_STREAM));
// use a NullOutputStream to not write the bytes anywhere for best runtime // use a NullOutputStream to not write the bytes anywhere for best runtime
InputStream wb = new FileInputStream(file); InputStream wb = new FileInputStream(pFile);
try { try {
BiffDrawingToXml.writeToFile(NULL_OUTPUT_STREAM, wb, false, new String[] {}); BiffDrawingToXml.writeToFile(NULL_OUTPUT_STREAM, wb, false, new String[] {});
} finally { } finally {

View File

@ -17,11 +17,15 @@
package org.apache.poi.hssf.model; package org.apache.poi.hssf.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.ddf.EscherBoolProperty; import org.apache.poi.ddf.EscherBoolProperty;
import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherContainerRecord;
import org.apache.poi.ddf.EscherDgRecord; import org.apache.poi.ddf.EscherDgRecord;
@ -34,21 +38,33 @@ import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.CommonObjectDataSubRecord; import org.apache.poi.hssf.record.CommonObjectDataSubRecord;
import org.apache.poi.hssf.record.EscherAggregate; import org.apache.poi.hssf.record.EscherAggregate;
import org.apache.poi.hssf.record.ObjRecord; import org.apache.poi.hssf.record.ObjRecord;
import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.usermodel.HSSFAnchor;
import org.apache.poi.hssf.usermodel.HSSFChildAnchor;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFPicture;
import org.apache.poi.hssf.usermodel.HSSFPolygon;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.hssf.usermodel.HSSFShapeGroup;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFSimpleShape;
import org.apache.poi.hssf.usermodel.HSSFTestHelper;
import org.apache.poi.hssf.usermodel.HSSFTextbox;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.HexDump; import org.apache.poi.util.HexDump;
import org.junit.Test;
/** /**
* @author Evgeniy Berlog * Test escher drawing
* date: 12.06.12 *
* optionally the system setting "poi.deserialize.escher" can be set to {@code true}
*/ */
public class TestDrawingShapes extends TestCase { public class TestDrawingShapes {
static {
//System.setProperty("poi.deserialize.escher", "true");
}
/** /**
* HSSFShape tree bust be built correctly * HSSFShape tree bust be built correctly
* Check file with such records structure: * Check file with such records structure:
@ -63,7 +79,8 @@ public class TestDrawingShapes extends TestCase {
* ----shape * ----shape
* ----shape * ----shape
*/ */
public void testDrawingGroups() { @Test
public void testDrawingGroups() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls");
HSSFSheet sheet = wb.getSheet("groups"); HSSFSheet sheet = wb.getSheet("groups");
HSSFPatriarch patriarch = sheet.getDrawingPatriarch(); HSSFPatriarch patriarch = sheet.getDrawingPatriarch();
@ -74,8 +91,10 @@ public class TestDrawingShapes extends TestCase {
assertEquals(2, group1.getChildren().size()); assertEquals(2, group1.getChildren().size());
group1 = (HSSFShapeGroup) group.getChildren().get(2); group1 = (HSSFShapeGroup) group.getChildren().get(2);
assertEquals(2, group1.getChildren().size()); assertEquals(2, group1.getChildren().size());
wb.close();
} }
@Test
public void testHSSFShapeCompatibility() { public void testHSSFShapeCompatibility() {
HSSFSimpleShape shape = new HSSFSimpleShape(null, new HSSFClientAnchor()); HSSFSimpleShape shape = new HSSFSimpleShape(null, new HSSFClientAnchor());
shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
@ -91,35 +110,33 @@ public class TestDrawingShapes extends TestCase {
spContainer.getChildById(EscherOptRecord.RECORD_ID); spContainer.getChildById(EscherOptRecord.RECORD_ID);
assertEquals(7, opt.getEscherProperties().size()); assertEquals(7, opt.getEscherProperties().size());
assertEquals(true, assertTrue(((EscherBoolProperty) opt.lookup(EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE)).isTrue());
((EscherBoolProperty) opt.lookup(EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE)).isTrue());
assertEquals(0x00000004, assertEquals(0x00000004,
((EscherSimpleProperty) opt.lookup(EscherProperties.GEOMETRY__SHAPEPATH)).getPropertyValue()); ((EscherSimpleProperty) opt.lookup(EscherProperties.GEOMETRY__SHAPEPATH)).getPropertyValue());
assertEquals(0x08000009, assertEquals(0x08000009,
((EscherSimpleProperty) opt.lookup(EscherProperties.FILL__FILLCOLOR)).getPropertyValue()); ((EscherSimpleProperty) opt.lookup(EscherProperties.FILL__FILLCOLOR)).getPropertyValue());
assertEquals(true, assertTrue(((EscherBoolProperty) opt.lookup(EscherProperties.FILL__NOFILLHITTEST)).isTrue());
((EscherBoolProperty) opt.lookup(EscherProperties.FILL__NOFILLHITTEST)).isTrue());
assertEquals(0x08000040, assertEquals(0x08000040,
((EscherSimpleProperty) opt.lookup(EscherProperties.LINESTYLE__COLOR)).getPropertyValue()); ((EscherSimpleProperty) opt.lookup(EscherProperties.LINESTYLE__COLOR)).getPropertyValue());
assertEquals(true, assertTrue(((EscherBoolProperty) opt.lookup(EscherProperties.LINESTYLE__NOLINEDRAWDASH)).isTrue());
((EscherBoolProperty) opt.lookup(EscherProperties.LINESTYLE__NOLINEDRAWDASH)).isTrue()); assertTrue(((EscherBoolProperty) opt.lookup(EscherProperties.GROUPSHAPE__PRINT)).isTrue());
assertEquals(true,
((EscherBoolProperty) opt.lookup(EscherProperties.GROUPSHAPE__PRINT)).isTrue());
} }
@Test
public void testDefaultPictureSettings() { public void testDefaultPictureSettings() {
HSSFPicture picture = new HSSFPicture(null, new HSSFClientAnchor()); HSSFPicture picture = new HSSFPicture(null, new HSSFClientAnchor());
assertEquals(picture.getLineWidth(), HSSFShape.LINEWIDTH_DEFAULT); assertEquals(picture.getLineWidth(), HSSFShape.LINEWIDTH_DEFAULT);
assertEquals(picture.getFillColor(), HSSFShape.FILL__FILLCOLOR_DEFAULT); assertEquals(picture.getFillColor(), HSSFShape.FILL__FILLCOLOR_DEFAULT);
assertEquals(picture.getLineStyle(), HSSFShape.LINESTYLE_NONE); assertEquals(picture.getLineStyle(), HSSFShape.LINESTYLE_NONE);
assertEquals(picture.getLineStyleColor(), HSSFShape.LINESTYLE__COLOR_DEFAULT); assertEquals(picture.getLineStyleColor(), HSSFShape.LINESTYLE__COLOR_DEFAULT);
assertEquals(picture.isNoFill(), false); assertFalse(picture.isNoFill());
assertEquals(picture.getPictureIndex(), -1);//not set yet assertEquals(picture.getPictureIndex(), -1);//not set yet
} }
/** /**
* No NullPointerException should appear * No NullPointerException should appear
*/ */
@Test
public void testDefaultSettingsWithEmptyContainer() { public void testDefaultSettingsWithEmptyContainer() {
EscherContainerRecord container = new EscherContainerRecord(); EscherContainerRecord container = new EscherContainerRecord();
EscherOptRecord opt = new EscherOptRecord(); EscherOptRecord opt = new EscherOptRecord();
@ -142,10 +159,10 @@ public class TestDrawingShapes extends TestCase {
/** /**
* create a rectangle, save the workbook, read back and verify that all shape properties are there * create a rectangle, save the workbook, read back and verify that all shape properties are there
*/ */
@Test
public void testReadWriteRectangle() throws IOException { public void testReadWriteRectangle() throws IOException {
HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb1.createSheet();
HSSFSheet sheet = wb.createSheet();
HSSFPatriarch drawing = sheet.createDrawingPatriarch(); HSSFPatriarch drawing = sheet.createDrawingPatriarch();
HSSFClientAnchor anchor = new HSSFClientAnchor(10, 10, 50, 50, (short) 2, 2, (short) 4, 4); HSSFClientAnchor anchor = new HSSFClientAnchor(10, 10, 50, 50, (short) 2, 2, (short) 4, 4);
@ -172,8 +189,9 @@ public class TestDrawingShapes extends TestCase {
assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_NONE); assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_NONE);
assertEquals(rectangle.getString().getString(), "teeeest"); assertEquals(rectangle.getString().getString(), "teeeest");
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
drawing = sheet.getDrawingPatriarch(); drawing = sheet.getDrawingPatriarch();
assertEquals(1, drawing.getChildren().size()); assertEquals(1, drawing.getChildren().size());
@ -202,8 +220,9 @@ public class TestDrawingShapes extends TestCase {
rectangle.setWrapText(HSSFSimpleShape.WRAP_BY_POINTS); rectangle.setWrapText(HSSFSimpleShape.WRAP_BY_POINTS);
rectangle2.setString(new HSSFRichTextString("test22")); rectangle2.setString(new HSSFRichTextString("test22"));
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
sheet = wb.getSheetAt(0); wb2.close();
sheet = wb3.getSheetAt(0);
drawing = sheet.getDrawingPatriarch(); drawing = sheet.getDrawingPatriarch();
assertEquals(1, drawing.getChildren().size()); assertEquals(1, drawing.getChildren().size());
rectangle2 = (HSSFSimpleShape) drawing.getChildren().get(0); rectangle2 = (HSSFSimpleShape) drawing.getChildren().get(0);
@ -222,13 +241,16 @@ public class TestDrawingShapes extends TestCase {
HSSFSimpleShape rect3 = drawing.createSimpleShape(new HSSFClientAnchor()); HSSFSimpleShape rect3 = drawing.createSimpleShape(new HSSFClientAnchor());
rect3.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); rect3.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3);
wb3.close();
drawing = wb.getSheetAt(0).getDrawingPatriarch(); drawing = wb4.getSheetAt(0).getDrawingPatriarch();
assertEquals(drawing.getChildren().size(), 2); assertEquals(drawing.getChildren().size(), 2);
wb4.close();
} }
public void testReadExistingImage() { @Test
public void testReadExistingImage() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls");
HSSFSheet sheet = wb.getSheet("pictures"); HSSFSheet sheet = wb.getSheet("pictures");
HSSFPatriarch drawing = sheet.getDrawingPatriarch(); HSSFPatriarch drawing = sheet.getDrawingPatriarch();
@ -244,11 +266,13 @@ public class TestDrawingShapes extends TestCase {
picture.setPictureIndex(2); picture.setPictureIndex(2);
assertEquals(picture.getPictureIndex(), 2); assertEquals(picture.getPictureIndex(), 2);
wb.close();
} }
/* assert shape properties when reading shapes from a existing workbook */ /* assert shape properties when reading shapes from a existing workbook */
public void testReadExistingRectangle() { @Test
public void testReadExistingRectangle() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls");
HSSFSheet sheet = wb.getSheet("rectangles"); HSSFSheet sheet = wb.getSheet("rectangles");
HSSFPatriarch drawing = sheet.getDrawingPatriarch(); HSSFPatriarch drawing = sheet.getDrawingPatriarch();
@ -262,18 +286,21 @@ public class TestDrawingShapes extends TestCase {
assertEquals(shape.getLineWidth(), HSSFShape.LINEWIDTH_ONE_PT * 2); assertEquals(shape.getLineWidth(), HSSFShape.LINEWIDTH_ONE_PT * 2);
assertEquals(shape.getString().getString(), "POItest"); assertEquals(shape.getString().getString(), "POItest");
assertEquals(shape.getRotationDegree(), 27); assertEquals(shape.getRotationDegree(), 27);
wb.close();
} }
public void testShapeIds() { @Test
HSSFWorkbook wb = new HSSFWorkbook(); public void testShapeIds() throws IOException {
HSSFSheet sheet1 = wb.createSheet(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet sheet1 = wb1.createSheet();
HSSFPatriarch patriarch1 = sheet1.createDrawingPatriarch(); HSSFPatriarch patriarch1 = sheet1.createDrawingPatriarch();
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
patriarch1.createSimpleShape(new HSSFClientAnchor()); patriarch1.createSimpleShape(new HSSFClientAnchor());
} }
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
sheet1 = wb.getSheetAt(0); wb1.close();
sheet1 = wb2.getSheetAt(0);
patriarch1 = sheet1.getDrawingPatriarch(); patriarch1 = sheet1.getDrawingPatriarch();
EscherAggregate agg1 = HSSFTestHelper.getEscherAggregate(patriarch1); EscherAggregate agg1 = HSSFTestHelper.getEscherAggregate(patriarch1);
@ -299,13 +326,15 @@ public class TestDrawingShapes extends TestCase {
EscherSpRecord sp2 = EscherSpRecord sp2 =
((EscherContainerRecord) spgrContainer.getChild(2)).getChildById(EscherSpRecord.RECORD_ID); ((EscherContainerRecord) spgrContainer.getChild(2)).getChildById(EscherSpRecord.RECORD_ID);
assertEquals(1026, sp2.getShapeId()); assertEquals(1026, sp2.getShapeId());
wb2.close();
} }
/** /**
* Test get new id for shapes from existing file * Test get new id for shapes from existing file
* File already have for 1 shape on each sheet, because document must contain EscherDgRecord for each sheet * File already have for 1 shape on each sheet, because document must contain EscherDgRecord for each sheet
*/ */
public void testAllocateNewIds() { @Test
public void testAllocateNewIds() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("empty.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("empty.xls");
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);
HSSFPatriarch patriarch = sheet.getDrawingPatriarch(); HSSFPatriarch patriarch = sheet.getDrawingPatriarch();
@ -336,12 +365,13 @@ public class TestDrawingShapes extends TestCase {
assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1026); assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1026);
assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1027); assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1027);
assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1028); assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1028);
wb.close();
} }
public void testOpt() throws Exception { @Test
public void testOpt() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
try {
// create a sheet with a text box // create a sheet with a text box
HSSFSheet sheet = wb.createSheet(); HSSFSheet sheet = wb.createSheet();
HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
@ -350,15 +380,13 @@ public class TestDrawingShapes extends TestCase {
EscherOptRecord opt1 = HSSFTestHelper.getOptRecord(textbox); EscherOptRecord opt1 = HSSFTestHelper.getOptRecord(textbox);
EscherOptRecord opt2 = HSSFTestHelper.getEscherContainer(textbox).getChildById(EscherOptRecord.RECORD_ID); EscherOptRecord opt2 = HSSFTestHelper.getEscherContainer(textbox).getChildById(EscherOptRecord.RECORD_ID);
assertSame(opt1, opt2); assertSame(opt1, opt2);
} finally {
wb.close(); wb.close();
} }
}
@Test
public void testCorrectOrderInOptRecord() throws IOException{ public void testCorrectOrderInOptRecord() throws IOException{
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
try {
HSSFSheet sheet = wb.createSheet(); HSSFSheet sheet = wb.createSheet();
HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
@ -377,28 +405,25 @@ public class TestDrawingShapes extends TestCase {
assertEquals(opt1Str, optRecord.toXml()); assertEquals(opt1Str, optRecord.toXml());
textbox.setLineStyleColor(textbox.getLineStyleColor()); textbox.setLineStyleColor(textbox.getLineStyleColor());
assertEquals(opt1Str, optRecord.toXml()); assertEquals(opt1Str, optRecord.toXml());
} finally {
wb.close(); wb.close();
} }
}
@Test
public void testDgRecordNumShapes() throws IOException { public void testDgRecordNumShapes() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
try {
HSSFSheet sheet = wb.createSheet(); HSSFSheet sheet = wb.createSheet();
HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
EscherAggregate aggregate = HSSFTestHelper.getEscherAggregate(patriarch); EscherAggregate aggregate = HSSFTestHelper.getEscherAggregate(patriarch);
EscherDgRecord dgRecord = (EscherDgRecord) aggregate.getEscherRecord(0).getChild(0); EscherDgRecord dgRecord = (EscherDgRecord) aggregate.getEscherRecord(0).getChild(0);
assertEquals(dgRecord.getNumShapes(), 1); assertEquals(dgRecord.getNumShapes(), 1);
} finally {
wb.close(); wb.close();
} }
}
public void testTextForSimpleShape(){ @Test
HSSFWorkbook wb = new HSSFWorkbook(); public void testTextForSimpleShape() throws IOException {
HSSFSheet sheet = wb.createSheet(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet sheet = wb1.createSheet();
HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
HSSFSimpleShape shape = patriarch.createSimpleShape(new HSSFClientAnchor()); HSSFSimpleShape shape = patriarch.createSimpleShape(new HSSFClientAnchor());
@ -407,8 +432,9 @@ public class TestDrawingShapes extends TestCase {
EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch); EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch);
assertEquals(agg.getShapeToObjMapping().size(), 2); assertEquals(agg.getShapeToObjMapping().size(), 2);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
shape = (HSSFSimpleShape) patriarch.getChildren().get(0); shape = (HSSFSimpleShape) patriarch.getChildren().get(0);
@ -422,10 +448,12 @@ public class TestDrawingShapes extends TestCase {
assertNotNull(HSSFTestHelper.getEscherContainer(shape).getChildById(EscherTextboxRecord.RECORD_ID)); assertNotNull(HSSFTestHelper.getEscherContainer(shape).getChildById(EscherTextboxRecord.RECORD_ID));
assertEquals(agg.getShapeToObjMapping().size(), 2); assertEquals(agg.getShapeToObjMapping().size(), 2);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
wb2.close();
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3);
sheet = wb.getSheetAt(0); wb3.close();
sheet = wb4.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
shape = (HSSFSimpleShape) patriarch.getChildren().get(0); shape = (HSSFSimpleShape) patriarch.getChildren().get(0);
@ -434,17 +462,19 @@ public class TestDrawingShapes extends TestCase {
assertEquals(shape.getString().getString(), "string1"); assertEquals(shape.getString().getString(), "string1");
assertNotNull(HSSFTestHelper.getEscherContainer(shape).getChildById(EscherTextboxRecord.RECORD_ID)); assertNotNull(HSSFTestHelper.getEscherContainer(shape).getChildById(EscherTextboxRecord.RECORD_ID));
assertEquals(agg.getShapeToObjMapping().size(), 2); assertEquals(agg.getShapeToObjMapping().size(), 2);
wb4.close();
} }
public void testRemoveShapes(){ @Test
HSSFWorkbook wb = new HSSFWorkbook(); public void testRemoveShapes() throws IOException {
HSSFSheet sheet = wb.createSheet(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet sheet = wb1.createSheet();
HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor()); HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor());
rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE);
int idx = wb.addPicture(new byte[]{1,2,3}, Workbook.PICTURE_TYPE_JPEG); int idx = wb1.addPicture(new byte[]{1,2,3}, Workbook.PICTURE_TYPE_JPEG);
patriarch.createPicture(new HSSFClientAnchor(), idx); patriarch.createPicture(new HSSFClientAnchor(), idx);
patriarch.createCellComment(new HSSFClientAnchor()); patriarch.createCellComment(new HSSFClientAnchor());
@ -464,8 +494,9 @@ public class TestDrawingShapes extends TestCase {
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12);
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12);
@ -479,8 +510,9 @@ public class TestDrawingShapes extends TestCase {
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10);
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
sheet = wb.getSheetAt(0); wb2.close();
sheet = wb3.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10);
@ -492,8 +524,9 @@ public class TestDrawingShapes extends TestCase {
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8);
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3);
sheet = wb.getSheetAt(0); wb3.close();
sheet = wb4.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8);
@ -507,8 +540,9 @@ public class TestDrawingShapes extends TestCase {
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
assertEquals(patriarch.getChildren().size(), 4); assertEquals(patriarch.getChildren().size(), 4);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb5 = HSSFTestDataSamples.writeOutAndReadBack(wb4);
sheet = wb.getSheetAt(0); wb4.close();
sheet = wb5.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6);
@ -522,8 +556,9 @@ public class TestDrawingShapes extends TestCase {
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
assertEquals(patriarch.getChildren().size(), 3); assertEquals(patriarch.getChildren().size(), 3);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb6 = HSSFTestDataSamples.writeOutAndReadBack(wb5);
sheet = wb.getSheetAt(0); wb5.close();
sheet = wb6.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5);
@ -537,8 +572,9 @@ public class TestDrawingShapes extends TestCase {
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
assertEquals(patriarch.getChildren().size(), 2); assertEquals(patriarch.getChildren().size(), 2);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb7 = HSSFTestDataSamples.writeOutAndReadBack(wb6);
sheet = wb.getSheetAt(0); wb6.close();
sheet = wb7.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3);
@ -552,8 +588,9 @@ public class TestDrawingShapes extends TestCase {
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
assertEquals(patriarch.getChildren().size(), 1); assertEquals(patriarch.getChildren().size(), 1);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb8 = HSSFTestDataSamples.writeOutAndReadBack(wb7);
sheet = wb.getSheetAt(0); wb7.close();
sheet = wb8.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2);
@ -567,18 +604,21 @@ public class TestDrawingShapes extends TestCase {
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
assertEquals(patriarch.getChildren().size(), 0); assertEquals(patriarch.getChildren().size(), 0);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb9 = HSSFTestDataSamples.writeOutAndReadBack(wb8);
sheet = wb.getSheetAt(0); wb8.close();
sheet = wb9.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0);
assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
assertEquals(patriarch.getChildren().size(), 0); assertEquals(patriarch.getChildren().size(), 0);
wb9.close();
} }
public void testShapeFlip(){ @Test
HSSFWorkbook wb = new HSSFWorkbook(); public void testShapeFlip() throws IOException {
HSSFSheet sheet = wb.createSheet(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet sheet = wb1.createSheet();
HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor()); HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor());
@ -592,8 +632,9 @@ public class TestDrawingShapes extends TestCase {
rectangle.setFlipHorizontal(true); rectangle.setFlipHorizontal(true);
assertEquals(rectangle.isFlipHorizontal(), true); assertEquals(rectangle.isFlipHorizontal(), true);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0); rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0);
@ -606,19 +647,22 @@ public class TestDrawingShapes extends TestCase {
rectangle.setFlipVertical(false); rectangle.setFlipVertical(false);
assertEquals(rectangle.isFlipVertical(), false); assertEquals(rectangle.isFlipVertical(), false);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
sheet = wb.getSheetAt(0); wb2.close();
sheet = wb3.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0); rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0);
assertEquals(rectangle.isFlipVertical(), false); assertEquals(rectangle.isFlipVertical(), false);
assertEquals(rectangle.isFlipHorizontal(), false); assertEquals(rectangle.isFlipHorizontal(), false);
wb3.close();
} }
public void testRotation() { @Test
HSSFWorkbook wb = new HSSFWorkbook(); public void testRotation() throws IOException {
HSSFSheet sheet = wb.createSheet(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet sheet = wb1.createSheet();
HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor(0,0,100,100, (short) 0,0,(short)5,5)); HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor(0,0,100,100, (short) 0,0,(short)5,5));
@ -629,8 +673,9 @@ public class TestDrawingShapes extends TestCase {
assertEquals(rectangle.getRotationDegree(), 45); assertEquals(rectangle.getRotationDegree(), 45);
rectangle.setFlipHorizontal(true); rectangle.setFlipHorizontal(true);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0); rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0);
assertEquals(rectangle.getRotationDegree(), 45); assertEquals(rectangle.getRotationDegree(), 45);
@ -639,12 +684,14 @@ public class TestDrawingShapes extends TestCase {
patriarch.setCoordinates(0, 0, 10, 10); patriarch.setCoordinates(0, 0, 10, 10);
rectangle.setString(new HSSFRichTextString("1234")); rectangle.setString(new HSSFRichTextString("1234"));
wb2.close();
} }
@SuppressWarnings("unused")
@Test
public void testShapeContainerImplementsIterable() throws IOException { public void testShapeContainerImplementsIterable() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
try {
HSSFSheet sheet = wb.createSheet(); HSSFSheet sheet = wb.createSheet();
HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
@ -657,14 +704,13 @@ public class TestDrawingShapes extends TestCase {
i--; i--;
} }
assertEquals(i, 0); assertEquals(i, 0);
} finally {
wb.close(); wb.close();
} }
}
public void testClearShapesForPatriarch(){ @Test
HSSFWorkbook wb = new HSSFWorkbook(); public void testClearShapesForPatriarch() throws IOException {
HSSFSheet sheet = wb.createSheet(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet sheet = wb1.createSheet();
HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
patriarch.createSimpleShape(new HSSFClientAnchor()); patriarch.createSimpleShape(new HSSFClientAnchor());
@ -683,15 +729,18 @@ public class TestDrawingShapes extends TestCase {
assertEquals(agg.getTailRecords().size(), 0); assertEquals(agg.getTailRecords().size(), 0);
assertEquals(patriarch.getChildren().size(), 0); assertEquals(patriarch.getChildren().size(), 0);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
patriarch = sheet.getDrawingPatriarch(); patriarch = sheet.getDrawingPatriarch();
assertEquals(agg.getShapeToObjMapping().size(), 0); assertEquals(agg.getShapeToObjMapping().size(), 0);
assertEquals(agg.getTailRecords().size(), 0); assertEquals(agg.getTailRecords().size(), 0);
assertEquals(patriarch.getChildren().size(), 0); assertEquals(patriarch.getChildren().size(), 0);
wb2.close();
} }
@Test
public void testBug45312() throws Exception { public void testBug45312() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
try { try {
@ -739,7 +788,7 @@ public class TestDrawingShapes extends TestCase {
} }
} }
private void checkWorkbookBack(HSSFWorkbook wb) { private void checkWorkbookBack(HSSFWorkbook wb) throws IOException {
HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
assertNotNull(wbBack); assertNotNull(wbBack);
@ -806,5 +855,7 @@ public class TestDrawingShapes extends TestCase {
assertEquals(2, cAnchor.getCol2()); assertEquals(2, cAnchor.getCol2());
assertEquals(2, cAnchor.getRow1()); assertEquals(2, cAnchor.getRow1());
assertEquals(2, cAnchor.getRow2()); assertEquals(2, cAnchor.getRow2());
wbBack.close();
} }
} }

View File

@ -62,7 +62,7 @@ public final class TestHSSFCell extends BaseTestCell {
* but there's a separate unit test for that. * but there's a separate unit test for that.
*/ */
@Test @Test
public void testDateWindowingRead() throws Exception { public void testDateWindowingRead() throws IOException {
Calendar cal = LocaleUtil.getLocaleCalendar(2000, 0, 1, 0, 0, 0);// Jan. 1, 2000 Calendar cal = LocaleUtil.getLocaleCalendar(2000, 0, 1, 0, 0, 0);// Jan. 1, 2000
Date date = cal.getTime(); Date date = cal.getTime();
@ -94,7 +94,7 @@ public final class TestHSSFCell extends BaseTestCell {
* results of this test are meaningless. * results of this test are meaningless.
*/ */
@Test @Test
public void testDateWindowingWrite() throws Exception { public void testDateWindowingWrite() throws IOException {
Calendar cal = LocaleUtil.getLocaleCalendar(2000,0,1,0,0,0); // Jan. 1, 2000 Calendar cal = LocaleUtil.getLocaleCalendar(2000,0,1,0,0,0); // Jan. 1, 2000
Date date = cal.getTime(); Date date = cal.getTime();
@ -143,7 +143,7 @@ public final class TestHSSFCell extends BaseTestCell {
* Tests that the active cell can be correctly read and set * Tests that the active cell can be correctly read and set
*/ */
@Test @Test
public void testActiveCell() throws Exception { public void testActiveCell() throws IOException {
//read in sample //read in sample
HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls"); HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls");
@ -235,7 +235,7 @@ public final class TestHSSFCell extends BaseTestCell {
* Test reading hyperlinks * Test reading hyperlinks
*/ */
@Test @Test
public void testWithHyperlink() throws Exception { public void testWithHyperlink() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithHyperlink.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithHyperlink.xls");
@ -256,7 +256,7 @@ public final class TestHSSFCell extends BaseTestCell {
* Test reading hyperlinks * Test reading hyperlinks
*/ */
@Test @Test
public void testWithTwoHyperlinks() throws Exception { public void testWithTwoHyperlinks() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithTwoHyperLinks.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithTwoHyperLinks.xls");
@ -286,7 +286,7 @@ public final class TestHSSFCell extends BaseTestCell {
* to our workbook, and not those from other workbooks. * to our workbook, and not those from other workbooks.
*/ */
@Test @Test
public void testCellStyleWorkbookMatch() throws Exception { public void testCellStyleWorkbookMatch() throws IOException {
HSSFWorkbook wbA = new HSSFWorkbook(); HSSFWorkbook wbA = new HSSFWorkbook();
HSSFWorkbook wbB = new HSSFWorkbook(); HSSFWorkbook wbB = new HSSFWorkbook();
@ -386,14 +386,14 @@ public final class TestHSSFCell extends BaseTestCell {
* HSSF prior to version 3.7 had a bug: it could write a NaN but could not read such a file back. * HSSF prior to version 3.7 had a bug: it could write a NaN but could not read such a file back.
*/ */
@Test @Test
public void testReadNaN() throws Exception { public void testReadNaN() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49761.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49761.xls");
assertNotNull(wb); assertNotNull(wb);
wb.close(); wb.close();
} }
@Test @Test
public void testHSSFCell() throws Exception { public void testHSSFCell() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(); HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow(0); HSSFRow row = sheet.createRow(0);
@ -403,9 +403,8 @@ public final class TestHSSFCell extends BaseTestCell {
wb.close(); wb.close();
} }
@SuppressWarnings("deprecation")
@Test @Test
public void testDeprecatedMethods() throws Exception { public void testDeprecatedMethods() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(); HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow(0); HSSFRow row = sheet.createRow(0);

View File

@ -24,13 +24,7 @@ import org.apache.poi.ss.formula.BaseTestExternalFunctions;
* Tests setting and evaluating user-defined functions in HSSF * Tests setting and evaluating user-defined functions in HSSF
*/ */
public final class TestHSSFExternalFunctions extends BaseTestExternalFunctions { public final class TestHSSFExternalFunctions extends BaseTestExternalFunctions {
public TestHSSFExternalFunctions() { public TestHSSFExternalFunctions() {
super(HSSFITestDataProvider.instance); super(HSSFITestDataProvider.instance, "atp.xls");
} }
public void testATP(){
baseTestInvokeATP("atp.xls");
}
} }

View File

@ -20,9 +20,6 @@ package org.apache.poi.hssf.usermodel;
import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.ss.usermodel.BaseTestSheetHiding; import org.apache.poi.ss.usermodel.BaseTestSheetHiding;
/**
* @author Yegor Kozlov
*/
public final class TestSheetHiding extends BaseTestSheetHiding { public final class TestSheetHiding extends BaseTestSheetHiding {
public TestSheetHiding() { public TestSheetHiding() {
super(HSSFITestDataProvider.instance, super(HSSFITestDataProvider.instance,

View File

@ -16,7 +16,10 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.ss.formula; package org.apache.poi.ss.formula;
import junit.framework.TestCase; import static org.junit.Assert.*;
import java.io.IOException;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.formula.eval.NotImplementedException; import org.apache.poi.ss.formula.eval.NotImplementedException;
@ -30,13 +33,12 @@ import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.junit.Test;
/** /**
* Test setting / evaluating of Analysis Toolpack and user-defined functions * Test setting / evaluating of Analysis Toolpack and user-defined functions
*
* @author Yegor Kozlov
*/ */
public class BaseTestExternalFunctions extends TestCase { public class BaseTestExternalFunctions {
// define two custom user-defined functions // define two custom user-defined functions
private static class MyFunc implements FreeRefFunction { private static class MyFunc implements FreeRefFunction {
public MyFunc() { public MyFunc() {
@ -75,34 +77,37 @@ public class BaseTestExternalFunctions extends TestCase {
); );
protected final ITestDataProvider _testDataProvider; private final ITestDataProvider _testDataProvider;
private final String atpFile;
/** /**
* @param testDataProvider an object that provides test data in HSSF / XSSF specific way * @param testDataProvider an object that provides test data in HSSF / XSSF specific way
*/ */
protected BaseTestExternalFunctions(ITestDataProvider testDataProvider) { protected BaseTestExternalFunctions(ITestDataProvider testDataProvider, String atpFile) {
_testDataProvider = testDataProvider; _testDataProvider = testDataProvider;
this.atpFile = atpFile;
} }
public void testExternalFunctions() { @Test
public void testExternalFunctions() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Sheet sh = wb.createSheet(); Sheet sh = wb.createSheet();
Cell cell1 = sh.createRow(0).createCell(0); Cell cell1 = sh.createRow(0).createCell(0);
cell1.setCellFormula("ISODD(1)+ISEVEN(2)"); // functions from the Excel Analysis Toolpack // functions from the Excel Analysis Toolpack
cell1.setCellFormula("ISODD(1)+ISEVEN(2)");
assertEquals("ISODD(1)+ISEVEN(2)", cell1.getCellFormula()); assertEquals("ISODD(1)+ISEVEN(2)", cell1.getCellFormula());
Cell cell2 = sh.createRow(1).createCell(0); Cell cell2 = sh.createRow(1).createCell(0);
cell2.setCellFormula("MYFUNC(\"B1\")"); //unregistered functions are parseable and renderable, but may not be evaluateable // unregistered functions are parseable and renderable, but may not be evaluateable
cell2.setCellFormula("MYFUNC(\"B1\")");
try { try {
evaluator.evaluate(cell2); evaluator.evaluate(cell2);
fail("Expected NotImplementedFunctionException/NotImplementedException"); fail("Expected NotImplementedFunctionException/NotImplementedException");
} catch (final NotImplementedException e) { } catch (final NotImplementedException e) {
if (!(e.getCause() instanceof NotImplementedFunctionException)) assertTrue(e.getCause() instanceof NotImplementedFunctionException);
throw e;
// expected
// Alternatively, a future implementation of evaluate could return #NAME? error to align behavior with Excel // Alternatively, a future implementation of evaluate could return #NAME? error to align behavior with Excel
// assertEquals(ErrorEval.NAME_INVALID, ErrorEval.valueOf(evaluator.evaluate(cell2).getErrorValue())); // assertEquals(ErrorEval.NAME_INVALID, ErrorEval.valueOf(evaluator.evaluate(cell2).getErrorValue()));
} }
@ -116,10 +121,11 @@ public class BaseTestExternalFunctions extends TestCase {
cell3.setCellFormula("MYFUNC2(\"C1\")&\"-\"&A2"); //where A2 is defined above cell3.setCellFormula("MYFUNC2(\"C1\")&\"-\"&A2"); //where A2 is defined above
assertEquals("MYFUNC2(\"C1\")&\"-\"&A2", cell3.getCellFormula()); assertEquals("MYFUNC2(\"C1\")&\"-\"&A2", cell3.getCellFormula());
assertEquals(2.0, evaluator.evaluate(cell1).getNumberValue()); assertEquals(2.0, evaluator.evaluate(cell1).getNumberValue(), 0);
assertEquals("B1abc", evaluator.evaluate(cell2).getStringValue()); assertEquals("B1abc", evaluator.evaluate(cell2).getStringValue());
assertEquals("C1abc2-B1abc", evaluator.evaluate(cell3).getStringValue()); assertEquals("C1abc2-B1abc", evaluator.evaluate(cell3).getStringValue());
wb.close();
} }
/** /**
@ -127,12 +133,13 @@ public class BaseTestExternalFunctions extends TestCase {
* *
* @param testFile either atp.xls or atp.xlsx * @param testFile either atp.xls or atp.xlsx
*/ */
public void baseTestInvokeATP(String testFile){ @Test
Workbook wb = _testDataProvider.openSampleWorkbook(testFile); public void baseTestInvokeATP() throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook(atpFile);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Sheet sh = wb.getSheetAt(0); Sheet sh = wb.getSheetAt(0);
// these two are not imlemented in r // these two are not implemented in r
assertEquals("DELTA(1.3,1.5)", sh.getRow(0).getCell(1).getCellFormula()); assertEquals("DELTA(1.3,1.5)", sh.getRow(0).getCell(1).getCellFormula());
assertEquals("COMPLEX(2,4)", sh.getRow(1).getCell(1).getCellFormula()); assertEquals("COMPLEX(2,4)", sh.getRow(1).getCell(1).getCellFormula());
@ -146,6 +153,7 @@ public class BaseTestExternalFunctions extends TestCase {
assertEquals(true, evaluator.evaluate(cell3).getBooleanValue()); assertEquals(true, evaluator.evaluate(cell3).getBooleanValue());
assertEquals(Cell.CELL_TYPE_BOOLEAN, evaluator.evaluateFormulaCell(cell3)); assertEquals(Cell.CELL_TYPE_BOOLEAN, evaluator.evaluateFormulaCell(cell3));
wb.close();
} }
} }

View File

@ -17,6 +17,7 @@
package org.apache.poi.ss.usermodel; package org.apache.poi.ss.usermodel;
import static org.apache.poi.ss.usermodel.FormulaError.forInt;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
@ -25,38 +26,22 @@ import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.LocaleUtil;
import org.junit.After;
import org.junit.Test; import org.junit.Test;
import junit.framework.AssertionFailedError;
/** /**
* Common superclass for testing implementations of * Common superclass for testing implementations of
* {@link org.apache.poi.ss.usermodel.Cell} * {@link org.apache.poi.ss.usermodel.Cell}
*/ */
@SuppressWarnings("deprecation")
public abstract class BaseTestCell { public abstract class BaseTestCell {
protected final ITestDataProvider _testDataProvider; protected final ITestDataProvider _testDataProvider;
private List<Workbook> workbooksToClose = new ArrayList<Workbook>();
@After
public void tearDown() throws IOException {
// free resources correctly
for(Workbook wb : workbooksToClose) {
wb.close();
}
}
/** /**
* @param testDataProvider an object that provides test data in HSSF / XSSF specific way * @param testDataProvider an object that provides test data in HSSF / XSSF specific way
*/ */
@ -307,7 +292,7 @@ public abstract class BaseTestCell {
r.createCell(0).setCellValue(true); r.createCell(0).setCellValue(true);
r.createCell(1).setCellValue(1.5); r.createCell(1).setCellValue(1.5);
r.createCell(2).setCellValue(factory.createRichTextString("Astring")); r.createCell(2).setCellValue(factory.createRichTextString("Astring"));
r.createCell(3).setCellErrorValue((byte)ErrorConstants.ERROR_DIV_0); r.createCell(3).setCellErrorValue(FormulaError.DIV0.getCode());
r.createCell(4).setCellFormula("A1+B1"); r.createCell(4).setCellFormula("A1+B1");
assertEquals("Boolean", "TRUE", r.getCell(0).toString()); assertEquals("Boolean", "TRUE", r.getCell(0).toString());
@ -364,9 +349,7 @@ public abstract class BaseTestCell {
} }
private Cell createACell() { private Cell createACell(Workbook wb) {
Workbook wb = _testDataProvider.createWorkbook();
workbooksToClose.add(wb);
return wb.createSheet("Sheet1").createRow(0).createCell(0); return wb.createSheet("Sheet1").createRow(0).createCell(0);
} }
@ -410,17 +393,15 @@ public abstract class BaseTestCell {
} }
@Test @Test
public void testChangeTypeStringToBool() { public void testChangeTypeStringToBool() throws IOException {
Cell cell = createACell(); Workbook wb = _testDataProvider.createWorkbook();
Cell cell = createACell(wb);
cell.setCellValue("TRUE"); cell.setCellValue("TRUE");
assertEquals(Cell.CELL_TYPE_STRING, cell.getCellType()); assertEquals(Cell.CELL_TYPE_STRING, cell.getCellType());
try { // test conversion of cell from text to boolean
cell.setCellType(Cell.CELL_TYPE_BOOLEAN); cell.setCellType(Cell.CELL_TYPE_BOOLEAN);
} catch (ClassCastException e) {
throw new AssertionFailedError(
"Identified bug in conversion of cell from text to boolean");
}
assertEquals(Cell.CELL_TYPE_BOOLEAN, cell.getCellType()); assertEquals(Cell.CELL_TYPE_BOOLEAN, cell.getCellType());
assertEquals(true, cell.getBooleanCellValue()); assertEquals(true, cell.getBooleanCellValue());
@ -434,52 +415,51 @@ public abstract class BaseTestCell {
assertEquals(false, cell.getBooleanCellValue()); assertEquals(false, cell.getBooleanCellValue());
cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellType(Cell.CELL_TYPE_STRING);
assertEquals("FALSE", cell.getRichStringCellValue().getString()); assertEquals("FALSE", cell.getRichStringCellValue().getString());
wb.close();
} }
@Test @Test
public void testChangeTypeBoolToString() { public void testChangeTypeBoolToString() throws IOException {
Cell cell = createACell(); Workbook wb = _testDataProvider.createWorkbook();
Cell cell = createACell(wb);
cell.setCellValue(true); cell.setCellValue(true);
try { // test conversion of cell from boolean to text
cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellType(Cell.CELL_TYPE_STRING);
} catch (IllegalStateException e) {
if (e.getMessage().equals("Cannot get a text value from a boolean cell")) {
throw new AssertionFailedError(
"Identified bug in conversion of cell from boolean to text");
}
throw e;
}
assertEquals("TRUE", cell.getRichStringCellValue().getString()); assertEquals("TRUE", cell.getRichStringCellValue().getString());
wb.close();
} }
@Test @Test
public void testChangeTypeErrorToNumber() { public void testChangeTypeErrorToNumber() throws IOException {
Cell cell = createACell(); Workbook wb = _testDataProvider.createWorkbook();
cell.setCellErrorValue((byte)ErrorConstants.ERROR_NAME);
Cell cell = createACell(wb);
cell.setCellErrorValue(FormulaError.NAME.getCode());
try { try {
cell.setCellValue(2.5); cell.setCellValue(2.5);
} catch (ClassCastException e) { } catch (ClassCastException e) {
throw new AssertionFailedError("Identified bug 46479b"); fail("Identified bug 46479b");
} }
assertEquals(2.5, cell.getNumericCellValue(), 0.0); assertEquals(2.5, cell.getNumericCellValue(), 0.0);
wb.close();
} }
@Test @Test
public void testChangeTypeErrorToBoolean() { public void testChangeTypeErrorToBoolean() throws IOException {
Cell cell = createACell(); Workbook wb = _testDataProvider.createWorkbook();
cell.setCellErrorValue((byte)ErrorConstants.ERROR_NAME);
cell.setCellValue(true);
try {
cell.getBooleanCellValue();
} catch (IllegalStateException e) {
if (e.getMessage().equals("Cannot get a boolean value from a error cell")) {
throw new AssertionFailedError("Identified bug 46479c"); Cell cell = createACell(wb);
} cell.setCellErrorValue(FormulaError.NAME.getCode());
throw e; cell.setCellValue(true);
} // Identify bug 46479c
assertEquals(true, cell.getBooleanCellValue()); assertEquals(true, cell.getBooleanCellValue());
wb.close();
} }
/** /**
@ -488,8 +468,10 @@ public abstract class BaseTestCell {
* string result type. * string result type.
*/ */
@Test @Test
public void testConvertStringFormulaCell() { public void testConvertStringFormulaCell() throws IOException {
Cell cellA1 = createACell(); Workbook wb = _testDataProvider.createWorkbook();
Cell cellA1 = createACell(wb);
cellA1.setCellFormula("\"abc\""); cellA1.setCellFormula("\"abc\"");
// default cached formula result is numeric zero // default cached formula result is numeric zero
@ -501,10 +483,10 @@ public abstract class BaseTestCell {
assertEquals("abc", cellA1.getStringCellValue()); assertEquals("abc", cellA1.getStringCellValue());
fe.evaluateInCell(cellA1); fe.evaluateInCell(cellA1);
if (cellA1.getStringCellValue().equals("")) { assertFalse("Identified bug with writing back formula result of type string", cellA1.getStringCellValue().equals(""));
throw new AssertionFailedError("Identified bug with writing back formula result of type string");
}
assertEquals("abc", cellA1.getStringCellValue()); assertEquals("abc", cellA1.getStringCellValue());
wb.close();
} }
/** /**
@ -512,8 +494,10 @@ public abstract class BaseTestCell {
* lower level that {#link {@link Cell#setCellType(int)} works properly * lower level that {#link {@link Cell#setCellType(int)} works properly
*/ */
@Test @Test
public void testSetTypeStringOnFormulaCell() { public void testSetTypeStringOnFormulaCell() throws IOException {
Cell cellA1 = createACell(); Workbook wb = _testDataProvider.createWorkbook();
Cell cellA1 = createACell(wb);
FormulaEvaluator fe = cellA1.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); FormulaEvaluator fe = cellA1.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
cellA1.setCellFormula("\"DEF\""); cellA1.setCellFormula("\"DEF\"");
@ -543,9 +527,11 @@ public abstract class BaseTestCell {
fe.clearAllCachedResultValues(); fe.clearAllCachedResultValues();
fe.evaluateFormulaCell(cellA1); fe.evaluateFormulaCell(cellA1);
confirmCannotReadString(cellA1); confirmCannotReadString(cellA1);
assertEquals(ErrorConstants.ERROR_NAME, cellA1.getErrorCellValue()); assertEquals(FormulaError.NAME, forInt(cellA1.getErrorCellValue()));
cellA1.setCellType(Cell.CELL_TYPE_STRING); cellA1.setCellType(Cell.CELL_TYPE_STRING);
assertEquals("#NAME?", cellA1.getStringCellValue()); assertEquals("#NAME?", cellA1.getStringCellValue());
wb.close();
} }
private static void confirmCannotReadString(Cell cell) { private static void confirmCannotReadString(Cell cell) {
@ -556,15 +542,17 @@ public abstract class BaseTestCell {
* Test for bug in convertCellValueToBoolean to make sure that formula results get converted * Test for bug in convertCellValueToBoolean to make sure that formula results get converted
*/ */
@Test @Test
public void testChangeTypeFormulaToBoolean() { public void testChangeTypeFormulaToBoolean() throws IOException {
Cell cell = createACell(); Workbook wb = _testDataProvider.createWorkbook();
Cell cell = createACell(wb);
cell.setCellFormula("1=1"); cell.setCellFormula("1=1");
cell.setCellValue(true); cell.setCellValue(true);
cell.setCellType(Cell.CELL_TYPE_BOOLEAN); cell.setCellType(Cell.CELL_TYPE_BOOLEAN);
if (cell.getBooleanCellValue() == false) { assertTrue("Identified bug 46479d", cell.getBooleanCellValue());
throw new AssertionFailedError("Identified bug 46479d");
}
assertEquals(true, cell.getBooleanCellValue()); assertEquals(true, cell.getBooleanCellValue());
wb.close();
} }
/** /**
@ -664,17 +652,17 @@ public abstract class BaseTestCell {
Cell cell0 = row.createCell(0); Cell cell0 = row.createCell(0);
cell0.setCellValue(Double.NaN); cell0.setCellValue(Double.NaN);
assertEquals("Double.NaN should change cell type to CELL_TYPE_ERROR", Cell.CELL_TYPE_ERROR, cell0.getCellType()); assertEquals("Double.NaN should change cell type to CELL_TYPE_ERROR", Cell.CELL_TYPE_ERROR, cell0.getCellType());
assertEquals("Double.NaN should change cell value to #NUM!", ErrorConstants.ERROR_NUM, cell0.getErrorCellValue()); assertEquals("Double.NaN should change cell value to #NUM!", FormulaError.NUM, forInt(cell0.getErrorCellValue()));
Cell cell1 = row.createCell(1); Cell cell1 = row.createCell(1);
cell1.setCellValue(Double.POSITIVE_INFINITY); cell1.setCellValue(Double.POSITIVE_INFINITY);
assertEquals("Double.POSITIVE_INFINITY should change cell type to CELL_TYPE_ERROR", Cell.CELL_TYPE_ERROR, cell1.getCellType()); assertEquals("Double.POSITIVE_INFINITY should change cell type to CELL_TYPE_ERROR", Cell.CELL_TYPE_ERROR, cell1.getCellType());
assertEquals("Double.POSITIVE_INFINITY should change cell value to #DIV/0!", ErrorConstants.ERROR_DIV_0, cell1.getErrorCellValue()); assertEquals("Double.POSITIVE_INFINITY should change cell value to #DIV/0!", FormulaError.DIV0, forInt(cell1.getErrorCellValue()));
Cell cell2 = row.createCell(2); Cell cell2 = row.createCell(2);
cell2.setCellValue(Double.NEGATIVE_INFINITY); cell2.setCellValue(Double.NEGATIVE_INFINITY);
assertEquals("Double.NEGATIVE_INFINITY should change cell type to CELL_TYPE_ERROR", Cell.CELL_TYPE_ERROR, cell2.getCellType()); assertEquals("Double.NEGATIVE_INFINITY should change cell type to CELL_TYPE_ERROR", Cell.CELL_TYPE_ERROR, cell2.getCellType());
assertEquals("Double.NEGATIVE_INFINITY should change cell value to #DIV/0!", ErrorConstants.ERROR_DIV_0, cell2.getErrorCellValue()); assertEquals("Double.NEGATIVE_INFINITY should change cell value to #DIV/0!", FormulaError.DIV0, forInt(cell2.getErrorCellValue()));
Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close(); wb1.close();
@ -682,15 +670,15 @@ public abstract class BaseTestCell {
cell0 = row.getCell(0); cell0 = row.getCell(0);
assertEquals(Cell.CELL_TYPE_ERROR, cell0.getCellType()); assertEquals(Cell.CELL_TYPE_ERROR, cell0.getCellType());
assertEquals(ErrorConstants.ERROR_NUM, cell0.getErrorCellValue()); assertEquals(FormulaError.NUM, forInt(cell0.getErrorCellValue()));
cell1 = row.getCell(1); cell1 = row.getCell(1);
assertEquals(Cell.CELL_TYPE_ERROR, cell1.getCellType()); assertEquals(Cell.CELL_TYPE_ERROR, cell1.getCellType());
assertEquals(ErrorConstants.ERROR_DIV_0, cell1.getErrorCellValue()); assertEquals(FormulaError.DIV0, forInt(cell1.getErrorCellValue()));
cell2 = row.getCell(2); cell2 = row.getCell(2);
assertEquals(Cell.CELL_TYPE_ERROR, cell2.getCellType()); assertEquals(Cell.CELL_TYPE_ERROR, cell2.getCellType());
assertEquals(ErrorConstants.ERROR_DIV_0, cell2.getErrorCellValue()); assertEquals(FormulaError.DIV0, forInt(cell2.getErrorCellValue()));
wb2.close(); wb2.close();
} }

View File

@ -24,13 +24,14 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.List;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference; import org.apache.poi.ss.util.CellReference;
import org.junit.Test; import org.junit.Test;
import java.util.List;
/** /**
* Tests of implementations of {@link org.apache.poi.ss.usermodel.Name}. * Tests of implementations of {@link org.apache.poi.ss.usermodel.Name}.
* *
@ -647,7 +648,7 @@ public abstract class BaseTestNamedRange {
} }
@Test @Test
public void testBug56930() { public void testBug56930() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
// x1 on sheet1 defines "x=1" // x1 on sheet1 defines "x=1"
@ -673,5 +674,7 @@ public abstract class BaseTestNamedRange {
assertEquals("1", wb.getName("x").getRefersToFormula()); assertEquals("1", wb.getName("x").getRefersToFormula());
wb.removeName("x"); wb.removeName("x");
assertEquals("2", wb.getName("x").getRefersToFormula()); assertEquals("2", wb.getName("x").getRefersToFormula());
wb.close();
} }
} }

View File

@ -17,9 +17,13 @@
package org.apache.poi.ss.usermodel; package org.apache.poi.ss.usermodel;
import static junit.framework.TestCase.assertNotNull; import static org.junit.Assert.assertEquals;
import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.*; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException; import java.io.IOException;
import java.util.Iterator; import java.util.Iterator;
@ -266,11 +270,11 @@ public abstract class BaseTestSheet {
} }
/** /**
* Dissallow creating wholly or partially overlapping merged regions * Disallow creating wholly or partially overlapping merged regions
* as this results in a corrupted workbook * as this results in a corrupted workbook
*/ */
@Test @Test
public void addOverlappingMergedRegions() { public void addOverlappingMergedRegions() throws IOException {
final Workbook wb = _testDataProvider.createWorkbook(); final Workbook wb = _testDataProvider.createWorkbook();
final Sheet sheet = wb.createSheet(); final Sheet sheet = wb.createSheet();
@ -282,14 +286,14 @@ public abstract class BaseTestSheet {
sheet.addMergedRegion(duplicateRegion); sheet.addMergedRegion(duplicateRegion);
fail("Should not be able to add a merged region (" + duplicateRegion.formatAsString() + ") " + fail("Should not be able to add a merged region (" + duplicateRegion.formatAsString() + ") " +
"if sheet already contains the same merged region (" + baseRegion.formatAsString() + ")"); "if sheet already contains the same merged region (" + baseRegion.formatAsString() + ")");
} catch (final IllegalStateException e) { } //expected } catch (final IllegalStateException e) { }
try { try {
final CellRangeAddress partiallyOverlappingRegion = new CellRangeAddress(1, 2, 1, 2); //B2:C3 final CellRangeAddress partiallyOverlappingRegion = new CellRangeAddress(1, 2, 1, 2); //B2:C3
sheet.addMergedRegion(partiallyOverlappingRegion); sheet.addMergedRegion(partiallyOverlappingRegion);
fail("Should not be able to add a merged region (" + partiallyOverlappingRegion.formatAsString() + ") " + fail("Should not be able to add a merged region (" + partiallyOverlappingRegion.formatAsString() + ") " +
"if it partially overlaps with an existing merged region (" + baseRegion.formatAsString() + ")"); "if it partially overlaps with an existing merged region (" + baseRegion.formatAsString() + ")");
} catch (final IllegalStateException e) { } //expected } catch (final IllegalStateException e) { }
try { try {
final CellRangeAddress subsetRegion = new CellRangeAddress(0, 1, 0, 0); //A1:A2 final CellRangeAddress subsetRegion = new CellRangeAddress(0, 1, 0, 0); //A1:A2
@ -303,10 +307,12 @@ public abstract class BaseTestSheet {
sheet.addMergedRegion(supersetRegion); sheet.addMergedRegion(supersetRegion);
fail("Should not be able to add a merged region (" + supersetRegion.formatAsString() + ") " + fail("Should not be able to add a merged region (" + supersetRegion.formatAsString() + ") " +
"if it is a formal superset of an existing merged region (" + baseRegion.formatAsString() + ")"); "if it is a formal superset of an existing merged region (" + baseRegion.formatAsString() + ")");
} catch (final IllegalStateException e) { } //expected } catch (final IllegalStateException e) { }
final CellRangeAddress disjointRegion = new CellRangeAddress(10, 11, 10, 11); final CellRangeAddress disjointRegion = new CellRangeAddress(10, 11, 10, 11);
sheet.addMergedRegion(disjointRegion); //allowed sheet.addMergedRegion(disjointRegion);
wb.close();
} }
/* /*

View File

@ -17,13 +17,19 @@
package org.apache.poi.ss.usermodel; package org.apache.poi.ss.usermodel;
import junit.framework.TestCase; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/** public abstract class BaseTestSheetHiding {
*/
public abstract class BaseTestSheetHiding extends TestCase {
protected final ITestDataProvider _testDataProvider; protected final ITestDataProvider _testDataProvider;
protected Workbook wbH; protected Workbook wbH;
@ -41,15 +47,22 @@ public abstract class BaseTestSheetHiding extends TestCase {
_file2 = file2; _file2 = file2;
} }
protected void setUp() { @Before
public void setUp() {
wbH = _testDataProvider.openSampleWorkbook(_file1); wbH = _testDataProvider.openSampleWorkbook(_file1);
wbU = _testDataProvider.openSampleWorkbook(_file2); wbU = _testDataProvider.openSampleWorkbook(_file2);
} }
@After
public void teadDown() throws IOException {
wbH.close();
wbU.close();
}
public final void testSheetHidden() { @Test
public final void testSheetHidden() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sh = wb.createSheet("MySheet"); wb.createSheet("MySheet");
assertFalse(wb.isSheetHidden(0)); assertFalse(wb.isSheetHidden(0));
assertFalse(wb.isSheetVeryHidden(0)); assertFalse(wb.isSheetVeryHidden(0));
@ -78,6 +91,8 @@ public abstract class BaseTestSheetHiding extends TestCase {
} catch (IllegalArgumentException e){ } catch (IllegalArgumentException e){
// ok // ok
} }
wb.close();
} }
/** /**
@ -85,6 +100,7 @@ public abstract class BaseTestSheetHiding extends TestCase {
* with the right text on them, no matter what * with the right text on them, no matter what
* the hidden flags are * the hidden flags are
*/ */
@Test
public void testTextSheets() { public void testTextSheets() {
// Both should have two sheets // Both should have two sheets
assertEquals(2, wbH.getNumberOfSheets()); assertEquals(2, wbH.getNumberOfSheets());
@ -113,6 +129,7 @@ public abstract class BaseTestSheetHiding extends TestCase {
* Check that we can get and set the hidden flags * Check that we can get and set the hidden flags
* as expected * as expected
*/ */
@Test
public void testHideUnHideFlags() { public void testHideUnHideFlags() {
assertTrue(wbH.isSheetHidden(0)); assertTrue(wbH.isSheetHidden(0));
assertFalse(wbH.isSheetHidden(1)); assertFalse(wbH.isSheetHidden(1));
@ -124,25 +141,29 @@ public abstract class BaseTestSheetHiding extends TestCase {
* Turn the sheet with none hidden into the one with * Turn the sheet with none hidden into the one with
* one hidden * one hidden
*/ */
public void testHide() { @Test
public void testHide() throws IOException {
wbU.setSheetHidden(0, true); wbU.setSheetHidden(0, true);
assertTrue(wbU.isSheetHidden(0)); assertTrue(wbU.isSheetHidden(0));
assertFalse(wbU.isSheetHidden(1)); assertFalse(wbU.isSheetHidden(1));
Workbook wb2 = _testDataProvider.writeOutAndReadBack(wbU); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wbU);
assertTrue(wb2.isSheetHidden(0)); assertTrue(wb2.isSheetHidden(0));
assertFalse(wb2.isSheetHidden(1)); assertFalse(wb2.isSheetHidden(1));
wb2.close();
} }
/** /**
* Turn the sheet with one hidden into the one with * Turn the sheet with one hidden into the one with
* none hidden * none hidden
*/ */
public void testUnHide() { @Test
public void testUnHide() throws IOException {
wbH.setSheetHidden(0, false); wbH.setSheetHidden(0, false);
assertFalse(wbH.isSheetHidden(0)); assertFalse(wbH.isSheetHidden(0));
assertFalse(wbH.isSheetHidden(1)); assertFalse(wbH.isSheetHidden(1));
Workbook wb2 = _testDataProvider.writeOutAndReadBack(wbH); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wbH);
assertFalse(wb2.isSheetHidden(0)); assertFalse(wb2.isSheetHidden(0));
assertFalse(wb2.isSheetHidden(1)); assertFalse(wb2.isSheetHidden(1));
wb2.close();
} }
} }