Changed CRLF to LF in .java test files. Minor reformatting and compiler warning fixes

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@776056 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Josh Micich 2009-05-18 19:11:45 +00:00
parent b924e3f4c8
commit e6a53dc85b
26 changed files with 3290 additions and 3291 deletions

View File

@ -1,156 +1,155 @@
/* ====================================================================
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with
contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership.
this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0
The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and
See the License for the specific language governing permissions and limitations under the License.
limitations under the License. ==================================================================== */
==================================================================== */
package org.apache.poi.ddf;
package org.apache.poi.ddf;
import java.io.File;
import junit.framework.TestCase; import java.io.FileInputStream;
import org.apache.poi.util.HexRead; import java.io.IOException;
import org.apache.poi.util.HexDump; import java.util.Arrays;
import java.io.IOException; import junit.framework.TestCase;
import java.io.File;
import java.io.FileInputStream; /**
import java.util.Iterator; * Test read/serialize of escher blip records
import java.util.Arrays; *
* @author Yegor Kozlov
/** */
* Test read/serialize of escher blip records public final class TestEscherBlipRecord extends TestCase {
* protected String cwd = System.getProperty("DDF.testdata.path");
* @author Yegor Kozlov
*/ //test reading/serializing of a PNG blip
public class TestEscherBlipRecord extends TestCase public void testReadPNG() {
{ //provided in bug-44886
protected String cwd = System.getProperty("DDF.testdata.path"); byte[] data = read(new File(cwd, "Container.dat"));
//test reading/serializing of a PNG blip EscherContainerRecord record = new EscherContainerRecord();
public void testReadPNG() throws IOException { record.fillFields(data, 0, new DefaultEscherRecordFactory());
//provided in bug-44886 EscherContainerRecord bstore = (EscherContainerRecord)record.getChild(1);
byte[] data = read(new File(cwd, "Container.dat")); EscherBSERecord bse1 = (EscherBSERecord)bstore.getChild(0);
assertEquals(EscherBSERecord.BT_PNG, bse1.getBlipTypeWin32());
EscherContainerRecord record = new EscherContainerRecord(); assertEquals(EscherBSERecord.BT_PNG, bse1.getBlipTypeMacOS());
record.fillFields(data, 0, new DefaultEscherRecordFactory()); assertTrue(Arrays.equals(new byte[]{
EscherContainerRecord bstore = (EscherContainerRecord)record.getChild(1); 0x65, 0x07, 0x4A, (byte)0x8D, 0x3E, 0x42, (byte)0x8B, (byte)0xAC,
EscherBSERecord bse1 = (EscherBSERecord)bstore.getChild(0); 0x1D, (byte)0x89, 0x35, 0x4F, 0x48, (byte)0xFA, 0x37, (byte)0xC2
assertEquals(EscherBSERecord.BT_PNG, bse1.getBlipTypeWin32()); }, bse1.getUid()));
assertEquals(EscherBSERecord.BT_PNG, bse1.getBlipTypeMacOS()); assertEquals(255, bse1.getTag());
assertTrue(Arrays.equals(new byte[]{ assertEquals(32308, bse1.getSize());
0x65, 0x07, 0x4A, (byte)0x8D, 0x3E, 0x42, (byte)0x8B, (byte)0xAC,
0x1D, (byte)0x89, 0x35, 0x4F, 0x48, (byte)0xFA, 0x37, (byte)0xC2 EscherBitmapBlip blip1 = (EscherBitmapBlip)bse1.getBlipRecord();
}, bse1.getUid())); assertEquals(0x6E00, blip1.getOptions());
assertEquals(255, bse1.getTag()); assertEquals(EscherBitmapBlip.RECORD_ID_PNG, blip1.getRecordId());
assertEquals(32308, bse1.getSize()); assertTrue(Arrays.equals(new byte[]{
0x65, 0x07, 0x4A, (byte)0x8D, 0x3E, 0x42, (byte)0x8B, (byte)0xAC,
EscherBitmapBlip blip1 = (EscherBitmapBlip)bse1.getBlipRecord(); 0x1D, (byte)0x89, 0x35, 0x4F, 0x48, (byte)0xFA, 0x37, (byte)0xC2
assertEquals(0x6E00, blip1.getOptions()); }, blip1.getUID()));
assertEquals(EscherBitmapBlip.RECORD_ID_PNG, blip1.getRecordId());
assertTrue(Arrays.equals(new byte[]{ //serialize and read again
0x65, 0x07, 0x4A, (byte)0x8D, 0x3E, 0x42, (byte)0x8B, (byte)0xAC, byte[] ser = bse1.serialize();
0x1D, (byte)0x89, 0x35, 0x4F, 0x48, (byte)0xFA, 0x37, (byte)0xC2 EscherBSERecord bse2 = new EscherBSERecord();
}, blip1.getUID())); bse2.fillFields(ser, 0, new DefaultEscherRecordFactory());
assertEquals(bse1.getRecordId(), bse2.getRecordId());
//serialize and read again assertEquals(bse1.getBlipTypeWin32(), bse2.getBlipTypeWin32());
byte[] ser = bse1.serialize(); assertEquals(bse1.getBlipTypeMacOS(), bse2.getBlipTypeMacOS());
EscherBSERecord bse2 = new EscherBSERecord(); assertTrue(Arrays.equals(bse1.getUid(), bse2.getUid()));
bse2.fillFields(ser, 0, new DefaultEscherRecordFactory()); assertEquals(bse1.getTag(), bse2.getTag());
assertEquals(bse1.getRecordId(), bse2.getRecordId()); assertEquals(bse1.getSize(), bse2.getSize());
assertEquals(bse1.getBlipTypeWin32(), bse2.getBlipTypeWin32());
assertEquals(bse1.getBlipTypeMacOS(), bse2.getBlipTypeMacOS()); EscherBitmapBlip blip2 = (EscherBitmapBlip)bse1.getBlipRecord();
assertTrue(Arrays.equals(bse1.getUid(), bse2.getUid())); assertEquals(blip1.getOptions(), blip2.getOptions());
assertEquals(bse1.getTag(), bse2.getTag()); assertEquals(blip1.getRecordId(), blip2.getRecordId());
assertEquals(bse1.getSize(), bse2.getSize()); assertEquals(blip1.getUID(), blip2.getUID());
EscherBitmapBlip blip2 = (EscherBitmapBlip)bse1.getBlipRecord(); assertTrue(Arrays.equals(blip1.getPicturedata(), blip1.getPicturedata()));
assertEquals(blip1.getOptions(), blip2.getOptions()); }
assertEquals(blip1.getRecordId(), blip2.getRecordId());
assertEquals(blip1.getUID(), blip2.getUID()); //test reading/serializing of a PICT metafile
public void testReadPICT() {
assertTrue(Arrays.equals(blip1.getPicturedata(), blip1.getPicturedata())); //provided in bug-44886
} byte[] data = read(new File(cwd, "Container.dat"));
//test reading/serializing of a PICT metafile EscherContainerRecord record = new EscherContainerRecord();
public void testReadPICT() throws IOException { record.fillFields(data, 0, new DefaultEscherRecordFactory());
//provided in bug-44886 EscherContainerRecord bstore = (EscherContainerRecord)record.getChild(1);
byte[] data = read(new File(cwd, "Container.dat")); EscherBSERecord bse1 = (EscherBSERecord)bstore.getChild(1);
//System.out.println(bse1);
EscherContainerRecord record = new EscherContainerRecord(); assertEquals(EscherBSERecord.BT_WMF, bse1.getBlipTypeWin32());
record.fillFields(data, 0, new DefaultEscherRecordFactory()); assertEquals(EscherBSERecord.BT_PICT, bse1.getBlipTypeMacOS());
EscherContainerRecord bstore = (EscherContainerRecord)record.getChild(1); assertTrue(Arrays.equals(new byte[]{
EscherBSERecord bse1 = (EscherBSERecord)bstore.getChild(1); (byte)0xC7, 0x15, 0x69, 0x2D, (byte)0xE5, (byte)0x89, (byte)0xA3, 0x6F,
//System.out.println(bse1); 0x66, 0x03, (byte)0xD6, 0x24, (byte)0xF7, (byte)0xDB, 0x1D, 0x13
assertEquals(EscherBSERecord.BT_WMF, bse1.getBlipTypeWin32()); }, bse1.getUid()));
assertEquals(EscherBSERecord.BT_PICT, bse1.getBlipTypeMacOS()); assertEquals(255, bse1.getTag());
assertTrue(Arrays.equals(new byte[]{ assertEquals(1133, bse1.getSize());
(byte)0xC7, 0x15, 0x69, 0x2D, (byte)0xE5, (byte)0x89, (byte)0xA3, 0x6F,
0x66, 0x03, (byte)0xD6, 0x24, (byte)0xF7, (byte)0xDB, 0x1D, 0x13 EscherMetafileBlip blip1 = (EscherMetafileBlip)bse1.getBlipRecord();
}, bse1.getUid())); assertEquals(0x5430, blip1.getOptions());
assertEquals(255, bse1.getTag()); assertEquals(EscherMetafileBlip.RECORD_ID_PICT, blip1.getRecordId());
assertEquals(1133, bse1.getSize()); assertTrue(Arrays.equals(new byte[]{
0x57, 0x32, 0x7B, (byte)0x91, 0x23, 0x5D, (byte)0xDB, 0x36,
EscherMetafileBlip blip1 = (EscherMetafileBlip)bse1.getBlipRecord(); 0x7A, (byte)0xDB, (byte)0xFF, 0x17, (byte)0xFE, (byte)0xF3, (byte)0xA7, 0x05
assertEquals(0x5430, blip1.getOptions()); }, blip1.getUID()));
assertEquals(EscherMetafileBlip.RECORD_ID_PICT, blip1.getRecordId()); assertTrue(Arrays.equals(new byte[]{
assertTrue(Arrays.equals(new byte[]{ (byte)0xC7, 0x15, 0x69, 0x2D, (byte)0xE5, (byte)0x89, (byte)0xA3, 0x6F,
0x57, 0x32, 0x7B, (byte)0x91, 0x23, 0x5D, (byte)0xDB, 0x36, 0x66, 0x03, (byte)0xD6, 0x24, (byte)0xF7, (byte)0xDB, 0x1D, 0x13
0x7A, (byte)0xDB, (byte)0xFF, 0x17, (byte)0xFE, (byte)0xF3, (byte)0xA7, 0x05 }, blip1.getPrimaryUID()));
}, blip1.getUID()));
assertTrue(Arrays.equals(new byte[]{ //serialize and read again
(byte)0xC7, 0x15, 0x69, 0x2D, (byte)0xE5, (byte)0x89, (byte)0xA3, 0x6F, byte[] ser = bse1.serialize();
0x66, 0x03, (byte)0xD6, 0x24, (byte)0xF7, (byte)0xDB, 0x1D, 0x13 EscherBSERecord bse2 = new EscherBSERecord();
}, blip1.getPrimaryUID())); bse2.fillFields(ser, 0, new DefaultEscherRecordFactory());
assertEquals(bse1.getRecordId(), bse2.getRecordId());
//serialize and read again assertEquals(bse1.getOptions(), bse2.getOptions());
byte[] ser = bse1.serialize(); assertEquals(bse1.getBlipTypeWin32(), bse2.getBlipTypeWin32());
EscherBSERecord bse2 = new EscherBSERecord(); assertEquals(bse1.getBlipTypeMacOS(), bse2.getBlipTypeMacOS());
bse2.fillFields(ser, 0, new DefaultEscherRecordFactory()); assertTrue(Arrays.equals(bse1.getUid(), bse2.getUid()));
assertEquals(bse1.getRecordId(), bse2.getRecordId()); assertEquals(bse1.getTag(), bse2.getTag());
assertEquals(bse1.getOptions(), bse2.getOptions()); assertEquals(bse1.getSize(), bse2.getSize());
assertEquals(bse1.getBlipTypeWin32(), bse2.getBlipTypeWin32());
assertEquals(bse1.getBlipTypeMacOS(), bse2.getBlipTypeMacOS()); EscherMetafileBlip blip2 = (EscherMetafileBlip)bse1.getBlipRecord();
assertTrue(Arrays.equals(bse1.getUid(), bse2.getUid())); assertEquals(blip1.getOptions(), blip2.getOptions());
assertEquals(bse1.getTag(), bse2.getTag()); assertEquals(blip1.getRecordId(), blip2.getRecordId());
assertEquals(bse1.getSize(), bse2.getSize()); assertEquals(blip1.getUID(), blip2.getUID());
assertEquals(blip1.getPrimaryUID(), blip2.getPrimaryUID());
EscherMetafileBlip blip2 = (EscherMetafileBlip)bse1.getBlipRecord();
assertEquals(blip1.getOptions(), blip2.getOptions()); assertTrue(Arrays.equals(blip1.getPicturedata(), blip1.getPicturedata()));
assertEquals(blip1.getRecordId(), blip2.getRecordId()); }
assertEquals(blip1.getUID(), blip2.getUID());
assertEquals(blip1.getPrimaryUID(), blip2.getPrimaryUID()); //integral test: check that the read-write-read round trip is consistent
public void testContainer() {
assertTrue(Arrays.equals(blip1.getPicturedata(), blip1.getPicturedata())); byte[] data = read(new File(cwd, "Container.dat"));
}
EscherContainerRecord record = new EscherContainerRecord();
//integral test: check that the read-write-read round trip is consistent record.fillFields(data, 0, new DefaultEscherRecordFactory());
public void testContainer() throws IOException {
byte[] data = read(new File(cwd, "Container.dat")); byte[] ser = record.serialize();
assertTrue(Arrays.equals(data, ser));
EscherContainerRecord record = new EscherContainerRecord(); }
record.fillFields(data, 0, new DefaultEscherRecordFactory());
private byte[] read(File file) {
byte[] ser = record.serialize(); byte[] data = new byte[(int)file.length()];
assertTrue(Arrays.equals(data, ser)); try {
} FileInputStream is = new FileInputStream(file);
is.read(data);
private byte[] read(File file) throws IOException { is.close();
byte[] data = new byte[(int)file.length()]; } catch (IOException e) {
FileInputStream is = new FileInputStream(file); throw new RuntimeException(e);
is.read(data); }
is.close(); return data;
return data; }
}
}
}

View File

@ -1,59 +1,59 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf; package org.apache.poi.hssf;
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.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
/** /**
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public final class HSSFITestDataProvider implements ITestDataProvider { public final class HSSFITestDataProvider implements ITestDataProvider {
public HSSFWorkbook openSampleWorkbook(String sampleFileName) { public HSSFWorkbook openSampleWorkbook(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
} }
public HSSFWorkbook writeOutAndReadBack(Workbook original) { public HSSFWorkbook writeOutAndReadBack(Workbook original) {
if(!(original instanceof HSSFWorkbook)) { if(!(original instanceof HSSFWorkbook)) {
throw new IllegalArgumentException("Expected an instance of HSSFWorkbook"); throw new IllegalArgumentException("Expected an instance of HSSFWorkbook");
} }
return HSSFTestDataSamples.writeOutAndReadBack((HSSFWorkbook)original); return HSSFTestDataSamples.writeOutAndReadBack((HSSFWorkbook)original);
} }
public HSSFWorkbook createWorkbook(){ public HSSFWorkbook createWorkbook(){
return new HSSFWorkbook(); return new HSSFWorkbook();
} }
public byte[] getTestDataFileContent(String fileName) { public byte[] getTestDataFileContent(String fileName) {
return HSSFTestDataSamples.getTestDataFileContent(fileName); return HSSFTestDataSamples.getTestDataFileContent(fileName);
} }
public SpreadsheetVersion getSpreadsheetVersion(){ public SpreadsheetVersion getSpreadsheetVersion(){
return SpreadsheetVersion.EXCEL97; return SpreadsheetVersion.EXCEL97;
} }
private HSSFITestDataProvider(){} private HSSFITestDataProvider(){}
private static HSSFITestDataProvider inst = new HSSFITestDataProvider(); private static HSSFITestDataProvider inst = new HSSFITestDataProvider();
public static HSSFITestDataProvider getInstance(){ public static HSSFITestDataProvider getInstance(){
return inst; return inst;
} }
} }

View File

@ -1,199 +1,198 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf; package org.apache.poi.hssf;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/** /**
* Centralises logic for finding/opening sample files in the src/testcases/org/apache/poi/hssf/hssf/data folder. * Centralises logic for finding/opening sample files in the src/testcases/org/apache/poi/hssf/hssf/data folder.
* *
* @author Josh Micich * @author Josh Micich
*/ */
public final class HSSFTestDataSamples { public final class HSSFTestDataSamples {
private static final String TEST_DATA_DIR_SYS_PROPERTY_NAME = "HSSF.testdata.path"; private static final String TEST_DATA_DIR_SYS_PROPERTY_NAME = "HSSF.testdata.path";
private static boolean _isInitialised; private static boolean _isInitialised;
private static File _resolvedDataDir; private static File _resolvedDataDir;
/** <code>true</code> if standard system propery is not set, /** <code>true</code> if standard system propery is not set,
* but the data is available on the test runtime classpath */ * but the data is available on the test runtime classpath */
private static boolean _sampleDataIsAvaliableOnClassPath; private static boolean _sampleDataIsAvaliableOnClassPath;
/** /**
* Opens a sample file from the standard HSSF test data directory * Opens a sample file from the standard HSSF test data directory
* *
* @return an open <tt>InputStream</tt> for the specified sample file * @return an open <tt>InputStream</tt> for the specified sample file
*/ */
public static InputStream openSampleFileStream(String sampleFileName) { public static InputStream openSampleFileStream(String sampleFileName) {
if(!_isInitialised) { if(!_isInitialised) {
try { try {
initialise(); initialise();
} finally { } finally {
_isInitialised = true; _isInitialised = true;
} }
} }
if (_sampleDataIsAvaliableOnClassPath) { if (_sampleDataIsAvaliableOnClassPath) {
InputStream result = openClasspathResource(sampleFileName); InputStream result = openClasspathResource(sampleFileName);
if(result == null) { if(result == null) {
throw new RuntimeException("specified test sample file '" + sampleFileName throw new RuntimeException("specified test sample file '" + sampleFileName
+ "' not found on the classpath"); + "' not found on the classpath");
} }
// System.out.println("opening cp: " + sampleFileName); // System.out.println("opening cp: " + sampleFileName);
// wrap to avoid temp warning method about auto-closing input stream // wrap to avoid temp warning method about auto-closing input stream
return new NonSeekableInputStream(result); return new NonSeekableInputStream(result);
} }
if (_resolvedDataDir == null) { if (_resolvedDataDir == null) {
throw new RuntimeException("Must set system property '" throw new RuntimeException("Must set system property '"
+ TEST_DATA_DIR_SYS_PROPERTY_NAME + TEST_DATA_DIR_SYS_PROPERTY_NAME
+ "' properly before running tests"); + "' properly before running tests");
} }
File f = new File(_resolvedDataDir, sampleFileName); File f = new File(_resolvedDataDir, sampleFileName);
if (!f.exists()) { if (!f.exists()) {
throw new RuntimeException("Sample file '" + sampleFileName throw new RuntimeException("Sample file '" + sampleFileName
+ "' not found in data dir '" + _resolvedDataDir.getAbsolutePath() + "'"); + "' not found in data dir '" + _resolvedDataDir.getAbsolutePath() + "'");
} }
// System.out.println("opening " + f.getAbsolutePath()); // System.out.println("opening " + f.getAbsolutePath());
try { try {
return new FileInputStream(f); return new FileInputStream(f);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
private static void initialise() { private static void initialise() {
String dataDirName = System.getProperty(TEST_DATA_DIR_SYS_PROPERTY_NAME); String dataDirName = System.getProperty(TEST_DATA_DIR_SYS_PROPERTY_NAME);
if (dataDirName == null) { if (dataDirName == null) {
// check to see if we can just get the resources from the classpath // check to see if we can just get the resources from the classpath
InputStream is = openClasspathResource("SampleSS.xls"); InputStream is = openClasspathResource("SampleSS.xls");
if(is != null) { if (is != null) {
try { try {
is.close(); // be nice is.close(); // be nice
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
_sampleDataIsAvaliableOnClassPath = true; _sampleDataIsAvaliableOnClassPath = true;
return; return;
} }
throw new RuntimeException("Must set system property '"
throw new RuntimeException("Must set system property '" + TEST_DATA_DIR_SYS_PROPERTY_NAME + "' before running tests");
+ TEST_DATA_DIR_SYS_PROPERTY_NAME }
+ "' before running tests"); File dataDir = new File(dataDirName);
} if (!dataDir.exists()) {
File dataDir = new File(dataDirName); throw new RuntimeException("Data dir '" + dataDirName
if (!dataDir.exists()) { + "' specified by system property '" + TEST_DATA_DIR_SYS_PROPERTY_NAME
throw new RuntimeException("Data dir '" + dataDirName + "' does not exist");
+ "' specified by system property '" }
+ TEST_DATA_DIR_SYS_PROPERTY_NAME + "' does not exist"); // convert to canonical file, to make any subsequent error messages
} // clearer.
// convert to canonical file, to make any subsequent error messages clearer. try {
try { _resolvedDataDir = dataDir.getCanonicalFile();
_resolvedDataDir = dataDir.getCanonicalFile(); } catch (IOException e) {
} catch (IOException e) { throw new RuntimeException(e);
throw new RuntimeException(e); }
} }
}
/**
/** * Opens a test sample file from the 'data' sub-package of this class's package.
* Opens a test sample file from the 'data' sub-package of this class's package. * @return <code>null</code> if the sample file is not deployed on the classpath.
* @return <code>null</code> if the sample file is not deployed on the classpath. */
*/ private static InputStream openClasspathResource(String sampleFileName) {
private static InputStream openClasspathResource(String sampleFileName) { return HSSFTestDataSamples.class.getResourceAsStream("data/" + sampleFileName);
return HSSFTestDataSamples.class.getResourceAsStream("data/" + sampleFileName); }
}
private static final class NonSeekableInputStream extends InputStream {
private static final class NonSeekableInputStream extends InputStream {
private final InputStream _is;
private final InputStream _is;
public NonSeekableInputStream(InputStream is) {
public NonSeekableInputStream(InputStream is) { _is = is;
_is = is; }
}
public int read() throws IOException {
public int read() throws IOException { return _is.read();
return _is.read(); }
} public int read(byte[] b, int off, int len) throws IOException {
public int read(byte[] b, int off, int len) throws IOException { return _is.read(b, off, len);
return _is.read(b, off, len); }
} public boolean markSupported() {
public boolean markSupported() { return false;
return false; }
} public void close() throws IOException {
public void close() throws IOException { _is.close();
_is.close(); }
} }
}
public static HSSFWorkbook openSampleWorkbook(String sampleFileName) {
public static HSSFWorkbook openSampleWorkbook(String sampleFileName) { try {
try { return new HSSFWorkbook(openSampleFileStream(sampleFileName));
return new HSSFWorkbook(openSampleFileStream(sampleFileName)); } catch (IOException e) {
} catch (IOException e) { throw new RuntimeException(e);
throw new RuntimeException(e); }
} }
} /**
/** * Writes a spreadsheet to a <tt>ByteArrayOutputStream</tt> and reads it back
* Writes a spreadsheet to a <tt>ByteArrayOutputStream</tt> and reads it back * from a <tt>ByteArrayInputStream</tt>.<p/>
* from a <tt>ByteArrayInputStream</tt>.<p/> * Useful for verifying that the serialisation round trip
* Useful for verifying that the serialisation round trip */
*/ public static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) {
public static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) {
try {
try { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); original.write(baos);
original.write(baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); return new HSSFWorkbook(bais);
return new HSSFWorkbook(bais); } catch (IOException e) {
} catch (IOException e) { throw new RuntimeException(e);
throw new RuntimeException(e); }
} }
}
/**
/** * @return byte array of sample file content from file found in standard hssf test data dir
* @return byte array of sample file content from file found in standard hssf test data dir */
*/ public static byte[] getTestDataFileContent(String fileName) {
public static byte[] getTestDataFileContent(String fileName) { ByteArrayOutputStream bos = new ByteArrayOutputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
try { InputStream fis = HSSFTestDataSamples.openSampleFileStream(fileName);
InputStream fis = HSSFTestDataSamples.openSampleFileStream(fileName);
byte[] buf = new byte[512];
byte[] buf = new byte[512]; while (true) {
while (true) { int bytesRead = fis.read(buf);
int bytesRead = fis.read(buf); if (bytesRead < 1) {
if (bytesRead < 1) { break;
break; }
} bos.write(buf, 0, bytesRead);
bos.write(buf, 0, bytesRead); }
} fis.close();
fis.close(); } catch (IOException e) {
} catch (IOException e) { throw new RuntimeException(e);
throw new RuntimeException(e); }
} return bos.toByteArray();
return bos.toByteArray(); }
} }
}

View File

@ -1,60 +1,61 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.model; package org.apache.poi.hssf.model;
import java.util.Arrays; import java.util.Arrays;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.record.NumberRecord; import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.RowRecord; import org.apache.poi.hssf.record.RowRecord;
import org.apache.poi.hssf.record.UnknownRecord; import org.apache.poi.hssf.record.UnknownRecord;
import org.apache.poi.hssf.record.WindowTwoRecord; import org.apache.poi.hssf.record.WindowTwoRecord;
import org.apache.poi.hssf.record.pivottable.ViewDefinitionRecord;
/**
* Tests for {@link RowBlocksReader} /**
* * Tests for {@link RowBlocksReader}
* @author Josh Micich *
*/ * @author Josh Micich
public final class TestRowBlocksReader extends TestCase { */
public void testAbnormalPivotTableRecords_bug46280() { public final class TestRowBlocksReader extends TestCase {
int SXVIEW_SID = 0x00B0; public void testAbnormalPivotTableRecords_bug46280() {
Record[] inRecs = { int SXVIEW_SID = ViewDefinitionRecord.sid;
new RowRecord(0), Record[] inRecs = {
new NumberRecord(), new RowRecord(0),
// normally MSODRAWING(0x00EC) would come here before SXVIEW new NumberRecord(),
new UnknownRecord(SXVIEW_SID, "dummydata (SXVIEW: View Definition)".getBytes()), // normally MSODRAWING(0x00EC) would come here before SXVIEW
new WindowTwoRecord(), new UnknownRecord(SXVIEW_SID, "dummydata (SXVIEW: View Definition)".getBytes()),
}; new WindowTwoRecord(),
RecordStream rs = new RecordStream(Arrays.asList(inRecs), 0); };
RowBlocksReader rbr = new RowBlocksReader(rs); RecordStream rs = new RecordStream(Arrays.asList(inRecs), 0);
if (rs.peekNextClass() == WindowTwoRecord.class) { RowBlocksReader rbr = new RowBlocksReader(rs);
// Should have stopped at the SXVIEW record if (rs.peekNextClass() == WindowTwoRecord.class) {
throw new AssertionFailedError("Identified bug 46280b"); // Should have stopped at the SXVIEW record
} throw new AssertionFailedError("Identified bug 46280b");
RecordStream rbStream = rbr.getPlainRecordStream(); }
assertEquals(inRecs[0], rbStream.getNext()); RecordStream rbStream = rbr.getPlainRecordStream();
assertEquals(inRecs[1], rbStream.getNext()); assertEquals(inRecs[0], rbStream.getNext());
assertFalse(rbStream.hasNext()); assertEquals(inRecs[1], rbStream.getNext());
assertTrue(rs.hasNext()); assertFalse(rbStream.hasNext());
assertEquals(inRecs[2], rs.getNext()); assertTrue(rs.hasNext());
assertEquals(inRecs[3], rs.getNext()); assertEquals(inRecs[2], rs.getNext());
} assertEquals(inRecs[3], rs.getNext());
} }
}

View File

@ -1,171 +1,171 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import java.util.Arrays; import java.util.Arrays;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.util.HexRead; import org.apache.poi.util.HexRead;
/** /**
* Tests the serialization and deserialization of the TestEmbeddedObjectRefSubRecord * Tests the serialization and deserialization of the TestEmbeddedObjectRefSubRecord
* class works correctly. Test data taken directly from a real * class works correctly. Test data taken directly from a real
* Excel file. * Excel file.
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public final class TestEmbeddedObjectRefSubRecord extends TestCase { public final class TestEmbeddedObjectRefSubRecord extends TestCase {
private static final short EORSR_SID = EmbeddedObjectRefSubRecord.sid; private static final short EORSR_SID = EmbeddedObjectRefSubRecord.sid;
public void testStore() { public void testStore() {
String data1 String data1
= "20 00 05 00 FC 10 76 01 02 24 14 DF 00 03 10 00 " = "20 00 05 00 FC 10 76 01 02 24 14 DF 00 03 10 00 "
+ "00 46 6F 72 6D 73 2E 43 68 65 63 6B 42 6F 78 2E " + "00 46 6F 72 6D 73 2E 43 68 65 63 6B 42 6F 78 2E "
+ "31 00 00 00 00 00 70 00 00 00 00 00 00 00 00 00 " + "31 00 00 00 00 00 70 00 00 00 00 00 00 00 00 00 "
+ "00 00"; + "00 00";
byte[] src = hr(data1); byte[] src = hr(data1);
RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, src); RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, src);
EmbeddedObjectRefSubRecord record1 = new EmbeddedObjectRefSubRecord(in, src.length); EmbeddedObjectRefSubRecord record1 = new EmbeddedObjectRefSubRecord(in, src.length);
byte[] ser = record1.serialize(); byte[] ser = record1.serialize();
RecordInputStream in2 = TestcaseRecordInputStream.create(ser); RecordInputStream in2 = TestcaseRecordInputStream.create(ser);
EmbeddedObjectRefSubRecord record2 = new EmbeddedObjectRefSubRecord(in2, ser.length-4); EmbeddedObjectRefSubRecord record2 = new EmbeddedObjectRefSubRecord(in2, ser.length-4);
confirmData(src, ser); confirmData(src, ser);
assertEquals(record1.getOLEClassName(), record2.getOLEClassName()); assertEquals(record1.getOLEClassName(), record2.getOLEClassName());
byte[] ser2 = record1.serialize(); byte[] ser2 = record1.serialize();
assertTrue(Arrays.equals(ser, ser2)); assertTrue(Arrays.equals(ser, ser2));
} }
/** /**
* @param expectedData does not include sid & size * @param expectedData does not include sid & size
* @param actualFullRecordData includes sid & size * @param actualFullRecordData includes sid & size
*/ */
private static void confirmData(byte[] expectedData, byte[] actualFullRecordData) { private static void confirmData(byte[] expectedData, byte[] actualFullRecordData) {
assertEquals(expectedData.length, actualFullRecordData.length-4); assertEquals(expectedData.length, actualFullRecordData.length-4);
for (int i = 0; i < expectedData.length; i++) { for (int i = 0; i < expectedData.length; i++) {
if(expectedData[i] != actualFullRecordData[i+4]) { if(expectedData[i] != actualFullRecordData[i+4]) {
throw new AssertionFailedError("Difference at offset (" + i + ")"); throw new AssertionFailedError("Difference at offset (" + i + ")");
} }
} }
} }
public void testCreate() { public void testCreate() {
EmbeddedObjectRefSubRecord record1 = new EmbeddedObjectRefSubRecord(); EmbeddedObjectRefSubRecord record1 = new EmbeddedObjectRefSubRecord();
byte[] ser = record1.serialize(); byte[] ser = record1.serialize();
RecordInputStream in2 = TestcaseRecordInputStream.create(ser); RecordInputStream in2 = TestcaseRecordInputStream.create(ser);
EmbeddedObjectRefSubRecord record2 = new EmbeddedObjectRefSubRecord(in2, ser.length-4); EmbeddedObjectRefSubRecord record2 = new EmbeddedObjectRefSubRecord(in2, ser.length-4);
assertEquals(record1.getOLEClassName(), record2.getOLEClassName()); assertEquals(record1.getOLEClassName(), record2.getOLEClassName());
assertEquals(record1.getStreamId(), record2.getStreamId()); assertEquals(record1.getStreamId(), record2.getStreamId());
byte[] ser2 = record1.serialize(); byte[] ser2 = record1.serialize();
assertTrue(Arrays.equals(ser, ser2)); assertTrue(Arrays.equals(ser, ser2));
} }
public void testCameraTool_bug45912() { public void testCameraTool_bug45912() {
/** /**
* taken from ftPictFmla sub-record in attachment 22645 (offset 0x40AB). * taken from ftPictFmla sub-record in attachment 22645 (offset 0x40AB).
*/ */
byte[] data45912 = hr( byte[] data45912 = hr(
"12 00 0B 00 F8 02 88 04 3B 00 " + "12 00 0B 00 F8 02 88 04 3B 00 " +
"00 00 00 01 00 00 00 01 " + "00 00 00 01 00 00 00 01 " +
"00 00"); "00 00");
RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data45912); RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data45912);
EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data45912.length); EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data45912.length);
byte[] ser2 = rec.serialize(); byte[] ser2 = rec.serialize();
confirmData(data45912, ser2); confirmData(data45912, ser2);
} }
private static byte[] hr(String string) { private static byte[] hr(String string) {
return HexRead.readFromString(string); return HexRead.readFromString(string);
} }
/** /**
* tests various examples of OLE controls * tests various examples of OLE controls
*/ */
public void testVarious() { public void testVarious() {
String[] rawData = { String[] rawData = {
"12 00 0B 00 70 95 0B 05 3B 01 00 36 00 40 00 18 00 19 00 18", "12 00 0B 00 70 95 0B 05 3B 01 00 36 00 40 00 18 00 19 00 18",
"12 00 0B 00 B0 4D 3E 03 3B 00 00 00 00 01 00 00 80 01 C0 00", "12 00 0B 00 B0 4D 3E 03 3B 00 00 00 00 01 00 00 80 01 C0 00",
"0C 00 05 00 60 AF 3B 03 24 FD FF FE C0 FE", "0C 00 05 00 60 AF 3B 03 24 FD FF FE C0 FE",
"24 00 05 00 40 42 3E 03 02 80 CD B4 04 03 15 00 00 46 6F 72 6D 73 2E 43 6F 6D 6D 61 6E 64 42 75 74 74 6F 6E 2E 31 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00", "24 00 05 00 40 42 3E 03 02 80 CD B4 04 03 15 00 00 46 6F 72 6D 73 2E 43 6F 6D 6D 61 6E 64 42 75 74 74 6F 6E 2E 31 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00",
"22 00 05 00 10 4E 3E 03 02 00 4C CC 04 03 12 00 00 46 6F 72 6D 73 2E 53 70 69 6E 42 75 74 74 6F 6E 2E 31 00 54 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00", "22 00 05 00 10 4E 3E 03 02 00 4C CC 04 03 12 00 00 46 6F 72 6D 73 2E 53 70 69 6E 42 75 74 74 6F 6E 2E 31 00 54 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00",
"20 00 05 00 E0 41 3E 03 02 00 FC 0B 05 03 10 00 00 46 6F 72 6D 73 2E 43 6F 6D 62 6F 42 6F 78 2E 31 00 74 00 00 00 4C 00 00 00 00 00 00 00 00 00 00 00", "20 00 05 00 E0 41 3E 03 02 00 FC 0B 05 03 10 00 00 46 6F 72 6D 73 2E 43 6F 6D 62 6F 42 6F 78 2E 31 00 74 00 00 00 4C 00 00 00 00 00 00 00 00 00 00 00",
"24 00 05 00 00 4C AF 03 02 80 E1 93 05 03 14 00 00 46 6F 72 6D 73 2E 4F 70 74 69 6F 6E 42 75 74 74 6F 6E 2E 31 00 C0 00 00 00 70 00 00 00 00 00 00 00 00 00 00 00", "24 00 05 00 00 4C AF 03 02 80 E1 93 05 03 14 00 00 46 6F 72 6D 73 2E 4F 70 74 69 6F 6E 42 75 74 74 6F 6E 2E 31 00 C0 00 00 00 70 00 00 00 00 00 00 00 00 00 00 00",
"20 00 05 00 E0 A4 28 04 02 80 EA 93 05 03 10 00 00 46 6F 72 6D 73 2E 43 68 65 63 6B 42 6F 78 2E 31 00 30 01 00 00 6C 00 00 00 00 00 00 00 00 00 00 00", "20 00 05 00 E0 A4 28 04 02 80 EA 93 05 03 10 00 00 46 6F 72 6D 73 2E 43 68 65 63 6B 42 6F 78 2E 31 00 30 01 00 00 6C 00 00 00 00 00 00 00 00 00 00 00",
"1C 00 05 00 30 40 3E 03 02 00 CC B4 04 03 0D 00 00 46 6F 72 6D 73 2E 4C 61 62 65 6C 2E 31 9C 01 00 00 54 00 00 00 00 00 00 00 00 00 00 00", "1C 00 05 00 30 40 3E 03 02 00 CC B4 04 03 0D 00 00 46 6F 72 6D 73 2E 4C 61 62 65 6C 2E 31 9C 01 00 00 54 00 00 00 00 00 00 00 00 00 00 00",
"1E 00 05 00 B0 A4 28 04 02 00 D0 0A 05 03 0F 00 00 46 6F 72 6D 73 2E 4C 69 73 74 42 6F 78 2E 31 F0 01 00 00 48 00 00 00 00 00 00 00 00 00 00 00", "1E 00 05 00 B0 A4 28 04 02 00 D0 0A 05 03 0F 00 00 46 6F 72 6D 73 2E 4C 69 73 74 42 6F 78 2E 31 F0 01 00 00 48 00 00 00 00 00 00 00 00 00 00 00",
"24 00 05 00 C0 AF 3B 03 02 80 D1 0A 05 03 14 00 00 46 6F 72 6D 73 2E 54 6F 67 67 6C 65 42 75 74 74 6F 6E 2E 31 00 38 02 00 00 6C 00 00 00 00 00 00 00 00 00 00 00", "24 00 05 00 C0 AF 3B 03 02 80 D1 0A 05 03 14 00 00 46 6F 72 6D 73 2E 54 6F 67 67 6C 65 42 75 74 74 6F 6E 2E 31 00 38 02 00 00 6C 00 00 00 00 00 00 00 00 00 00 00",
"1E 00 05 00 90 AF 3B 03 02 80 D4 0A 05 03 0F 00 00 46 6F 72 6D 73 2E 54 65 78 74 42 6F 78 2E 31 A4 02 00 00 48 00 00 00 00 00 00 00 00 00 00 00", "1E 00 05 00 90 AF 3B 03 02 80 D4 0A 05 03 0F 00 00 46 6F 72 6D 73 2E 54 65 78 74 42 6F 78 2E 31 A4 02 00 00 48 00 00 00 00 00 00 00 00 00 00 00",
"24 00 05 00 60 40 3E 03 02 00 D6 0A 05 03 14 00 00 46 6F 72 6D 73 2E 54 6F 67 67 6C 65 42 75 74 74 6F 6E 2E 31 00 EC 02 00 00 6C 00 00 00 00 00 00 00 00 00 00 00", "24 00 05 00 60 40 3E 03 02 00 D6 0A 05 03 14 00 00 46 6F 72 6D 73 2E 54 6F 67 67 6C 65 42 75 74 74 6F 6E 2E 31 00 EC 02 00 00 6C 00 00 00 00 00 00 00 00 00 00 00",
"20 00 05 00 20 4D 3E 03 02 00 D9 0A 05 03 11 00 00 46 6F 72 6D 73 2E 53 63 72 6F 6C 6C 42 61 72 2E 31 58 03 00 00 20 00 00 00 00 00 00 00 00 00 00 00", "20 00 05 00 20 4D 3E 03 02 00 D9 0A 05 03 11 00 00 46 6F 72 6D 73 2E 53 63 72 6F 6C 6C 42 61 72 2E 31 58 03 00 00 20 00 00 00 00 00 00 00 00 00 00 00",
"20 00 05 00 00 AF 28 04 02 80 31 AC 04 03 10 00 00 53 68 65 6C 6C 2E 45 78 70 6C 6F 72 65 72 2E 32 00 78 03 00 00 AC 00 00 00 00 00 00 00 00 00 00 00", "20 00 05 00 00 AF 28 04 02 80 31 AC 04 03 10 00 00 53 68 65 6C 6C 2E 45 78 70 6C 6F 72 65 72 2E 32 00 78 03 00 00 AC 00 00 00 00 00 00 00 00 00 00 00",
}; };
for (int i = 0; i < rawData.length; i++) { for (int i = 0; i < rawData.length; i++) {
confirmRead(hr(rawData[i]), i); confirmRead(hr(rawData[i]), i);
} }
} }
private static void confirmRead(byte[] data, int i) { private static void confirmRead(byte[] data, int i) {
RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data); RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data);
EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data.length); EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data.length);
byte[] ser2 = rec.serialize(); byte[] ser2 = rec.serialize();
TestcaseRecordInputStream.confirmRecordEncoding("Test record " + i, EORSR_SID, data, ser2); TestcaseRecordInputStream.confirmRecordEncoding("Test record " + i, EORSR_SID, data, ser2);
} }
public void testVisioDrawing_bug46199() { public void testVisioDrawing_bug46199() {
/** /**
* taken from ftPictFmla sub-record in attachment 22860 (stream offset 0x768F).<br/> * taken from ftPictFmla sub-record in attachment 22860 (stream offset 0x768F).<br/>
* Note that the since the string length is zero, there is no unicode flag byte * Note that the since the string length is zero, there is no unicode flag byte
*/ */
byte[] data46199 = hr( byte[] data46199 = hr(
"0E 00 " "0E 00 "
+ "05 00 " + "05 00 "
+ "28 25 A3 01 " + "28 25 A3 01 "
+ "02 6C D1 34 02 " + "02 6C D1 34 02 "
+ "03 00 00 " + "03 00 00 "
+ "0F CB E8 00"); + "0F CB E8 00");
RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data46199); RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data46199);
EmbeddedObjectRefSubRecord rec; EmbeddedObjectRefSubRecord rec;
try { try {
rec = new EmbeddedObjectRefSubRecord(in, data46199.length); rec = new EmbeddedObjectRefSubRecord(in, data46199.length);
} catch (RecordFormatException e) { } catch (RecordFormatException e) {
if (e.getMessage().equals("Not enough data (3) to read requested (4) bytes")) { if (e.getMessage().equals("Not enough data (3) to read requested (4) bytes")) {
throw new AssertionFailedError("Identified bug 22860"); throw new AssertionFailedError("Identified bug 22860");
} }
throw e; throw e;
} }
byte[] ser2 = rec.serialize(); byte[] ser2 = rec.serialize();
TestcaseRecordInputStream.confirmRecordEncoding(EORSR_SID, data46199, ser2); TestcaseRecordInputStream.confirmRecordEncoding(EORSR_SID, data46199, ser2);
} }
} }

View File

@ -1,105 +1,105 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
/** /**
* *
* @author Josh Micich * @author Josh Micich
*/ */
public final class TestExternalNameRecord extends TestCase { public final class TestExternalNameRecord extends TestCase {
private static final byte[] dataFDS = { private static final byte[] dataFDS = {
0, 0, 0, 0, 0, 0, 3, 0, 70, 68, 83, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 70, 68, 83, 0, 0,
}; };
// data taken from bugzilla 44774 att 21790 // data taken from bugzilla 44774 att 21790
private static final byte[] dataAutoDocName = { private static final byte[] dataAutoDocName = {
-22, 127, 0, 0, 0, 0, 29, 0, 39, 49, 57, 49, 50, 49, 57, 65, 87, 52, 32, 67, 111, 114, -22, 127, 0, 0, 0, 0, 29, 0, 39, 49, 57, 49, 50, 49, 57, 65, 87, 52, 32, 67, 111, 114,
112, 44, 91, 87, 79, 82, 75, 79, 85, 84, 95, 80, 88, 93, 39, 112, 44, 91, 87, 79, 82, 75, 79, 85, 84, 95, 80, 88, 93, 39,
}; };
// data taken from bugzilla 44774 att 21790 // data taken from bugzilla 44774 att 21790
private static final byte[] dataPlainName = { private static final byte[] dataPlainName = {
0, 0, 0, 0, 0, 0, 9, 0, 82, 97, 116, 101, 95, 68, 97, 116, 101, 9, 0, 58, 0, 0, 0, 0, 4, 0, 8, 0 0, 0, 0, 0, 0, 0, 9, 0, 82, 97, 116, 101, 95, 68, 97, 116, 101, 9, 0, 58, 0, 0, 0, 0, 4, 0, 8, 0
// TODO - the last 2 bytes of formula data (8,0) seem weird. They encode to ConcatPtg, UnknownPtg // TODO - the last 2 bytes of formula data (8,0) seem weird. They encode to ConcatPtg, UnknownPtg
// UnknownPtg is otherwise not created by any other test cases // UnknownPtg is otherwise not created by any other test cases
}; };
private static ExternalNameRecord createSimpleENR(byte[] data) { private static ExternalNameRecord createSimpleENR(byte[] data) {
return new ExternalNameRecord(TestcaseRecordInputStream.create(0x0023, data)); return new ExternalNameRecord(TestcaseRecordInputStream.create(0x0023, data));
} }
public void testBasicDeserializeReserialize() { public void testBasicDeserializeReserialize() {
ExternalNameRecord enr = createSimpleENR(dataFDS); ExternalNameRecord enr = createSimpleENR(dataFDS);
assertEquals("FDS", enr.getText()); assertEquals("FDS", enr.getText());
try { try {
TestcaseRecordInputStream.confirmRecordEncoding(0x0023, dataFDS, enr.serialize()); TestcaseRecordInputStream.confirmRecordEncoding(0x0023, dataFDS, enr.serialize());
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException e) {
if(e.getMessage().equals("15")) { if(e.getMessage().equals("15")) {
throw new AssertionFailedError("Identified bug 44695"); throw new AssertionFailedError("Identified bug 44695");
} }
} }
} }
public void testBasicSize() { public void testBasicSize() {
ExternalNameRecord enr = createSimpleENR(dataFDS); ExternalNameRecord enr = createSimpleENR(dataFDS);
if(enr.getRecordSize() == 13) { if(enr.getRecordSize() == 13) {
throw new AssertionFailedError("Identified bug 44695"); throw new AssertionFailedError("Identified bug 44695");
} }
assertEquals(17, enr.getRecordSize()); assertEquals(17, enr.getRecordSize());
} }
public void testAutoStdDocName() { public void testAutoStdDocName() {
ExternalNameRecord enr; ExternalNameRecord enr;
try { try {
enr = createSimpleENR(dataAutoDocName); enr = createSimpleENR(dataAutoDocName);
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException e) {
if(e.getMessage() == null) { if(e.getMessage() == null) {
throw new AssertionFailedError("Identified bug XXXX"); throw new AssertionFailedError("Identified bug XXXX");
} }
throw e; throw e;
} }
assertEquals("'191219AW4 Corp,[WORKOUT_PX]'", enr.getText()); assertEquals("'191219AW4 Corp,[WORKOUT_PX]'", enr.getText());
assertTrue(enr.isAutomaticLink()); assertTrue(enr.isAutomaticLink());
assertFalse(enr.isBuiltInName()); assertFalse(enr.isBuiltInName());
assertFalse(enr.isIconifiedPictureLink()); assertFalse(enr.isIconifiedPictureLink());
assertFalse(enr.isOLELink()); assertFalse(enr.isOLELink());
assertFalse(enr.isPicureLink()); assertFalse(enr.isPicureLink());
assertTrue(enr.isStdDocumentNameIdentifier()); assertTrue(enr.isStdDocumentNameIdentifier());
TestcaseRecordInputStream.confirmRecordEncoding(0x0023, dataAutoDocName, enr.serialize()); TestcaseRecordInputStream.confirmRecordEncoding(0x0023, dataAutoDocName, enr.serialize());
} }
public void testPlainName() { public void testPlainName() {
ExternalNameRecord enr = createSimpleENR(dataPlainName); ExternalNameRecord enr = createSimpleENR(dataPlainName);
assertEquals("Rate_Date", enr.getText()); assertEquals("Rate_Date", enr.getText());
assertFalse(enr.isAutomaticLink()); assertFalse(enr.isAutomaticLink());
assertFalse(enr.isBuiltInName()); assertFalse(enr.isBuiltInName());
assertFalse(enr.isIconifiedPictureLink()); assertFalse(enr.isIconifiedPictureLink());
assertFalse(enr.isOLELink()); assertFalse(enr.isOLELink());
assertFalse(enr.isPicureLink()); assertFalse(enr.isPicureLink());
assertFalse(enr.isStdDocumentNameIdentifier()); assertFalse(enr.isStdDocumentNameIdentifier());
TestcaseRecordInputStream.confirmRecordEncoding(0x0023, dataPlainName, enr.serialize()); TestcaseRecordInputStream.confirmRecordEncoding(0x0023, dataPlainName, enr.serialize());
} }
} }

View File

@ -1,46 +1,46 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.util.HexRead; import org.apache.poi.util.HexRead;
/** /**
* Tests for {@link StyleRecord} * Tests for {@link StyleRecord}
*/ */
public final class TestStyleRecord extends TestCase { public final class TestStyleRecord extends TestCase {
public void testUnicodeReadName() { public void testUnicodeReadName() {
byte[] data = HexRead.readFromString( byte[] data = HexRead.readFromString(
"11 00 09 00 01 38 5E C4 89 5F 00 53 00 68 00 65 00 65 00 74 00 31 00"); "11 00 09 00 01 38 5E C4 89 5F 00 53 00 68 00 65 00 65 00 74 00 31 00");
RecordInputStream in = TestcaseRecordInputStream.create(StyleRecord.sid, data); RecordInputStream in = TestcaseRecordInputStream.create(StyleRecord.sid, data);
StyleRecord sr = new StyleRecord(in); StyleRecord sr = new StyleRecord(in);
assertEquals("\u5E38\u89C4_Sheet1", sr.getName()); // "<Conventional>_Sheet1" assertEquals("\u5E38\u89C4_Sheet1", sr.getName()); // "<Conventional>_Sheet1"
byte[] ser; byte[] ser;
try { try {
ser = sr.serialize(); ser = sr.serialize();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
if (e.getMessage().equals("Incorrect number of bytes written - expected 27 but got 18")) { if (e.getMessage().equals("Incorrect number of bytes written - expected 27 but got 18")) {
throw new AssertionFailedError("Identified bug 46385"); throw new AssertionFailedError("Identified bug 46385");
} }
throw e; throw e;
} }
TestcaseRecordInputStream.confirmRecordEncoding(StyleRecord.sid, data, ser); TestcaseRecordInputStream.confirmRecordEncoding(StyleRecord.sid, data, ser);
} }
} }

View File

@ -1,196 +1,194 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.util.Arrays; import java.util.Arrays;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.record.formula.Ptg; import org.apache.poi.hssf.record.formula.Ptg;
import org.apache.poi.hssf.record.formula.RefPtg; import org.apache.poi.hssf.record.formula.RefPtg;
import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.util.HexRead; import org.apache.poi.util.HexRead;
import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LittleEndian;
/** /**
* Tests that serialization and deserialization of the TextObjectRecord . * Tests that serialization and deserialization of the TextObjectRecord .
* Test data taken directly from a real Excel file. * Test data taken directly from a real Excel file.
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public final class TestTextObjectRecord extends TestCase { public final class TestTextObjectRecord extends TestCase {
private static final byte[] simpleData = HexRead.readFromString( private static final byte[] simpleData = HexRead.readFromString(
"B6 01 12 00 " + "B6 01 12 00 " +
"12 02 00 00 00 00 00 00" + "12 02 00 00 00 00 00 00" +
"00 00 0D 00 08 00 00 00" + "00 00 0D 00 08 00 00 00" +
"00 00 " + "00 00 " +
"3C 00 0E 00 " + "3C 00 0E 00 " +
"00 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 " + "00 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 " +
"3C 00 08 " + "3C 00 08 " +
"00 0D 00 00 00 00 00 00 00" "00 0D 00 00 00 00 00 00 00"
); );
public void testRead() { public void testRead() {
RecordInputStream is =TestcaseRecordInputStream.create(simpleData); RecordInputStream is =TestcaseRecordInputStream.create(simpleData);
TextObjectRecord record = new TextObjectRecord(is); TextObjectRecord record = new TextObjectRecord(is);
assertEquals(TextObjectRecord.sid, record.getSid()); assertEquals(TextObjectRecord.sid, record.getSid());
assertEquals(TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED, record.getHorizontalTextAlignment()); assertEquals(TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED, record.getHorizontalTextAlignment());
assertEquals(TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_TOP, record.getVerticalTextAlignment()); assertEquals(TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_TOP, record.getVerticalTextAlignment());
assertEquals(TextObjectRecord.TEXT_ORIENTATION_NONE, record.getTextOrientation()); assertEquals(TextObjectRecord.TEXT_ORIENTATION_NONE, record.getTextOrientation());
assertEquals("Hello, World!", record.getStr().getString()); assertEquals("Hello, World!", record.getStr().getString());
} }
public void testWrite() { public void testWrite() {
HSSFRichTextString str = new HSSFRichTextString("Hello, World!"); HSSFRichTextString str = new HSSFRichTextString("Hello, World!");
TextObjectRecord record = new TextObjectRecord(); TextObjectRecord record = new TextObjectRecord();
record.setStr(str); record.setStr(str);
record.setHorizontalTextAlignment( TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED ); record.setHorizontalTextAlignment( TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED );
record.setVerticalTextAlignment( TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_TOP ); record.setVerticalTextAlignment( TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_TOP );
record.setTextLocked( true ); record.setTextLocked( true );
record.setTextOrientation( TextObjectRecord.TEXT_ORIENTATION_NONE ); record.setTextOrientation( TextObjectRecord.TEXT_ORIENTATION_NONE );
byte [] ser = record.serialize(); byte [] ser = record.serialize();
assertEquals(ser.length , simpleData.length); assertEquals(ser.length , simpleData.length);
assertTrue(Arrays.equals(simpleData, ser)); assertTrue(Arrays.equals(simpleData, ser));
//read again //read again
RecordInputStream is = TestcaseRecordInputStream.create(simpleData); RecordInputStream is = TestcaseRecordInputStream.create(simpleData);
record = new TextObjectRecord(is); record = new TextObjectRecord(is);
} }
/** /**
* Zero {@link ContinueRecord}s follow a {@link TextObjectRecord} if the text is empty * Zero {@link ContinueRecord}s follow a {@link TextObjectRecord} if the text is empty
*/ */
public void testWriteEmpty() { public void testWriteEmpty() {
HSSFRichTextString str = new HSSFRichTextString(""); HSSFRichTextString str = new HSSFRichTextString("");
TextObjectRecord record = new TextObjectRecord(); TextObjectRecord record = new TextObjectRecord();
record.setStr(str); record.setStr(str);
byte [] ser = record.serialize(); byte [] ser = record.serialize();
int formatDataLen = LittleEndian.getUShort(ser, 16); int formatDataLen = LittleEndian.getUShort(ser, 16);
assertEquals("formatDataLength", 0, formatDataLen); assertEquals("formatDataLength", 0, formatDataLen);
assertEquals(22, ser.length); // just the TXO record assertEquals(22, ser.length); // just the TXO record
//read again //read again
RecordInputStream is = TestcaseRecordInputStream.create(ser); RecordInputStream is = TestcaseRecordInputStream.create(ser);
record = new TextObjectRecord(is); record = new TextObjectRecord(is);
assertEquals(0, record.getStr().length()); assertEquals(0, record.getStr().length());
} }
/** /**
* Test that TextObjectRecord serializes logs records properly. * Test that TextObjectRecord serializes logs records properly.
*/ */
public void testLongRecords() { public void testLongRecords() {
int[] length = {1024, 2048, 4096, 8192, 16384}; //test against strings of different length int[] length = {1024, 2048, 4096, 8192, 16384}; //test against strings of different length
for (int i = 0; i < length.length; i++) { for (int i = 0; i < length.length; i++) {
StringBuffer buff = new StringBuffer(length[i]); StringBuffer buff = new StringBuffer(length[i]);
for (int j = 0; j < length[i]; j++) { for (int j = 0; j < length[i]; j++) {
buff.append("x"); buff.append("x");
} }
HSSFRichTextString str = new HSSFRichTextString(buff.toString()); HSSFRichTextString str = new HSSFRichTextString(buff.toString());
TextObjectRecord obj = new TextObjectRecord(); TextObjectRecord obj = new TextObjectRecord();
obj.setStr(str); obj.setStr(str);
byte [] data = obj.serialize(); byte [] data = obj.serialize();
RecordInputStream is = new RecordInputStream(new ByteArrayInputStream(data)); RecordInputStream is = new RecordInputStream(new ByteArrayInputStream(data));
is.nextRecord(); is.nextRecord();
TextObjectRecord record = new TextObjectRecord(is); TextObjectRecord record = new TextObjectRecord(is);
str = record.getStr(); str = record.getStr();
assertEquals(buff.length(), str.length()); assertEquals(buff.length(), str.length());
assertEquals(buff.toString(), str.getString()); assertEquals(buff.toString(), str.getString());
} }
}
}
/**
/** * Test cloning
* Test cloning */
*/ public void testClone() {
public void testClone() { String text = "Hello, World";
String text = "Hello, World"; HSSFRichTextString str = new HSSFRichTextString(text);
HSSFRichTextString str = new HSSFRichTextString(text);
TextObjectRecord obj = new TextObjectRecord();
TextObjectRecord obj = new TextObjectRecord(); obj.setStr( str );
obj.setStr( str );
TextObjectRecord cloned = (TextObjectRecord)obj.clone();
TextObjectRecord cloned = (TextObjectRecord)obj.clone(); assertEquals(obj.getRecordSize(), cloned.getRecordSize());
assertEquals(obj.getRecordSize(), cloned.getRecordSize()); assertEquals(obj.getHorizontalTextAlignment(), cloned.getHorizontalTextAlignment());
assertEquals(obj.getHorizontalTextAlignment(), cloned.getHorizontalTextAlignment()); assertEquals(obj.getStr().getString(), cloned.getStr().getString());
assertEquals(obj.getStr().getString(), cloned.getStr().getString());
//finally check that the serialized data is the same
//finally check that the serialized data is the same byte[] src = obj.serialize();
byte[] src = obj.serialize(); byte[] cln = cloned.serialize();
byte[] cln = cloned.serialize(); assertTrue(Arrays.equals(src, cln));
assertTrue(Arrays.equals(src, cln)); }
}
/** similar to {@link #simpleData} but with link formula at end of TXO rec*/
/** similar to {@link #simpleData} but with link formula at end of TXO rec*/ private static final byte[] linkData = HexRead.readFromString(
private static final byte[] linkData = HexRead.readFromString( "B6 01 " + // TextObjectRecord.sid
"B6 01 " + // TextObjectRecord.sid "1E 00 " + // size 18
"1E 00 " + // size 18 "44 02 02 00 00 00 00 00" +
"44 02 02 00 00 00 00 00" + "00 00 " +
"00 00 " + "02 00 " + // strLen 2
"02 00 " + // strLen 2 "10 00 " + // 16 bytes for 2 format runs
"10 00 " + // 16 bytes for 2 format runs "00 00 00 00 " +
"00 00 00 00 " +
"05 00 " + // formula size
"05 00 " + // formula size "D4 F0 8A 03 " + // unknownInt
"D4 F0 8A 03 " + // unknownInt "24 01 00 13 C0 " + //tRef(T2)
"24 01 00 13 C0 " + //tRef(T2) "13 " + // ??
"13 " + // ??
"3C 00 " + // ContinueRecord.sid
"3C 00 " + // ContinueRecord.sid "03 00 " + // size 3
"03 00 " + // size 3 "00 " + // unicode compressed
"00 " + // unicode compressed "41 42 " + // 'AB'
"41 42 " + // 'AB' "3C 00 " + // ContinueRecord.sid
"3C 00 " + // ContinueRecord.sid "10 00 " + // size 16
"10 00 " + // size 16 "00 00 18 00 00 00 00 00 " +
"00 00 18 00 00 00 00 00 " + "02 00 00 00 00 00 00 00 "
"02 00 00 00 00 00 00 00 " );
);
public void testLinkFormula() {
public void testLinkFormula() { RecordInputStream is = new RecordInputStream(new ByteArrayInputStream(linkData));
RecordInputStream is = new RecordInputStream(new ByteArrayInputStream(linkData)); is.nextRecord();
is.nextRecord(); TextObjectRecord rec = new TextObjectRecord(is);
TextObjectRecord rec = new TextObjectRecord(is);
Ptg ptg = rec.getLinkRefPtg();
Ptg ptg = rec.getLinkRefPtg(); assertNotNull(ptg);
assertNotNull(ptg); assertEquals(RefPtg.class, ptg.getClass());
assertEquals(RefPtg.class, ptg.getClass()); RefPtg rptg = (RefPtg) ptg;
RefPtg rptg = (RefPtg) ptg; assertEquals("T2", rptg.toFormulaString());
assertEquals("T2", rptg.toFormulaString());
byte [] data2 = rec.serialize();
byte [] data2 = rec.serialize(); assertEquals(linkData.length, data2.length);
assertEquals(linkData.length, data2.length); assertTrue(Arrays.equals(linkData, data2));
assertTrue(Arrays.equals(linkData, data2)); }
} }
}

View File

@ -1,103 +1,103 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.util.HexRead; import org.apache.poi.util.HexRead;
/** /**
* Tests for {@link WriteAccessRecord} * Tests for {@link WriteAccessRecord}
* *
* @author Josh Micich * @author Josh Micich
*/ */
public final class TestWriteAccessRecord extends TestCase { public final class TestWriteAccessRecord extends TestCase {
private static final String HEX_SIXTYFOUR_SPACES = "" private static final String HEX_SIXTYFOUR_SPACES = ""
+ "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
+ "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
+ "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
+ "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20"; + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20";
public void testMissingStringHeader_bug47001a() { public void testMissingStringHeader_bug47001a() {
/* /*
* Data taken from offset 0x0224 in * Data taken from offset 0x0224 in
* attachment 23468 from bugzilla 47001 * attachment 23468 from bugzilla 47001
*/ */
byte[] data = HexRead.readFromString("" byte[] data = HexRead.readFromString(""
+ "5C 00 70 00 " + "5C 00 70 00 "
+ "4A 61 76 61 20 45 78 63 65 6C 20 41 50 49 20 76 " + "4A 61 76 61 20 45 78 63 65 6C 20 41 50 49 20 76 "
+ "32 2E 36 2E 34" + "32 2E 36 2E 34"
+ "20 20 20 20 20 20 20 20 20 20 20 " + "20 20 20 20 20 20 20 20 20 20 20 "
+ "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
+ HEX_SIXTYFOUR_SPACES); + HEX_SIXTYFOUR_SPACES);
RecordInputStream in = TestcaseRecordInputStream.create(data); RecordInputStream in = TestcaseRecordInputStream.create(data);
WriteAccessRecord rec; WriteAccessRecord rec;
try { try {
rec = new WriteAccessRecord(in); rec = new WriteAccessRecord(in);
} catch (RecordFormatException e) { } catch (RecordFormatException e) {
if (e.getMessage().equals("Not enough data (0) to read requested (1) bytes")) { if (e.getMessage().equals("Not enough data (0) to read requested (1) bytes")) {
throw new AssertionFailedError("Identified bug 47001a"); throw new AssertionFailedError("Identified bug 47001a");
} }
throw e; throw e;
} }
assertEquals("Java Excel API v2.6.4", rec.getUsername()); assertEquals("Java Excel API v2.6.4", rec.getUsername());
byte[] expectedEncoding = HexRead.readFromString("" byte[] expectedEncoding = HexRead.readFromString(""
+ "15 00 00 4A 61 76 61 20 45 78 63 65 6C 20 41 50 " + "15 00 00 4A 61 76 61 20 45 78 63 65 6C 20 41 50 "
+ "49 20 76 32 2E 36 2E 34" + "49 20 76 32 2E 36 2E 34"
+ "20 20 20 20 20 20 20 20 " + "20 20 20 20 20 20 20 20 "
+ "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
+ HEX_SIXTYFOUR_SPACES); + HEX_SIXTYFOUR_SPACES);
TestcaseRecordInputStream.confirmRecordEncoding(WriteAccessRecord.sid, expectedEncoding, rec.serialize()); TestcaseRecordInputStream.confirmRecordEncoding(WriteAccessRecord.sid, expectedEncoding, rec.serialize());
} }
public void testShortRecordWrittenByMSAccess() { public void testShortRecordWrittenByMSAccess() {
/* /*
* Data taken from two example files * Data taken from two example files
* ex42564-21435.xls * ex42564-21435.xls
* bug_42794.xls (from bug 42794 attachment 20429) * bug_42794.xls (from bug 42794 attachment 20429)
* In both cases, this data is found at offset 0x0C1C. * In both cases, this data is found at offset 0x0C1C.
*/ */
byte[] data = HexRead.readFromString("" byte[] data = HexRead.readFromString(""
+ "5C 00 39 00 " + "5C 00 39 00 "
+ "36 00 00 41 20 73 61 74 69 73 66 69 65 64 20 4D " + "36 00 00 41 20 73 61 74 69 73 66 69 65 64 20 4D "
+ "69 63 72 6F 73 6F 66 74 20 4F 66 66 69 63 65 39 " + "69 63 72 6F 73 6F 66 74 20 4F 66 66 69 63 65 39 "
+ "20 55 73 65 72" + "20 55 73 65 72"
+ "20 20 20 20 20 20 20 20 20 20 20 " + "20 20 20 20 20 20 20 20 20 20 20 "
+ "20 20 20 20 20 20 20 20 20"); + "20 20 20 20 20 20 20 20 20");
RecordInputStream in = TestcaseRecordInputStream.create(data); RecordInputStream in = TestcaseRecordInputStream.create(data);
WriteAccessRecord rec = new WriteAccessRecord(in); WriteAccessRecord rec = new WriteAccessRecord(in);
assertEquals("A satisfied Microsoft Office9 User", rec.getUsername()); assertEquals("A satisfied Microsoft Office9 User", rec.getUsername());
byte[] expectedEncoding = HexRead.readFromString("" byte[] expectedEncoding = HexRead.readFromString(""
+ "22 00 00 41 20 73 61 74 69 73 66 69 65 64 20 4D " + "22 00 00 41 20 73 61 74 69 73 66 69 65 64 20 4D "
+ "69 63 72 6F 73 6F 66 74 20 4F 66 66 69 63 65 39 " + "69 63 72 6F 73 6F 66 74 20 4F 66 66 69 63 65 39 "
+ "20 55 73 65 72" + "20 55 73 65 72"
+ "20 20 20 20 20 20 20 20 20 20 20 " + "20 20 20 20 20 20 20 20 20 20 20 "
+ HEX_SIXTYFOUR_SPACES); + HEX_SIXTYFOUR_SPACES);
TestcaseRecordInputStream.confirmRecordEncoding(WriteAccessRecord.sid, expectedEncoding, rec.serialize()); TestcaseRecordInputStream.confirmRecordEncoding(WriteAccessRecord.sid, expectedEncoding, rec.serialize());
} }
} }

View File

@ -1,61 +1,61 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record.chart; package org.apache.poi.hssf.record.chart;
import java.util.Arrays; import java.util.Arrays;
import org.apache.poi.hssf.record.RecordInputStream; import org.apache.poi.hssf.record.RecordInputStream;
import org.apache.poi.hssf.record.TestcaseRecordInputStream; import org.apache.poi.hssf.record.TestcaseRecordInputStream;
import org.apache.poi.util.HexRead; import org.apache.poi.util.HexRead;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
/** /**
* Tests for {@link ChartFormatRecord} Test data taken directly from a real * Tests for {@link ChartFormatRecord} Test data taken directly from a real
* Excel file. * Excel file.
* *
* @author Josh Micich * @author Josh Micich
*/ */
public final class TestChartFormatRecord extends TestCase { public final class TestChartFormatRecord extends TestCase {
/** /**
* This rather uninteresting data came from attachment 23347 of bug 46693 at * This rather uninteresting data came from attachment 23347 of bug 46693 at
* offsets 0x6BB2 and 0x7BAF * offsets 0x6BB2 and 0x7BAF
*/ */
private static final byte[] data = HexRead.readFromString( private static final byte[] data = HexRead.readFromString(
"14 10 14 00 " // BIFF header "14 10 14 00 " // BIFF header
+ "00 00 00 00 00 00 00 00 " + "00 00 00 00 00 00 00 00 "
+ "00 00 00 00 00 00 00 00 " + "00 00 00 00 00 00 00 00 "
+ "00 00 00 00"); + "00 00 00 00");
/** /**
* The correct size of a {@link ChartFormatRecord} is 20 bytes (not including header). * The correct size of a {@link ChartFormatRecord} is 20 bytes (not including header).
*/ */
public void testLoad() { public void testLoad() {
RecordInputStream in = TestcaseRecordInputStream.create(data); RecordInputStream in = TestcaseRecordInputStream.create(data);
ChartFormatRecord record = new ChartFormatRecord(in); ChartFormatRecord record = new ChartFormatRecord(in);
if (in.remaining() == 2) { if (in.remaining() == 2) {
throw new AssertionFailedError("Identified bug 44693d"); throw new AssertionFailedError("Identified bug 44693d");
} }
assertEquals(0, in.remaining()); assertEquals(0, in.remaining());
assertEquals(24, record.getRecordSize()); assertEquals(24, record.getRecordSize());
byte[] data2 = record.serialize(); byte[] data2 = record.serialize();
assertTrue(Arrays.equals(data, data2)); assertTrue(Arrays.equals(data, data2));
} }
} }

View File

@ -1,94 +1,94 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record.formula.eval; package org.apache.poi.hssf.record.formula.eval;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.record.formula.functions.EvalFactory; import org.apache.poi.hssf.record.formula.functions.EvalFactory;
/** /**
* Test for {@link EqualEval} * Test for {@link EqualEval}
* *
* @author Josh Micich * @author Josh Micich
*/ */
public final class TestEqualEval extends TestCase { public final class TestEqualEval extends TestCase {
/** /**
* Test for bug observable at svn revision 692218 (Sep 2008)<br/> * Test for bug observable at svn revision 692218 (Sep 2008)<br/>
* The value from a 1x1 area should be taken immediately, regardless of srcRow and srcCol * The value from a 1x1 area should be taken immediately, regardless of srcRow and srcCol
*/ */
public void test1x1AreaOperand() { public void test1x1AreaOperand() {
ValueEval[] values = { BoolEval.FALSE, }; ValueEval[] values = { BoolEval.FALSE, };
Eval[] args = { Eval[] args = {
EvalFactory.createAreaEval("B1:B1", values), EvalFactory.createAreaEval("B1:B1", values),
BoolEval.FALSE, BoolEval.FALSE,
}; };
Eval result = EqualEval.instance.evaluate(args, 10, (short)20); Eval result = EqualEval.instance.evaluate(args, 10, (short)20);
if (result instanceof ErrorEval) { if (result instanceof ErrorEval) {
if (result == ErrorEval.VALUE_INVALID) { if (result == ErrorEval.VALUE_INVALID) {
throw new AssertionFailedError("Identified bug in evaluation of 1x1 area"); throw new AssertionFailedError("Identified bug in evaluation of 1x1 area");
} }
} }
assertEquals(BoolEval.class, result.getClass()); assertEquals(BoolEval.class, result.getClass());
assertTrue(((BoolEval)result).getBooleanValue()); assertTrue(((BoolEval)result).getBooleanValue());
} }
/** /**
* Empty string is equal to blank * Empty string is equal to blank
*/ */
public void testBlankEqualToEmptyString() { public void testBlankEqualToEmptyString() {
Eval[] args = { Eval[] args = {
new StringEval(""), new StringEval(""),
BlankEval.INSTANCE, BlankEval.INSTANCE,
}; };
Eval result = EqualEval.instance.evaluate(args, 10, (short)20); Eval result = EqualEval.instance.evaluate(args, 10, (short)20);
assertEquals(BoolEval.class, result.getClass()); assertEquals(BoolEval.class, result.getClass());
BoolEval be = (BoolEval) result; BoolEval be = (BoolEval) result;
if (!be.getBooleanValue()) { if (!be.getBooleanValue()) {
throw new AssertionFailedError("Identified bug blank/empty string equality"); throw new AssertionFailedError("Identified bug blank/empty string equality");
} }
assertTrue(be.getBooleanValue()); assertTrue(be.getBooleanValue());
} }
/** /**
* Test for bug 46613 (observable at svn r737248) * Test for bug 46613 (observable at svn r737248)
*/ */
public void testStringInsensitive_bug46613() { public void testStringInsensitive_bug46613() {
if (!evalStringCmp("abc", "aBc", EqualEval.instance)) { if (!evalStringCmp("abc", "aBc", EqualEval.instance)) {
throw new AssertionFailedError("Identified bug 46613"); throw new AssertionFailedError("Identified bug 46613");
} }
assertTrue(evalStringCmp("abc", "aBc", EqualEval.instance)); assertTrue(evalStringCmp("abc", "aBc", EqualEval.instance));
assertTrue(evalStringCmp("ABC", "azz", LessThanEval.instance)); assertTrue(evalStringCmp("ABC", "azz", LessThanEval.instance));
assertTrue(evalStringCmp("abc", "AZZ", LessThanEval.instance)); assertTrue(evalStringCmp("abc", "AZZ", LessThanEval.instance));
assertTrue(evalStringCmp("ABC", "aaa", GreaterThanEval.instance)); assertTrue(evalStringCmp("ABC", "aaa", GreaterThanEval.instance));
assertTrue(evalStringCmp("abc", "AAA", GreaterThanEval.instance)); assertTrue(evalStringCmp("abc", "AAA", GreaterThanEval.instance));
} }
private static boolean evalStringCmp(String a, String b, OperationEval cmpOp) { private static boolean evalStringCmp(String a, String b, OperationEval cmpOp) {
Eval[] args = { Eval[] args = {
new StringEval(a), new StringEval(a),
new StringEval(b), new StringEval(b),
}; };
Eval result = cmpOp.evaluate(args, 10, (short)20); Eval result = cmpOp.evaluate(args, 10, (short)20);
assertEquals(BoolEval.class, result.getClass()); assertEquals(BoolEval.class, result.getClass());
BoolEval be = (BoolEval) result; BoolEval be = (BoolEval) result;
return be.getBooleanValue(); return be.getBooleanValue();
} }
} }

View File

@ -1,232 +1,232 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase; import junit.framework.TestCase;
import java.io.*; import java.io.*;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests HSSFHyperlink. * Tests HSSFHyperlink.
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public final class TestHSSFHyperlink extends TestCase { public final class TestHSSFHyperlink extends TestCase {
/** /**
* Test that we can read hyperlinks. * Test that we can read hyperlinks.
*/ */
public void testRead() { public void testRead() {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
HSSFSheet sheet; HSSFSheet sheet;
HSSFCell cell; HSSFCell cell;
HSSFHyperlink link; HSSFHyperlink link;
sheet = wb.getSheet("WebLinks"); sheet = wb.getSheet("WebLinks");
cell = sheet.getRow(4).getCell(0); cell = sheet.getRow(4).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
assertNotNull(link); assertNotNull(link);
assertEquals("POI", link.getLabel()); assertEquals("POI", link.getLabel());
assertEquals("POI", cell.getRichStringCellValue().getString()); assertEquals("POI", cell.getRichStringCellValue().getString());
assertEquals("http://poi.apache.org/", link.getAddress()); assertEquals("http://poi.apache.org/", link.getAddress());
cell = sheet.getRow(8).getCell(0); cell = sheet.getRow(8).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
assertNotNull(link); assertNotNull(link);
assertEquals("HSSF", link.getLabel()); assertEquals("HSSF", link.getLabel());
assertEquals("HSSF", cell.getRichStringCellValue().getString()); assertEquals("HSSF", cell.getRichStringCellValue().getString());
assertEquals("http://poi.apache.org/hssf/", link.getAddress()); assertEquals("http://poi.apache.org/hssf/", link.getAddress());
sheet = wb.getSheet("Emails"); sheet = wb.getSheet("Emails");
cell = sheet.getRow(4).getCell(0); cell = sheet.getRow(4).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
assertNotNull(link); assertNotNull(link);
assertEquals("dev", link.getLabel()); assertEquals("dev", link.getLabel());
assertEquals("dev", cell.getRichStringCellValue().getString()); assertEquals("dev", cell.getRichStringCellValue().getString());
assertEquals("mailto:dev@poi.apache.org", link.getAddress()); assertEquals("mailto:dev@poi.apache.org", link.getAddress());
sheet = wb.getSheet("Internal"); sheet = wb.getSheet("Internal");
cell = sheet.getRow(4).getCell(0); cell = sheet.getRow(4).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
assertNotNull(link); assertNotNull(link);
assertEquals("Link To First Sheet", link.getLabel()); assertEquals("Link To First Sheet", link.getLabel());
assertEquals("Link To First Sheet", cell.getRichStringCellValue().getString()); assertEquals("Link To First Sheet", cell.getRichStringCellValue().getString());
assertEquals("WebLinks!A1", link.getTextMark()); assertEquals("WebLinks!A1", link.getTextMark());
} }
public void testModify() throws Exception { public void testModify() throws Exception {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
HSSFSheet sheet; HSSFSheet sheet;
HSSFCell cell; HSSFCell cell;
HSSFHyperlink link; HSSFHyperlink link;
sheet = wb.getSheet("WebLinks"); sheet = wb.getSheet("WebLinks");
cell = sheet.getRow(4).getCell(0); cell = sheet.getRow(4).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
//modify the link //modify the link
link.setAddress("www.apache.org"); link.setAddress("www.apache.org");
//serialize and read again //serialize and read again
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
wb.write(out); wb.write(out);
wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray()));
sheet = wb.getSheet("WebLinks"); sheet = wb.getSheet("WebLinks");
cell = sheet.getRow(4).getCell(0); cell = sheet.getRow(4).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
assertNotNull(link); assertNotNull(link);
assertEquals("www.apache.org", link.getAddress()); assertEquals("www.apache.org", link.getAddress());
} }
public void testCreate() throws Exception { public void testCreate() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFCell cell; HSSFCell cell;
HSSFSheet sheet = wb.createSheet("Hyperlinks"); HSSFSheet sheet = wb.createSheet("Hyperlinks");
//URL //URL
cell = sheet.createRow(0).createCell(0); cell = sheet.createRow(0).createCell(0);
cell.setCellValue("URL Link"); cell.setCellValue("URL Link");
HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL); HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
link.setAddress("http://poi.apache.org/"); link.setAddress("http://poi.apache.org/");
cell.setHyperlink(link); cell.setHyperlink(link);
//link to a file in the current directory //link to a file in the current directory
cell = sheet.createRow(1).createCell(0); cell = sheet.createRow(1).createCell(0);
cell.setCellValue("File Link"); cell.setCellValue("File Link");
link = new HSSFHyperlink(HSSFHyperlink.LINK_FILE); link = new HSSFHyperlink(HSSFHyperlink.LINK_FILE);
link.setAddress("link1.xls"); link.setAddress("link1.xls");
cell.setHyperlink(link); cell.setHyperlink(link);
//e-mail link //e-mail link
cell = sheet.createRow(2).createCell(0); cell = sheet.createRow(2).createCell(0);
cell.setCellValue("Email Link"); cell.setCellValue("Email Link");
link = new HSSFHyperlink(HSSFHyperlink.LINK_EMAIL); link = new HSSFHyperlink(HSSFHyperlink.LINK_EMAIL);
//note, if subject contains white spaces, make sure they are url-encoded //note, if subject contains white spaces, make sure they are url-encoded
link.setAddress("mailto:poi@apache.org?subject=Hyperlinks"); link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
cell.setHyperlink(link); cell.setHyperlink(link);
//link to a place in this workbook //link to a place in this workbook
//create a target sheet and cell //create a target sheet and cell
HSSFSheet sheet2 = wb.createSheet("Target Sheet"); HSSFSheet sheet2 = wb.createSheet("Target Sheet");
sheet2.createRow(0).createCell(0).setCellValue("Target Cell"); sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
cell = sheet.createRow(3).createCell(0); cell = sheet.createRow(3).createCell(0);
cell.setCellValue("Worksheet Link"); cell.setCellValue("Worksheet Link");
link = new HSSFHyperlink(HSSFHyperlink.LINK_DOCUMENT); link = new HSSFHyperlink(HSSFHyperlink.LINK_DOCUMENT);
link.setTextMark("'Target Sheet'!A1"); link.setTextMark("'Target Sheet'!A1");
cell.setHyperlink(link); cell.setHyperlink(link);
//serialize and read again //serialize and read again
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
wb.write(out); wb.write(out);
wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); wb = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray()));
sheet = wb.getSheet("Hyperlinks"); sheet = wb.getSheet("Hyperlinks");
cell = sheet.getRow(0).getCell(0); cell = sheet.getRow(0).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
assertNotNull(link); assertNotNull(link);
assertEquals("http://poi.apache.org/", link.getAddress()); assertEquals("http://poi.apache.org/", link.getAddress());
cell = sheet.getRow(1).getCell(0); cell = sheet.getRow(1).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
assertNotNull(link); assertNotNull(link);
assertEquals("link1.xls", link.getAddress()); assertEquals("link1.xls", link.getAddress());
cell = sheet.getRow(2).getCell(0); cell = sheet.getRow(2).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
assertNotNull(link); assertNotNull(link);
assertEquals("mailto:poi@apache.org?subject=Hyperlinks", link.getAddress()); assertEquals("mailto:poi@apache.org?subject=Hyperlinks", link.getAddress());
cell = sheet.getRow(3).getCell(0); cell = sheet.getRow(3).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
assertNotNull(link); assertNotNull(link);
assertEquals("'Target Sheet'!A1", link.getTextMark()); assertEquals("'Target Sheet'!A1", link.getTextMark());
} }
public void testCloneSheet() { public void testCloneSheet() {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
HSSFCell cell; HSSFCell cell;
HSSFHyperlink link; HSSFHyperlink link;
HSSFSheet sheet = wb.cloneSheet(0); HSSFSheet sheet = wb.cloneSheet(0);
cell = sheet.getRow(4).getCell(0); cell = sheet.getRow(4).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
assertNotNull(link); assertNotNull(link);
assertEquals("http://poi.apache.org/", link.getAddress()); assertEquals("http://poi.apache.org/", link.getAddress());
cell = sheet.getRow(8).getCell(0); cell = sheet.getRow(8).getCell(0);
link = cell.getHyperlink(); link = cell.getHyperlink();
assertNotNull(link); assertNotNull(link);
assertEquals("http://poi.apache.org/hssf/", link.getAddress()); assertEquals("http://poi.apache.org/hssf/", link.getAddress());
} }
/** /**
* Test that HSSFSheet#shiftRows moves hyperlinks, * Test that HSSFSheet#shiftRows moves hyperlinks,
* see bugs #46445 and #29957 * see bugs #46445 and #29957
*/ */
public void testShiftRows(){ public void testShiftRows(){
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("46445.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("46445.xls");
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);
//verify existing hyperlink in A3 //verify existing hyperlink in A3
HSSFCell cell1 = sheet.getRow(2).getCell(0); HSSFCell cell1 = sheet.getRow(2).getCell(0);
HSSFHyperlink link1 = cell1.getHyperlink(); HSSFHyperlink link1 = cell1.getHyperlink();
assertNotNull(link1); assertNotNull(link1);
assertEquals(2, link1.getFirstRow()); assertEquals(2, link1.getFirstRow());
assertEquals(2, link1.getLastRow()); assertEquals(2, link1.getLastRow());
//assign a hyperlink to A4 //assign a hyperlink to A4
HSSFHyperlink link2 = new HSSFHyperlink(HSSFHyperlink.LINK_DOCUMENT); HSSFHyperlink link2 = new HSSFHyperlink(HSSFHyperlink.LINK_DOCUMENT);
link2.setAddress("Sheet2!A2"); link2.setAddress("Sheet2!A2");
HSSFCell cell2 = sheet.getRow(3).getCell(0); HSSFCell cell2 = sheet.getRow(3).getCell(0);
cell2.setHyperlink(link2); cell2.setHyperlink(link2);
assertEquals(3, link2.getFirstRow()); assertEquals(3, link2.getFirstRow());
assertEquals(3, link2.getLastRow()); assertEquals(3, link2.getLastRow());
//move the 3rd row two rows down //move the 3rd row two rows down
sheet.shiftRows(sheet.getFirstRowNum(), sheet.getLastRowNum(), 2); sheet.shiftRows(sheet.getFirstRowNum(), sheet.getLastRowNum(), 2);
//cells A3 and A4 don't contain hyperlinks anymore //cells A3 and A4 don't contain hyperlinks anymore
assertNull(sheet.getRow(2).getCell(0).getHyperlink()); assertNull(sheet.getRow(2).getCell(0).getHyperlink());
assertNull(sheet.getRow(3).getCell(0).getHyperlink()); assertNull(sheet.getRow(3).getCell(0).getHyperlink());
//the first hypelink now belongs to A5 //the first hypelink now belongs to A5
HSSFHyperlink link1_shifted = sheet.getRow(2+2).getCell(0).getHyperlink(); HSSFHyperlink link1_shifted = sheet.getRow(2+2).getCell(0).getHyperlink();
assertNotNull(link1_shifted); assertNotNull(link1_shifted);
assertEquals(4, link1_shifted.getFirstRow()); assertEquals(4, link1_shifted.getFirstRow());
assertEquals(4, link1_shifted.getLastRow()); assertEquals(4, link1_shifted.getLastRow());
//the second hypelink now belongs to A6 //the second hypelink now belongs to A6
HSSFHyperlink link2_shifted = sheet.getRow(3+2).getCell(0).getHyperlink(); HSSFHyperlink link2_shifted = sheet.getRow(3+2).getCell(0).getHyperlink();
assertNotNull(link2_shifted); assertNotNull(link2_shifted);
assertEquals(5, link2_shifted.getFirstRow()); assertEquals(5, link2_shifted.getFirstRow());
assertEquals(5, link2_shifted.getLastRow()); assertEquals(5, link2_shifted.getLastRow());
} }
} }

View File

@ -1,71 +1,69 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
/** /**
* @author Josh Micich * @author Josh Micich
*/ */
public final class TestHSSFPatriarch extends TestCase { public final class TestHSSFPatriarch extends TestCase {
public void testBasic() { public void testBasic() {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(); HSSFSheet sheet = wb.createSheet();
HSSFPatriarch patr = sheet.createDrawingPatriarch(); HSSFPatriarch patr = sheet.createDrawingPatriarch();
assertNotNull(patr);
assertNotNull(patr);
// assert something more interesting
// assert something more interesting }
}
// TODO - fix bug 44916 (1-May-2008)
// TODO - fix bug 44916 (1-May-2008) public void DISABLED_test44916() {
public void DISABLED_test44916() {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet();
HSSFSheet sheet = wb.createSheet();
// 1. Create drawing patriarch
// 1. Create drawing patriarch HSSFPatriarch patr = sheet.createDrawingPatriarch();
HSSFPatriarch patr = sheet.createDrawingPatriarch();
// 2. Try to re-get the patriarch
// 2. Try to re-get the patriarch HSSFPatriarch existingPatr;
HSSFPatriarch existingPatr; try {
try { existingPatr = sheet.getDrawingPatriarch();
existingPatr = sheet.getDrawingPatriarch(); } catch (NullPointerException e) {
} catch (NullPointerException e) { throw new AssertionFailedError("Identified bug 44916");
throw new AssertionFailedError("Identified bug 44916"); }
}
// 3. Use patriarch
// 3. Use patriarch HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 600, 245, (short) 1, 1, (short) 1, 2);
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 600, 245, (short) 1, 1, (short) 1, 2); anchor.setAnchorType(3);
anchor.setAnchorType(3); byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png");
byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png"); int idx1 = wb.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG);
int idx1 = wb.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG); patr.createPicture(anchor, idx1);
patr.createPicture(anchor, idx1);
// 4. Try to re-use patriarch later
// 4. Try to re-use patriarch later existingPatr = sheet.getDrawingPatriarch();
existingPatr = sheet.getDrawingPatriarch(); assertNotNull(existingPatr);
assertNotNull(existingPatr); }
} }
}

View File

@ -1,54 +1,54 @@
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.ss.usermodel.BaseTestPicture; import org.apache.poi.ss.usermodel.BaseTestPicture;
/** /**
* Test <code>HSSFPicture</code>. * Test <code>HSSFPicture</code>.
* *
* @author Yegor Kozlov (yegor at apache.org) * @author Yegor Kozlov (yegor at apache.org)
*/ */
public final class TestHSSFPicture extends BaseTestPicture { public final class TestHSSFPicture extends BaseTestPicture {
@Override @Override
protected HSSFITestDataProvider getTestDataProvider(){ protected HSSFITestDataProvider getTestDataProvider(){
return HSSFITestDataProvider.getInstance(); return HSSFITestDataProvider.getInstance();
} }
public void testResize() { public void testResize() {
baseTestResize(new HSSFClientAnchor(0, 0, 848, 240, (short)0, 0, (short)1, 9)); baseTestResize(new HSSFClientAnchor(0, 0, 848, 240, (short)0, 0, (short)1, 9));
} }
/** /**
* Bug # 45829 reported ArithmeticException (/ by zero) when resizing png with zero DPI. * Bug # 45829 reported ArithmeticException (/ by zero) when resizing png with zero DPI.
*/ */
public void test45829() { public void test45829() {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sh1 = wb.createSheet(); HSSFSheet sh1 = wb.createSheet();
HSSFPatriarch p1 = sh1.createDrawingPatriarch(); HSSFPatriarch p1 = sh1.createDrawingPatriarch();
byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("45829.png"); byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("45829.png");
int idx1 = wb.addPicture( pictureData, HSSFWorkbook.PICTURE_TYPE_PNG ); int idx1 = wb.addPicture( pictureData, HSSFWorkbook.PICTURE_TYPE_PNG );
HSSFPicture pic = p1.createPicture(new HSSFClientAnchor(), idx1); HSSFPicture pic = p1.createPicture(new HSSFClientAnchor(), idx1);
pic.resize(); pic.resize();
} }
} }

View File

@ -1,71 +1,72 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Test <code>HSSFPictureData</code>. * Test <code>HSSFPictureData</code>.
* The code to retrieve images from a workbook provided by Trejkaz (trejkaz at trypticon dot org) in Bug 41223. * The code to retrieve images from a workbook provided by Trejkaz (trejkaz at trypticon dot org) in Bug 41223.
* *
* @author Yegor Kozlov (yegor at apache dot org) * @author Yegor Kozlov (yegor at apache dot org)
* @author Trejkaz (trejkaz at trypticon dot org) * @author Trejkaz (trejkaz at trypticon dot org)
*/ */
public final class TestHSSFPictureData extends TestCase{ public final class TestHSSFPictureData extends TestCase{
public void testPictures() throws IOException { public void testPictures() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithImages.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithImages.xls");
List lst = wb.getAllPictures(); @SuppressWarnings("unchecked") // TODO - add getFormat() to interface PictureData and genericise wb.getAllPictures()
//assertEquals(2, lst.size()); List<HSSFPictureData> lst = (List<HSSFPictureData>)(List<?>)wb.getAllPictures();
//assertEquals(2, lst.size());
for (Iterator it = lst.iterator(); it.hasNext(); ) {
HSSFPictureData pict = (HSSFPictureData)it.next(); for (Iterator it = lst.iterator(); it.hasNext(); ) {
String ext = pict.suggestFileExtension(); HSSFPictureData pict = (HSSFPictureData)it.next();
byte[] data = pict.getData(); String ext = pict.suggestFileExtension();
if (ext.equals("jpeg")){ byte[] data = pict.getData();
//try to read image data using javax.imageio.* (JDK 1.4+) if (ext.equals("jpeg")){
BufferedImage jpg = ImageIO.read(new ByteArrayInputStream(data)); //try to read image data using javax.imageio.* (JDK 1.4+)
assertNotNull(jpg); BufferedImage jpg = ImageIO.read(new ByteArrayInputStream(data));
assertEquals(192, jpg.getWidth()); assertNotNull(jpg);
assertEquals(176, jpg.getHeight()); assertEquals(192, jpg.getWidth());
assertEquals(HSSFWorkbook.PICTURE_TYPE_JPEG, pict.getFormat()); assertEquals(176, jpg.getHeight());
} else if (ext.equals("png")){ assertEquals(HSSFWorkbook.PICTURE_TYPE_JPEG, pict.getFormat());
//try to read image data using javax.imageio.* (JDK 1.4+) } else if (ext.equals("png")){
BufferedImage png = ImageIO.read(new ByteArrayInputStream(data)); //try to read image data using javax.imageio.* (JDK 1.4+)
assertNotNull(png); BufferedImage png = ImageIO.read(new ByteArrayInputStream(data));
assertEquals(300, png.getWidth()); assertNotNull(png);
assertEquals(300, png.getHeight()); assertEquals(300, png.getWidth());
assertEquals(HSSFWorkbook.PICTURE_TYPE_PNG, pict.getFormat()); assertEquals(300, png.getHeight());
} else { assertEquals(HSSFWorkbook.PICTURE_TYPE_PNG, pict.getFormat());
//TODO: test code for PICT, WMF and EMF } else {
} //TODO: test code for PICT, WMF and EMF
} }
} }
} }
}

View File

@ -1,71 +1,65 @@
/* /* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and See the License for the specific language governing permissions and
* limitations under the License. limitations under the License.
*/ ==================================================================== */
package org.apache.poi.hssf.usermodel;
package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayOutputStream;
import java.io.File; import junit.framework.TestCase;
import java.io.FileInputStream;
import java.io.IOException; /**
import java.io.InputStream; * Test <code>HSSFTextbox</code>.
*
import junit.framework.TestCase; * @author Yegor Kozlov (yegor at apache.org)
*/
/** public final class TestHSSFTextbox extends TestCase{
* Test <code>HSSFTextbox</code>.
* /**
* @author Yegor Kozlov (yegor at apache.org) * Test that accessors to horizontal and vertical alignment work properly
*/ */
public final class TestHSSFTextbox extends TestCase{ public void testAlignment() {
HSSFWorkbook wb = new HSSFWorkbook();
/** HSSFSheet sh1 = wb.createSheet();
* Test that accessors to horizontal and vertical alignment work properly HSSFPatriarch patriarch = sh1.createDrawingPatriarch();
*/
public void testAlignment() { HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 6, 4));
HSSFWorkbook wb = new HSSFWorkbook(); HSSFRichTextString str = new HSSFRichTextString("Hello, World");
HSSFSheet sh1 = wb.createSheet(); textbox.setString(str);
HSSFPatriarch patriarch = sh1.createDrawingPatriarch(); textbox.setHorizontalAlignment(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED);
textbox.setVerticalAlignment(HSSFTextbox.VERTICAL_ALIGNMENT_CENTER);
HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 6, 4));
HSSFRichTextString str = new HSSFRichTextString("Hello, World"); assertEquals(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED, textbox.getHorizontalAlignment());
textbox.setString(str); assertEquals(HSSFTextbox.VERTICAL_ALIGNMENT_CENTER, textbox.getVerticalAlignment());
textbox.setHorizontalAlignment(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED); }
textbox.setVerticalAlignment(HSSFTextbox.VERTICAL_ALIGNMENT_CENTER);
/**
assertEquals(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED, textbox.getHorizontalAlignment()); * Excel requires at least one format run in HSSFTextbox.
assertEquals(HSSFTextbox.VERTICAL_ALIGNMENT_CENTER, textbox.getVerticalAlignment()); * When inserting text make sure that if font is not set we must set the default one.
} */
public void testSetDeafultTextFormat() {
/** HSSFWorkbook wb = new HSSFWorkbook();
* Excel requires at least one format run in HSSFTextbox. HSSFSheet sheet = wb.createSheet();
* When inserting text make sure that if font is not set we must set the default one. HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
*/
public void testSetDeafultTextFormat() { HSSFTextbox textbox1 = patriarch.createTextbox(new HSSFClientAnchor(0,0,0,0,(short)1,1,(short)3,3));
HSSFWorkbook wb = new HSSFWorkbook(); HSSFRichTextString rt1 = new HSSFRichTextString("Hello, World!");
HSSFSheet sheet = wb.createSheet(); assertEquals(0, rt1.numFormattingRuns());
HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); textbox1.setString(rt1);
HSSFTextbox textbox1 = patriarch.createTextbox(new HSSFClientAnchor(0,0,0,0,(short)1,1,(short)3,3)); HSSFRichTextString rt2 = textbox1.getString();
HSSFRichTextString rt1 = new HSSFRichTextString("Hello, World!"); assertEquals(1, rt2.numFormattingRuns());
assertEquals(0, rt1.numFormattingRuns()); assertEquals(HSSFRichTextString.NO_FONT, rt2.getFontOfFormattingRun(0));
textbox1.setString(rt1); }
}
HSSFRichTextString rt2 = textbox1.getString();
assertEquals(1, rt2.numFormattingRuns());
assertEquals(HSSFRichTextString.NO_FONT, rt2.getFontOfFormattingRun(0));
}
}

View File

@ -1,55 +1,56 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.ss;
package org.apache.poi.ss;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Workbook;
/**
* Incapsulates a provider of test data for common HSSF / XSSF tests. /**
*/ * Encapsulates a provider of test data for common HSSF / XSSF tests.
public interface ITestDataProvider { */
/** public interface ITestDataProvider {
* Override to provide HSSF / XSSF specific way for re-serialising a workbook /**
* * Override to provide HSSF / XSSF specific way for re-serialising a workbook
* @param wb the workbook to re-serialize *
* @return the re-serialized workbook * @param wb the workbook to re-serialize
*/ * @return the re-serialized workbook
Workbook writeOutAndReadBack(Workbook wb); */
Workbook writeOutAndReadBack(Workbook wb);
/**
* Override to provide way of loading HSSF / XSSF sample workbooks /**
* * Override to provide way of loading HSSF / XSSF sample workbooks
* @param sampleFileName the file name to load *
* @return an instance of Workbook loaded from the supplied file name * @param sampleFileName the file name to load
*/ * @return an instance of Workbook loaded from the supplied file name
Workbook openSampleWorkbook(String sampleFileName); */
Workbook openSampleWorkbook(String sampleFileName);
/**
* Override to provide way of creating HSSF / XSSF workbooks /**
* @return an instance of Workbook * Override to provide way of creating HSSF / XSSF workbooks
*/ * @return an instance of Workbook
Workbook createWorkbook(); */
Workbook createWorkbook();
/**
* Opens a sample file from the standard HSSF test data directory /**
* * Opens a sample file from the standard HSSF test data directory
* @return an open <tt>InputStream</tt> for the specified sample file *
*/ * @return an open <tt>InputStream</tt> for the specified sample file
byte[] getTestDataFileContent(String fileName); */
byte[] getTestDataFileContent(String fileName);
SpreadsheetVersion getSpreadsheetVersion();
} SpreadsheetVersion getSpreadsheetVersion();
}

View File

@ -1,49 +1,50 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.ss;
package org.apache.poi.ss;
import junit.framework.TestCase;
import junit.framework.TestCase;
/**
* Check that all enum values are properly set /**
* * Check that all enum values are properly set
* @author Yegor Kozlov *
*/ * @author Yegor Kozlov
public class TestSpreadsheetVersion extends TestCase { */
public final class TestSpreadsheetVersion extends TestCase {
public void testExcel97(){
SpreadsheetVersion v = SpreadsheetVersion.EXCEL97; public void testExcel97(){
assertEquals(1 << 8, v.getMaxColumns()); SpreadsheetVersion v = SpreadsheetVersion.EXCEL97;
assertEquals(v.getMaxColumns() - 1, v.getLastColumnIndex()); assertEquals(1 << 8, v.getMaxColumns());
assertEquals(1 << 16, v.getMaxRows()); assertEquals(v.getMaxColumns() - 1, v.getLastColumnIndex());
assertEquals(v.getMaxRows() - 1, v.getLastRowIndex()); assertEquals(1 << 16, v.getMaxRows());
assertEquals(30, v.getMaxFunctionArgs()); assertEquals(v.getMaxRows() - 1, v.getLastRowIndex());
assertEquals(3, v.getMaxConditionalFormats()); assertEquals(30, v.getMaxFunctionArgs());
assertEquals("IV", v.getLastColumnName()); assertEquals(3, v.getMaxConditionalFormats());
} assertEquals("IV", v.getLastColumnName());
}
public void testExcel2007(){
SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007; public void testExcel2007(){
assertEquals(1 << 14, v.getMaxColumns()); SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007;
assertEquals(v.getMaxColumns() - 1, v.getLastColumnIndex()); assertEquals(1 << 14, v.getMaxColumns());
assertEquals(1 << 20, v.getMaxRows()); assertEquals(v.getMaxColumns() - 1, v.getLastColumnIndex());
assertEquals(v.getMaxRows() - 1, v.getLastRowIndex()); assertEquals(1 << 20, v.getMaxRows());
assertEquals(255, v.getMaxFunctionArgs()); assertEquals(v.getMaxRows() - 1, v.getLastRowIndex());
assertEquals(Integer.MAX_VALUE, v.getMaxConditionalFormats()); assertEquals(255, v.getMaxFunctionArgs());
assertEquals("XFD", v.getLastColumnName()); assertEquals(Integer.MAX_VALUE, v.getMaxConditionalFormats());
} assertEquals("XFD", v.getLastColumnName());
} }
}

View File

@ -1,55 +1,55 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.ss.formula; package org.apache.poi.ss.formula;
import junit.framework.Assert; import junit.framework.Assert;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import org.apache.poi.ss.formula.FormulaParser.FormulaParseException; import org.apache.poi.ss.formula.FormulaParser.FormulaParseException;
/** /**
* Avoids making {@link FormulaParseException} public * Avoids making {@link FormulaParseException} public
* *
* @author Josh Micich * @author Josh Micich
*/ */
public class FormulaParserTestHelper { public class FormulaParserTestHelper {
/** /**
* @throws AssertionFailedError if <tt>e</tt> is not a formula parser exception * @throws AssertionFailedError if <tt>e</tt> is not a formula parser exception
* or if the exception message doesn't match. * or if the exception message doesn't match.
*/ */
public static void confirmParseException(RuntimeException e, String expectedMessage) { public static void confirmParseException(RuntimeException e, String expectedMessage) {
checkType(e); checkType(e);
Assert.assertEquals(expectedMessage, e.getMessage()); Assert.assertEquals(expectedMessage, e.getMessage());
} }
/** /**
* @throws AssertionFailedError if <tt>e</tt> is not a formula parser exception * @throws AssertionFailedError if <tt>e</tt> is not a formula parser exception
* or if <tt>e</tt> has no message. * or if <tt>e</tt> has no message.
*/ */
public static void confirmParseException(RuntimeException e) { public static void confirmParseException(RuntimeException e) {
checkType(e); checkType(e);
Assert.assertNotNull(e.getMessage()); Assert.assertNotNull(e.getMessage());
} }
private static void checkType(RuntimeException e) throws AssertionFailedError { private static void checkType(RuntimeException e) throws AssertionFailedError {
if (!(e instanceof FormulaParseException)) { if (!(e instanceof FormulaParseException)) {
String failMsg = "Expected FormulaParseException, but got (" String failMsg = "Expected FormulaParseException, but got ("
+ e.getClass().getName() + "):"; + e.getClass().getName() + "):";
System.err.println(failMsg); System.err.println(failMsg);
e.printStackTrace(); e.printStackTrace();
throw new AssertionFailedError(failMsg); throw new AssertionFailedError(failMsg);
} }
} }
} }

View File

@ -1,336 +1,337 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.ss.usermodel;
package org.apache.poi.ss.usermodel;
import junit.framework.TestCase;
import org.apache.poi.ss.ITestDataProvider; import junit.framework.TestCase;
import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.util.CellRangeAddress;
/**
* A base class for bugzilla issues that can be described in terms of common ss interfaces. /**
* * A base class for bugzilla issues that can be described in terms of common ss interfaces.
* @author Yegor Kozlov *
*/ * @author Yegor Kozlov
public abstract class BaseTestBugzillaIssues extends TestCase { */
public abstract class BaseTestBugzillaIssues extends TestCase {
protected abstract ITestDataProvider getTestDataProvider();
protected abstract ITestDataProvider getTestDataProvider();
/**
* /**
* Test writing a hyperlink *
* Open resulting sheet in Excel and check that A1 contains a hyperlink * Test writing a hyperlink
* * Open resulting sheet in Excel and check that A1 contains a hyperlink
* Also tests bug 15353 (problems with hyperlinks to Google) *
*/ * Also tests bug 15353 (problems with hyperlinks to Google)
public void test23094() { */
Workbook wb = getTestDataProvider().createWorkbook(); public void test23094() {
Sheet s = wb.createSheet(); Workbook wb = getTestDataProvider().createWorkbook();
Row r = s.createRow(0); Sheet s = wb.createSheet();
r.createCell(0).setCellFormula("HYPERLINK(\"http://jakarta.apache.org\",\"Jakarta\")"); Row r = s.createRow(0);
r.createCell(1).setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")"); r.createCell(0).setCellFormula("HYPERLINK(\"http://jakarta.apache.org\",\"Jakarta\")");
r.createCell(1).setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")");
wb = getTestDataProvider().writeOutAndReadBack(wb);
r = wb.getSheetAt(0).getRow(0); wb = getTestDataProvider().writeOutAndReadBack(wb);
r = wb.getSheetAt(0).getRow(0);
Cell cell_0 = r.getCell(0);
assertEquals("HYPERLINK(\"http://jakarta.apache.org\",\"Jakarta\")", cell_0.getCellFormula()); Cell cell_0 = r.getCell(0);
Cell cell_1 = r.getCell(1); assertEquals("HYPERLINK(\"http://jakarta.apache.org\",\"Jakarta\")", cell_0.getCellFormula());
assertEquals("HYPERLINK(\"http://google.com\",\"Google\")", cell_1.getCellFormula()); Cell cell_1 = r.getCell(1);
} assertEquals("HYPERLINK(\"http://google.com\",\"Google\")", cell_1.getCellFormula());
}
/**
* test writing a file with large number of unique strings, /**
* open resulting file in Excel to check results! * test writing a file with large number of unique strings,
* @param num the number of strings to generate * open resulting file in Excel to check results!
*/ * @param num the number of strings to generate
public void baseTest15375(int num) { */
Workbook wb = getTestDataProvider().createWorkbook(); public void baseTest15375(int num) {
Sheet sheet = wb.createSheet(); Workbook wb = getTestDataProvider().createWorkbook();
CreationHelper factory = wb.getCreationHelper(); Sheet sheet = wb.createSheet();
CreationHelper factory = wb.getCreationHelper();
String tmp1 = null;
String tmp2 = null; String tmp1 = null;
String tmp3 = null; String tmp2 = null;
String tmp3 = null;
for (int i = 0; i < num; i++) {
tmp1 = "Test1" + i; for (int i = 0; i < num; i++) {
tmp2 = "Test2" + i; tmp1 = "Test1" + i;
tmp3 = "Test3" + i; tmp2 = "Test2" + i;
tmp3 = "Test3" + i;
Row row = sheet.createRow(i);
Row row = sheet.createRow(i);
Cell cell = row.createCell(0);
cell.setCellValue(factory.createRichTextString(tmp1)); Cell cell = row.createCell(0);
cell = row.createCell(1); cell.setCellValue(factory.createRichTextString(tmp1));
cell.setCellValue(factory.createRichTextString(tmp2)); cell = row.createCell(1);
cell = row.createCell(2); cell.setCellValue(factory.createRichTextString(tmp2));
cell.setCellValue(factory.createRichTextString(tmp3)); cell = row.createCell(2);
} cell.setCellValue(factory.createRichTextString(tmp3));
wb = getTestDataProvider().writeOutAndReadBack(wb); }
for (int i = 0; i < num; i++) { wb = getTestDataProvider().writeOutAndReadBack(wb);
tmp1 = "Test1" + i; for (int i = 0; i < num; i++) {
tmp2 = "Test2" + i; tmp1 = "Test1" + i;
tmp3 = "Test3" + i; tmp2 = "Test2" + i;
tmp3 = "Test3" + i;
Row row = sheet.getRow(i);
Row row = sheet.getRow(i);
assertEquals(tmp1, row.getCell(0).getStringCellValue());
assertEquals(tmp2, row.getCell(1).getStringCellValue()); assertEquals(tmp1, row.getCell(0).getStringCellValue());
assertEquals(tmp3, row.getCell(2).getStringCellValue()); assertEquals(tmp2, row.getCell(1).getStringCellValue());
} assertEquals(tmp3, row.getCell(2).getStringCellValue());
} }
}
/**
* Merged regions were being removed from the parent in cloned sheets /**
*/ * Merged regions were being removed from the parent in cloned sheets
public void test22720() { */
Workbook workBook = getTestDataProvider().createWorkbook(); public void test22720() {
workBook.createSheet("TEST"); Workbook workBook = getTestDataProvider().createWorkbook();
Sheet template = workBook.getSheetAt(0); workBook.createSheet("TEST");
Sheet template = workBook.getSheetAt(0);
template.addMergedRegion(new CellRangeAddress(0, 1, 0, 2));
template.addMergedRegion(new CellRangeAddress(1, 2, 0, 2)); template.addMergedRegion(new CellRangeAddress(0, 1, 0, 2));
template.addMergedRegion(new CellRangeAddress(1, 2, 0, 2));
Sheet clone = workBook.cloneSheet(0);
int originalMerged = template.getNumMergedRegions(); Sheet clone = workBook.cloneSheet(0);
assertEquals("2 merged regions", 2, originalMerged); int originalMerged = template.getNumMergedRegions();
assertEquals("2 merged regions", 2, originalMerged);
//remove merged regions from clone
for (int i=template.getNumMergedRegions()-1; i>=0; i--) { //remove merged regions from clone
clone.removeMergedRegion(i); for (int i=template.getNumMergedRegions()-1; i>=0; i--) {
} clone.removeMergedRegion(i);
}
assertEquals("Original Sheet's Merged Regions were removed", originalMerged, template.getNumMergedRegions());
//check if template's merged regions are OK assertEquals("Original Sheet's Merged Regions were removed", originalMerged, template.getNumMergedRegions());
if (template.getNumMergedRegions()>0) { //check if template's merged regions are OK
// fetch the first merged region...EXCEPTION OCCURS HERE if (template.getNumMergedRegions()>0) {
template.getMergedRegion(0); // fetch the first merged region...EXCEPTION OCCURS HERE
} template.getMergedRegion(0);
//make sure we dont exception }
//make sure we dont exception
}
}
public void test28031() {
Workbook wb = getTestDataProvider().createWorkbook(); public void test28031() {
Sheet sheet = wb.createSheet(); Workbook wb = getTestDataProvider().createWorkbook();
wb.setSheetName(0, "Sheet1"); Sheet sheet = wb.createSheet();
wb.setSheetName(0, "Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0); Row row = sheet.createRow(0);
String formulaText = Cell cell = row.createCell(0);
"IF(ROUND(A2*B2*C2,2)>ROUND(B2*D2,2),ROUND(A2*B2*C2,2),ROUND(B2*D2,2))"; String formulaText =
cell.setCellFormula(formulaText); "IF(ROUND(A2*B2*C2,2)>ROUND(B2*D2,2),ROUND(A2*B2*C2,2),ROUND(B2*D2,2))";
cell.setCellFormula(formulaText);
assertEquals(formulaText, cell.getCellFormula());
wb = getTestDataProvider().writeOutAndReadBack(wb); assertEquals(formulaText, cell.getCellFormula());
cell = wb.getSheetAt(0).getRow(0).getCell(0); wb = getTestDataProvider().writeOutAndReadBack(wb);
assertEquals("IF(ROUND(A2*B2*C2,2)>ROUND(B2*D2,2),ROUND(A2*B2*C2,2),ROUND(B2*D2,2))", cell.getCellFormula()); cell = wb.getSheetAt(0).getRow(0).getCell(0);
} assertEquals("IF(ROUND(A2*B2*C2,2)>ROUND(B2*D2,2),ROUND(A2*B2*C2,2),ROUND(B2*D2,2))", cell.getCellFormula());
}
/**
* Bug 21334: "File error: data may have been lost" with a file /**
* that contains macros and this formula: * Bug 21334: "File error: data may have been lost" with a file
* {=SUM(IF(FREQUENCY(IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),""),IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),""))>0,1))} * that contains macros and this formula:
*/ * {=SUM(IF(FREQUENCY(IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),""),IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),""))>0,1))}
public void test21334() { */
Workbook wb = getTestDataProvider().createWorkbook(); public void test21334() {
Sheet sh = wb.createSheet(); Workbook wb = getTestDataProvider().createWorkbook();
Cell cell = sh.createRow(0).createCell(0); Sheet sh = wb.createSheet();
String formula = "SUM(IF(FREQUENCY(IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),\"\"),IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),\"\"))>0,1))"; Cell cell = sh.createRow(0).createCell(0);
cell.setCellFormula(formula); String formula = "SUM(IF(FREQUENCY(IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),\"\"),IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),\"\"))>0,1))";
cell.setCellFormula(formula);
Workbook wb_sv = getTestDataProvider().writeOutAndReadBack(wb);
Cell cell_sv = wb_sv.getSheetAt(0).getRow(0).getCell(0); Workbook wb_sv = getTestDataProvider().writeOutAndReadBack(wb);
assertEquals(formula, cell_sv.getCellFormula()); Cell cell_sv = wb_sv.getSheetAt(0).getRow(0).getCell(0);
} assertEquals(formula, cell_sv.getCellFormula());
}
/** another test for the number of unique strings issue
*test opening the resulting file in Excel*/ /** another test for the number of unique strings issue
public void test22568() { *test opening the resulting file in Excel*/
int r=2000;int c=3; public void test22568() {
int r=2000;int c=3;
Workbook wb = getTestDataProvider().createWorkbook();
Sheet sheet = wb.createSheet("ExcelTest") ; Workbook wb = getTestDataProvider().createWorkbook();
Sheet sheet = wb.createSheet("ExcelTest") ;
int col_cnt=0, rw_cnt=0 ;
int col_cnt=0, rw_cnt=0 ;
col_cnt = c;
rw_cnt = r; col_cnt = c;
rw_cnt = r;
Row rw ;
rw = sheet.createRow(0) ; Row rw ;
//Header row rw = sheet.createRow(0) ;
for(int j=0; j<col_cnt; j++){ //Header row
Cell cell = rw.createCell(j) ; for(int j=0; j<col_cnt; j++){
cell.setCellValue("Col " + (j+1)); Cell cell = rw.createCell(j) ;
} cell.setCellValue("Col " + (j+1));
}
for(int i=1; i<rw_cnt; i++){
rw = sheet.createRow(i) ; for(int i=1; i<rw_cnt; i++){
for(int j=0; j<col_cnt; j++){ rw = sheet.createRow(i) ;
Cell cell = rw.createCell(j) ; for(int j=0; j<col_cnt; j++){
cell.setCellValue("Row:" + (i+1) + ",Column:" + (j+1)); Cell cell = rw.createCell(j) ;
} cell.setCellValue("Row:" + (i+1) + ",Column:" + (j+1));
} }
}
sheet.setDefaultColumnWidth(18) ;
sheet.setDefaultColumnWidth(18) ;
wb = getTestDataProvider().writeOutAndReadBack(wb);
sheet = wb.getSheetAt(0); wb = getTestDataProvider().writeOutAndReadBack(wb);
rw = sheet.getRow(0); sheet = wb.getSheetAt(0);
//Header row rw = sheet.getRow(0);
for(int j=0; j<col_cnt; j++){ //Header row
Cell cell = rw.getCell(j) ; for(int j=0; j<col_cnt; j++){
assertEquals("Col " + (j+1), cell.getStringCellValue()); Cell cell = rw.getCell(j) ;
} assertEquals("Col " + (j+1), cell.getStringCellValue());
for(int i=1; i<rw_cnt; i++){ }
rw = sheet.getRow(i) ; for(int i=1; i<rw_cnt; i++){
for(int j=0; j<col_cnt; j++){ rw = sheet.getRow(i) ;
Cell cell = rw.getCell(j) ; for(int j=0; j<col_cnt; j++){
assertEquals("Row:" + (i+1) + ",Column:" + (j+1), cell.getStringCellValue()); Cell cell = rw.getCell(j) ;
} assertEquals("Row:" + (i+1) + ",Column:" + (j+1), cell.getStringCellValue());
} }
} }
}
/**
* Bug 42448: Can't parse SUMPRODUCT(A!C7:A!C67, B8:B68) / B69 /**
*/ * Bug 42448: Can't parse SUMPRODUCT(A!C7:A!C67, B8:B68) / B69
public void test42448(){ */
Workbook wb = getTestDataProvider().createWorkbook(); public void test42448(){
Cell cell = wb.createSheet().createRow(0).createCell(0); Workbook wb = getTestDataProvider().createWorkbook();
cell.setCellFormula("SUMPRODUCT(A!C7:A!C67, B8:B68) / B69"); Cell cell = wb.createSheet().createRow(0).createCell(0);
assertTrue("no errors parsing formula", true); cell.setCellFormula("SUMPRODUCT(A!C7:A!C67, B8:B68) / B69");
} assertTrue("no errors parsing formula", true);
}
/**
* HSSFRichTextString.length() returns negative for really /**
* long strings * HSSFRichTextString.length() returns negative for really
*/ * long strings
public void test46368() { */
Workbook wb = getTestDataProvider().createWorkbook(); public void test46368() {
Sheet s = wb.createSheet(); Workbook wb = getTestDataProvider().createWorkbook();
Row r = s.createRow(0); Sheet s = wb.createSheet();
for(int i=0; i<15; i++) { Row r = s.createRow(0);
int len = 32760 + i; for(int i=0; i<15; i++) {
Cell c = r.createCell(i); int len = 32760 + i;
Cell c = r.createCell(i);
StringBuffer sb = new StringBuffer();
for(int j=0; j<len; j++) { StringBuffer sb = new StringBuffer();
sb.append("x"); for(int j=0; j<len; j++) {
} sb.append("x");
RichTextString rtr = wb.getCreationHelper().createRichTextString(sb.toString()); }
assertEquals(len, rtr.length()); RichTextString rtr = wb.getCreationHelper().createRichTextString(sb.toString());
c.setCellValue(rtr); assertEquals(len, rtr.length());
} c.setCellValue(rtr);
}
// Save and reload
wb = getTestDataProvider().writeOutAndReadBack(wb); // Save and reload
s = wb.getSheetAt(0); wb = getTestDataProvider().writeOutAndReadBack(wb);
r = s.getRow(0); s = wb.getSheetAt(0);
for(int i=0; i<15; i++) { r = s.getRow(0);
int len = 32760 + i; for(int i=0; i<15; i++) {
Cell c = r.getCell(i); int len = 32760 + i;
assertEquals(len, c.getRichStringCellValue().length()); Cell c = r.getCell(i);
} assertEquals(len, c.getRichStringCellValue().length());
} }
}
public void test18800() {
Workbook book = getTestDataProvider().createWorkbook(); public void test18800() {
book.createSheet("TEST"); Workbook book = getTestDataProvider().createWorkbook();
Sheet sheet = book.cloneSheet(0); book.createSheet("TEST");
book.setSheetName(1,"CLONE"); Sheet sheet = book.cloneSheet(0);
sheet.createRow(0).createCell(0).setCellValue("Test"); book.setSheetName(1,"CLONE");
sheet.createRow(0).createCell(0).setCellValue("Test");
book = getTestDataProvider().writeOutAndReadBack(book);
sheet = book.getSheet("CLONE"); book = getTestDataProvider().writeOutAndReadBack(book);
Row row = sheet.getRow(0); sheet = book.getSheet("CLONE");
Cell cell = row.getCell(0); Row row = sheet.getRow(0);
assertEquals("Test", cell.getRichStringCellValue().getString()); Cell cell = row.getCell(0);
} assertEquals("Test", cell.getRichStringCellValue().getString());
}
private static void addNewSheetWithCellsA1toD4(Workbook book, int sheet) {
private static void addNewSheetWithCellsA1toD4(Workbook book, int sheet) {
Sheet sht = book .createSheet("s" + sheet);
for (int r=0; r < 4; r++) { Sheet sht = book .createSheet("s" + sheet);
for (int r=0; r < 4; r++) {
Row row = sht.createRow (r);
for (int c=0; c < 4; c++) { Row row = sht.createRow (r);
for (int c=0; c < 4; c++) {
Cell cel = row.createCell(c);
cel.setCellValue(sheet*100 + r*10 + c); Cell cel = row.createCell(c);
} cel.setCellValue(sheet*100 + r*10 + c);
} }
} }
}
public void testBug43093() {
Workbook xlw = getTestDataProvider().createWorkbook(); public void testBug43093() {
Workbook xlw = getTestDataProvider().createWorkbook();
addNewSheetWithCellsA1toD4(xlw, 1);
addNewSheetWithCellsA1toD4(xlw, 2); addNewSheetWithCellsA1toD4(xlw, 1);
addNewSheetWithCellsA1toD4(xlw, 3); addNewSheetWithCellsA1toD4(xlw, 2);
addNewSheetWithCellsA1toD4(xlw, 4); addNewSheetWithCellsA1toD4(xlw, 3);
addNewSheetWithCellsA1toD4(xlw, 4);
Sheet s2 = xlw.getSheet("s2");
Row s2r3 = s2.getRow(3); Sheet s2 = xlw.getSheet("s2");
Cell s2E4 = s2r3.createCell(4); Row s2r3 = s2.getRow(3);
s2E4.setCellFormula("SUM(s3!B2:C3)"); Cell s2E4 = s2r3.createCell(4);
s2E4.setCellFormula("SUM(s3!B2:C3)");
FormulaEvaluator eva = xlw.getCreationHelper().createFormulaEvaluator();
double d = eva.evaluate(s2E4).getNumberValue(); FormulaEvaluator eva = xlw.getCreationHelper().createFormulaEvaluator();
double d = eva.evaluate(s2E4).getNumberValue();
assertEquals(d, (311+312+321+322), 0.0000001);
} assertEquals(d, (311+312+321+322), 0.0000001);
}
public void testMaxFunctionArguments_bug46729(){
String[] func = {"COUNT", "AVERAGE", "MAX", "MIN", "OR", "SUBTOTAL", "SKEW"}; public void testMaxFunctionArguments_bug46729(){
String[] func = {"COUNT", "AVERAGE", "MAX", "MIN", "OR", "SUBTOTAL", "SKEW"};
SpreadsheetVersion ssVersion = getTestDataProvider().getSpreadsheetVersion();
Workbook wb = getTestDataProvider().createWorkbook(); SpreadsheetVersion ssVersion = getTestDataProvider().getSpreadsheetVersion();
Cell cell = wb.createSheet().createRow(0).createCell(0); Workbook wb = getTestDataProvider().createWorkbook();
Cell cell = wb.createSheet().createRow(0).createCell(0);
String fmla;
for (String name : func) { String fmla;
for (String name : func) {
fmla = createFunction(name, 5);
cell.setCellFormula(fmla); fmla = createFunction(name, 5);
cell.setCellFormula(fmla);
fmla = createFunction(name, ssVersion.getMaxFunctionArgs());
cell.setCellFormula(fmla); fmla = createFunction(name, ssVersion.getMaxFunctionArgs());
cell.setCellFormula(fmla);
try {
fmla = createFunction(name, ssVersion.getMaxFunctionArgs() + 1); try {
cell.setCellFormula(fmla); fmla = createFunction(name, ssVersion.getMaxFunctionArgs() + 1);
fail("Expected FormulaParseException"); cell.setCellFormula(fmla);
} catch (RuntimeException e){ fail("Expected FormulaParseException");
assertTrue(e.getMessage().startsWith("Too many arguments to function '"+name+"'")); } catch (RuntimeException e){
} assertTrue(e.getMessage().startsWith("Too many arguments to function '"+name+"'"));
} }
} }
}
private String createFunction(String name, int maxArgs){
StringBuffer fmla = new StringBuffer(); private String createFunction(String name, int maxArgs){
fmla.append(name); StringBuffer fmla = new StringBuffer();
fmla.append("("); fmla.append(name);
for(int i=0; i < maxArgs; i++){ fmla.append("(");
if(i > 0) fmla.append(','); for(int i=0; i < maxArgs; i++){
fmla.append("A1"); if(i > 0) fmla.append(',');
} fmla.append("A1");
fmla.append(")"); }
return fmla.toString(); fmla.append(")");
} return fmla.toString();
} }
}

View File

@ -1,204 +1,200 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.ss.usermodel;
package org.apache.poi.ss.usermodel;
import junit.framework.TestCase;
import junit.framework.AssertionFailedError; import junit.framework.TestCase;
import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.ITestDataProvider;
/** /**
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public abstract class BaseTestFont extends TestCase { public abstract class BaseTestFont extends TestCase {
protected abstract ITestDataProvider getTestDataProvider(); protected abstract ITestDataProvider getTestDataProvider();
public void baseTestDefaultFont(String defaultName, short defaultSize, short defaultColor){ public void baseTestDefaultFont(String defaultName, short defaultSize, short defaultColor){
//get default font and check against default value //get default font and check against default value
Workbook workbook = getTestDataProvider().createWorkbook(); Workbook workbook = getTestDataProvider().createWorkbook();
Font fontFind=workbook.findFont(Font.BOLDWEIGHT_NORMAL, defaultColor, defaultSize, defaultName, false, false, Font.SS_NONE, Font.U_NONE); Font fontFind=workbook.findFont(Font.BOLDWEIGHT_NORMAL, defaultColor, defaultSize, defaultName, false, false, Font.SS_NONE, Font.U_NONE);
assertNotNull(fontFind); assertNotNull(fontFind);
//get default font, then change 2 values and check against different values (height changes) //get default font, then change 2 values and check against different values (height changes)
Font font=workbook.createFont(); Font font=workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD); font.setBoldweight(Font.BOLDWEIGHT_BOLD);
assertEquals(Font.BOLDWEIGHT_BOLD, font.getBoldweight()); assertEquals(Font.BOLDWEIGHT_BOLD, font.getBoldweight());
font.setUnderline(Font.U_DOUBLE); font.setUnderline(Font.U_DOUBLE);
assertEquals(Font.U_DOUBLE, font.getUnderline()); assertEquals(Font.U_DOUBLE, font.getUnderline());
font.setFontHeightInPoints((short)15); font.setFontHeightInPoints((short)15);
assertEquals(15*20, font.getFontHeight()); assertEquals(15*20, font.getFontHeight());
assertEquals(15, font.getFontHeightInPoints()); assertEquals(15, font.getFontHeightInPoints());
fontFind=workbook.findFont(Font.BOLDWEIGHT_BOLD, defaultColor, (short)(15*20), defaultName, false, false, Font.SS_NONE, Font.U_DOUBLE); fontFind=workbook.findFont(Font.BOLDWEIGHT_BOLD, defaultColor, (short)(15*20), defaultName, false, false, Font.SS_NONE, Font.U_DOUBLE);
assertNotNull(fontFind); assertNotNull(fontFind);
} }
public void testGetNumberOfFonts(){ public void testGetNumberOfFonts(){
Workbook wb = getTestDataProvider().createWorkbook(); Workbook wb = getTestDataProvider().createWorkbook();
int num0 = wb.getNumberOfFonts(); int num0 = wb.getNumberOfFonts();
Font f1=wb.createFont(); Font f1=wb.createFont();
f1.setBoldweight(Font.BOLDWEIGHT_BOLD); f1.setBoldweight(Font.BOLDWEIGHT_BOLD);
short idx1 = f1.getIndex(); short idx1 = f1.getIndex();
wb.createCellStyle().setFont(f1); wb.createCellStyle().setFont(f1);
Font f2=wb.createFont(); Font f2=wb.createFont();
f2.setUnderline(Font.U_DOUBLE); f2.setUnderline(Font.U_DOUBLE);
short idx2 = f2.getIndex(); short idx2 = f2.getIndex();
wb.createCellStyle().setFont(f2); wb.createCellStyle().setFont(f2);
Font f3=wb.createFont(); Font f3=wb.createFont();
f3.setFontHeightInPoints((short)23); f3.setFontHeightInPoints((short)23);
short idx3 = f3.getIndex(); short idx3 = f3.getIndex();
wb.createCellStyle().setFont(f3); wb.createCellStyle().setFont(f3);
assertEquals(num0 + 3,wb.getNumberOfFonts()); assertEquals(num0 + 3,wb.getNumberOfFonts());
assertEquals(Font.BOLDWEIGHT_BOLD,wb.getFontAt(idx1).getBoldweight()); assertEquals(Font.BOLDWEIGHT_BOLD,wb.getFontAt(idx1).getBoldweight());
assertEquals(Font.U_DOUBLE,wb.getFontAt(idx2).getUnderline()); assertEquals(Font.U_DOUBLE,wb.getFontAt(idx2).getUnderline());
assertEquals(23,wb.getFontAt(idx3).getFontHeightInPoints()); assertEquals(23,wb.getFontAt(idx3).getFontHeightInPoints());
} }
/** /**
* Tests that we can define fonts to a new * Tests that we can define fonts to a new
* file, save, load, and still see them * file, save, load, and still see them
* @throws Exception */
*/ public void testCreateSave() {
public void testCreateSave() { Workbook wb = getTestDataProvider().createWorkbook();
Workbook wb = getTestDataProvider().createWorkbook(); Sheet s1 = wb.createSheet();
Sheet s1 = wb.createSheet(); Row r1 = s1.createRow(0);
Row r1 = s1.createRow(0); Cell r1c1 = r1.createCell(0);
Cell r1c1 = r1.createCell(0); r1c1.setCellValue(2.2);
r1c1.setCellValue(2.2);
int num0 = wb.getNumberOfFonts();
int num0 = wb.getNumberOfFonts();
Font font=wb.createFont();
Font font=wb.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD);
font.setBoldweight(Font.BOLDWEIGHT_BOLD); font.setStrikeout(true);
font.setStrikeout(true); font.setColor(IndexedColors.YELLOW.getIndex());
font.setColor(IndexedColors.YELLOW.getIndex()); font.setFontName("Courier");
font.setFontName("Courier"); short font1Idx = font.getIndex();
short font1Idx = font.getIndex(); wb.createCellStyle().setFont(font);
wb.createCellStyle().setFont(font); assertEquals(num0 + 1, wb.getNumberOfFonts());
assertEquals(num0 + 1, wb.getNumberOfFonts());
CellStyle cellStyleTitle=wb.createCellStyle();
CellStyle cellStyleTitle=wb.createCellStyle(); cellStyleTitle.setFont(font);
cellStyleTitle.setFont(font); r1c1.setCellStyle(cellStyleTitle);
r1c1.setCellStyle(cellStyleTitle);
// Save and re-load
// Save and re-load wb = getTestDataProvider().writeOutAndReadBack(wb);
wb = getTestDataProvider().writeOutAndReadBack(wb); s1 = wb.getSheetAt(0);
s1 = wb.getSheetAt(0);
assertEquals(num0 + 1, wb.getNumberOfFonts());
assertEquals(num0 + 1, wb.getNumberOfFonts()); short idx = s1.getRow(0).getCell(0).getCellStyle().getFontIndex();
short idx = s1.getRow(0).getCell(0).getCellStyle().getFontIndex(); Font fnt = wb.getFontAt(idx);
Font fnt = wb.getFontAt(idx); assertNotNull(fnt);
assertNotNull(fnt); assertEquals(IndexedColors.YELLOW.getIndex(), fnt.getColor());
assertEquals(IndexedColors.YELLOW.getIndex(), fnt.getColor()); assertEquals("Courier", fnt.getFontName());
assertEquals("Courier", fnt.getFontName());
// Now add an orphaned one
// Now add an orphaned one Font font2 = wb.createFont();
Font font2 = wb.createFont(); font2.setItalic(true);
font2.setItalic(true); font2.setFontHeightInPoints((short)15);
font2.setFontHeightInPoints((short)15); short font2Idx = font2.getIndex();
short font2Idx = font2.getIndex(); wb.createCellStyle().setFont(font2);
wb.createCellStyle().setFont(font2); assertEquals(num0 + 2, wb.getNumberOfFonts());
assertEquals(num0 + 2, wb.getNumberOfFonts());
// Save and re-load
// Save and re-load wb = getTestDataProvider().writeOutAndReadBack(wb);
wb = getTestDataProvider().writeOutAndReadBack(wb); s1 = wb.getSheetAt(0);
s1 = wb.getSheetAt(0);
assertEquals(num0 + 2, wb.getNumberOfFonts());
assertEquals(num0 + 2, wb.getNumberOfFonts()); assertNotNull(wb.getFontAt(font1Idx));
assertNotNull(wb.getFontAt(font1Idx)); assertNotNull(wb.getFontAt(font2Idx));
assertNotNull(wb.getFontAt(font2Idx));
assertEquals(15, wb.getFontAt(font2Idx).getFontHeightInPoints());
assertEquals(15, wb.getFontAt(font2Idx).getFontHeightInPoints()); assertEquals(true, wb.getFontAt(font2Idx).getItalic());
assertEquals(true, wb.getFontAt(font2Idx).getItalic()); }
}
/**
* Test that fonts get added properly
*
/** * @see org.apache.poi.hssf.usermodel.TestBugs#test45338()
* Test that fonts get added properly */
* public void test45338() {
* @see org.apache.poi.hssf.usermodel.TestBugs#test45338() Workbook wb = getTestDataProvider().createWorkbook();
*/ int num0 = wb.getNumberOfFonts();
public void test45338() {
Workbook wb = getTestDataProvider().createWorkbook(); Sheet s = wb.createSheet();
int num0 = wb.getNumberOfFonts(); s.createRow(0);
s.createRow(1);
Sheet s = wb.createSheet(); s.getRow(0).createCell(0);
s.createRow(0); s.getRow(1).createCell(0);
s.createRow(1);
s.getRow(0).createCell(0); //default font
s.getRow(1).createCell(0); Font f1 = wb.getFontAt((short)0);
assertEquals(Font.BOLDWEIGHT_NORMAL, f1.getBoldweight());
//default font
Font f1 = wb.getFontAt((short)0); // Check that asking for the same font
assertEquals(Font.BOLDWEIGHT_NORMAL, f1.getBoldweight()); // multiple times gives you the same thing.
// Otherwise, our tests wouldn't work!
// Check that asking for the same font assertSame(wb.getFontAt((short)0), wb.getFontAt((short)0));
// multiple times gives you the same thing.
// Otherwise, our tests wouldn't work! // Look for a new font we have
assertSame(wb.getFontAt((short)0), wb.getFontAt((short)0)); // yet to add
assertNull(
// Look for a new font we have wb.findFont(
// yet to add Font.BOLDWEIGHT_BOLD, (short)123, (short)(22*20),
assertNull( "Thingy", false, true, (short)2, (byte)2
wb.findFont( )
Font.BOLDWEIGHT_BOLD, (short)123, (short)(22*20), );
"Thingy", false, true, (short)2, (byte)2
) Font nf = wb.createFont();
); short nfIdx = nf.getIndex();
assertEquals(num0 + 1, wb.getNumberOfFonts());
Font nf = wb.createFont();
short nfIdx = nf.getIndex(); assertSame(nf, wb.getFontAt(nfIdx));
assertEquals(num0 + 1, wb.getNumberOfFonts());
nf.setBoldweight(Font.BOLDWEIGHT_BOLD);
assertSame(nf, wb.getFontAt(nfIdx)); nf.setColor((short)123);
nf.setFontHeightInPoints((short)22);
nf.setBoldweight(Font.BOLDWEIGHT_BOLD); nf.setFontName("Thingy");
nf.setColor((short)123); nf.setItalic(false);
nf.setFontHeightInPoints((short)22); nf.setStrikeout(true);
nf.setFontName("Thingy"); nf.setTypeOffset((short)2);
nf.setItalic(false); nf.setUnderline((byte)2);
nf.setStrikeout(true);
nf.setTypeOffset((short)2); assertEquals(num0 + 1, wb.getNumberOfFonts());
nf.setUnderline((byte)2); assertEquals(nf, wb.getFontAt(nfIdx));
assertEquals(num0 + 1, wb.getNumberOfFonts()); assertEquals(wb.getFontAt(nfIdx), wb.getFontAt(nfIdx));
assertEquals(nf, wb.getFontAt(nfIdx)); assertTrue(wb.getFontAt((short)0) != wb.getFontAt(nfIdx));
assertEquals(wb.getFontAt(nfIdx), wb.getFontAt(nfIdx)); // Find it now
assertTrue(wb.getFontAt((short)0) != wb.getFontAt(nfIdx)); assertNotNull(
wb.findFont(
// Find it now Font.BOLDWEIGHT_BOLD, (short)123, (short)(22*20),
assertNotNull( "Thingy", false, true, (short)2, (byte)2
wb.findFont( )
Font.BOLDWEIGHT_BOLD, (short)123, (short)(22*20), );
"Thingy", false, true, (short)2, (byte)2 assertSame(nf,
) wb.findFont(
); Font.BOLDWEIGHT_BOLD, (short)123, (short)(22*20),
assertSame(nf, "Thingy", false, true, (short)2, (byte)2
wb.findFont( )
Font.BOLDWEIGHT_BOLD, (short)123, (short)(22*20), );
"Thingy", false, true, (short)2, (byte)2 }
) }
);
}
}

View File

@ -1,53 +1,52 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.ss.usermodel;
package org.apache.poi.ss.usermodel;
import junit.framework.TestCase;
import org.apache.poi.ss.ITestDataProvider; import junit.framework.TestCase;
import org.apache.poi.ss.ITestDataProvider;
/**
* @author Yegor Kozlov /**
*/ * @author Yegor Kozlov
public abstract class BaseTestPicture extends TestCase { */
public abstract class BaseTestPicture extends TestCase {
protected abstract ITestDataProvider getTestDataProvider();
protected abstract ITestDataProvider getTestDataProvider();
public void baseTestResize(ClientAnchor referenceAnchor) {
Workbook wb = getTestDataProvider().createWorkbook(); public void baseTestResize(ClientAnchor referenceAnchor) {
Sheet sh1 = wb.createSheet(); Workbook wb = getTestDataProvider().createWorkbook();
Drawing p1 = sh1.createDrawingPatriarch(); Sheet sh1 = wb.createSheet();
CreationHelper factory = wb.getCreationHelper(); Drawing p1 = sh1.createDrawingPatriarch();
CreationHelper factory = wb.getCreationHelper();
byte[] pictureData = getTestDataProvider().getTestDataFileContent("logoKarmokar4.png");
int idx1 = wb.addPicture( pictureData, Workbook.PICTURE_TYPE_PNG ); byte[] pictureData = getTestDataProvider().getTestDataFileContent("logoKarmokar4.png");
Picture picture = p1.createPicture(factory.createClientAnchor(), idx1); int idx1 = wb.addPicture( pictureData, Workbook.PICTURE_TYPE_PNG );
picture.resize(); Picture picture = p1.createPicture(factory.createClientAnchor(), idx1);
ClientAnchor anchor1 = picture.getPreferredSize(); picture.resize();
ClientAnchor anchor1 = picture.getPreferredSize();
//assert against what would BiffViewer print if we insert the image in xls and dump the file
assertEquals(referenceAnchor.getCol1(), anchor1.getCol1()); //assert against what would BiffViewer print if we insert the image in xls and dump the file
assertEquals(referenceAnchor.getRow1(), anchor1.getRow1()); assertEquals(referenceAnchor.getCol1(), anchor1.getCol1());
assertEquals(referenceAnchor.getCol2(), anchor1.getCol2()); assertEquals(referenceAnchor.getRow1(), anchor1.getRow1());
assertEquals(referenceAnchor.getRow2(), anchor1.getRow2()); assertEquals(referenceAnchor.getCol2(), anchor1.getCol2());
assertEquals(referenceAnchor.getDx1(), anchor1.getDx1()); assertEquals(referenceAnchor.getRow2(), anchor1.getRow2());
assertEquals(referenceAnchor.getDy1(), anchor1.getDy1()); assertEquals(referenceAnchor.getDx1(), anchor1.getDx1());
assertEquals(referenceAnchor.getDx2(), anchor1.getDx2()); assertEquals(referenceAnchor.getDy1(), anchor1.getDy1());
assertEquals(referenceAnchor.getDy2(), anchor1.getDy2()); assertEquals(referenceAnchor.getDx2(), anchor1.getDx2());
} assertEquals(referenceAnchor.getDy2(), anchor1.getDy2());
}
}
}

View File

@ -1,327 +1,327 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.ss.usermodel; package org.apache.poi.ss.usermodel;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
/** /**
* Tests row shifting capabilities. * Tests row shifting capabilities.
* *
* @author Shawn Laubach (slaubach at apache dot com) * @author Shawn Laubach (slaubach at apache dot com)
* @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp)
*/ */
public abstract class BaseTestSheetShiftRows extends TestCase { public abstract class BaseTestSheetShiftRows extends TestCase {
/** /**
* @return an object that provides test data in HSSF / XSSF specific way * @return an object that provides test data in HSSF / XSSF specific way
*/ */
protected abstract ITestDataProvider getTestDataProvider(); protected abstract ITestDataProvider getTestDataProvider();
/** /**
* Tests the shiftRows function. Does three different shifts. * Tests the shiftRows function. Does three different shifts.
* After each shift, writes the workbook to file and reads back to * After each shift, writes the workbook to file and reads back to
* check. This ensures that if some changes code that breaks * check. This ensures that if some changes code that breaks
* writing or what not, they realize it. * writing or what not, they realize it.
* *
* @param sampleName the sample file to test against * @param sampleName the sample file to test against
*/ */
public final void baseTestShiftRows(String sampleName){ public final void baseTestShiftRows(String sampleName){
// Read initial file in // Read initial file in
Workbook wb = getTestDataProvider().openSampleWorkbook(sampleName); Workbook wb = getTestDataProvider().openSampleWorkbook(sampleName);
Sheet s = wb.getSheetAt( 0 ); Sheet s = wb.getSheetAt( 0 );
// Shift the second row down 1 and write to temp file // Shift the second row down 1 and write to temp file
s.shiftRows( 1, 1, 1 ); s.shiftRows( 1, 1, 1 );
wb = getTestDataProvider().writeOutAndReadBack(wb); wb = getTestDataProvider().writeOutAndReadBack(wb);
// Read from temp file and check the number of cells in each // Read from temp file and check the number of cells in each
// row (in original file each row was unique) // row (in original file each row was unique)
s = wb.getSheetAt( 0 ); s = wb.getSheetAt( 0 );
assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 1); assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 1);
confirmEmptyRow(s, 1); confirmEmptyRow(s, 1);
assertEquals(s.getRow(2).getPhysicalNumberOfCells(), 2); assertEquals(s.getRow(2).getPhysicalNumberOfCells(), 2);
assertEquals(s.getRow(3).getPhysicalNumberOfCells(), 4); assertEquals(s.getRow(3).getPhysicalNumberOfCells(), 4);
assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5); assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5);
// Shift rows 1-3 down 3 in the current one. This tests when // Shift rows 1-3 down 3 in the current one. This tests when
// 1 row is blank. Write to a another temp file // 1 row is blank. Write to a another temp file
s.shiftRows( 0, 2, 3 ); s.shiftRows( 0, 2, 3 );
wb = getTestDataProvider().writeOutAndReadBack(wb); wb = getTestDataProvider().writeOutAndReadBack(wb);
// Read and ensure things are where they should be // Read and ensure things are where they should be
s = wb.getSheetAt(0); s = wb.getSheetAt(0);
confirmEmptyRow(s, 0); confirmEmptyRow(s, 0);
confirmEmptyRow(s, 1); confirmEmptyRow(s, 1);
confirmEmptyRow(s, 2); confirmEmptyRow(s, 2);
assertEquals(s.getRow(3).getPhysicalNumberOfCells(), 1); assertEquals(s.getRow(3).getPhysicalNumberOfCells(), 1);
confirmEmptyRow(s, 4); confirmEmptyRow(s, 4);
assertEquals(s.getRow(5).getPhysicalNumberOfCells(), 2); assertEquals(s.getRow(5).getPhysicalNumberOfCells(), 2);
// Read the first file again // Read the first file again
wb = getTestDataProvider().openSampleWorkbook(sampleName); wb = getTestDataProvider().openSampleWorkbook(sampleName);
s = wb.getSheetAt( 0 ); s = wb.getSheetAt( 0 );
// Shift rows 3 and 4 up and write to temp file // Shift rows 3 and 4 up and write to temp file
s.shiftRows( 2, 3, -2 ); s.shiftRows( 2, 3, -2 );
wb = getTestDataProvider().writeOutAndReadBack(wb); wb = getTestDataProvider().writeOutAndReadBack(wb);
s = wb.getSheetAt( 0 ); s = wb.getSheetAt( 0 );
assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 3); assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 3);
assertEquals(s.getRow(1).getPhysicalNumberOfCells(), 4); assertEquals(s.getRow(1).getPhysicalNumberOfCells(), 4);
confirmEmptyRow(s, 2); confirmEmptyRow(s, 2);
confirmEmptyRow(s, 3); confirmEmptyRow(s, 3);
assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5); assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5);
} }
private static void confirmEmptyRow(Sheet s, int rowIx) { private static void confirmEmptyRow(Sheet s, int rowIx) {
Row row = s.getRow(rowIx); Row row = s.getRow(rowIx);
assertTrue(row == null || row.getPhysicalNumberOfCells() == 0); assertTrue(row == null || row.getPhysicalNumberOfCells() == 0);
} }
/** /**
* Tests when rows are null. * Tests when rows are null.
*/ */
public final void baseTestShiftRow() { public final void baseTestShiftRow() {
Workbook b = getTestDataProvider().createWorkbook(); Workbook b = getTestDataProvider().createWorkbook();
Sheet s = b.createSheet(); Sheet s = b.createSheet();
s.createRow(0).createCell(0).setCellValue("TEST1"); s.createRow(0).createCell(0).setCellValue("TEST1");
s.createRow(3).createCell(0).setCellValue("TEST2"); s.createRow(3).createCell(0).setCellValue("TEST2");
s.shiftRows(0,4,1); s.shiftRows(0,4,1);
} }
/** /**
* Tests when shifting the first row. * Tests when shifting the first row.
*/ */
public final void baseTestActiveCell() { public final void baseTestActiveCell() {
Workbook b = getTestDataProvider().createWorkbook(); Workbook b = getTestDataProvider().createWorkbook();
Sheet s = b.createSheet(); Sheet s = b.createSheet();
s.createRow(0).createCell(0).setCellValue("TEST1"); s.createRow(0).createCell(0).setCellValue("TEST1");
s.createRow(3).createCell(0).setCellValue("TEST2"); s.createRow(3).createCell(0).setCellValue("TEST2");
s.shiftRows(0,4,1); s.shiftRows(0,4,1);
} }
/** /**
* When shifting rows, the page breaks should go with it * When shifting rows, the page breaks should go with it
* *
*/ */
public final void baseTestShiftRowBreaks() { public final void baseTestShiftRowBreaks() {
Workbook b = getTestDataProvider().createWorkbook(); Workbook b = getTestDataProvider().createWorkbook();
Sheet s = b.createSheet(); Sheet s = b.createSheet();
Row row = s.createRow(4); Row row = s.createRow(4);
row.createCell(0).setCellValue("test"); row.createCell(0).setCellValue("test");
s.setRowBreak(4); s.setRowBreak(4);
s.shiftRows(4, 4, 2); s.shiftRows(4, 4, 2);
assertTrue("Row number 6 should have a pagebreak", s.isRowBroken(6)); assertTrue("Row number 6 should have a pagebreak", s.isRowBroken(6));
} }
public final void baseTestShiftWithComments(String sampleName) { public final void baseTestShiftWithComments(String sampleName) {
Workbook wb = getTestDataProvider().openSampleWorkbook(sampleName); Workbook wb = getTestDataProvider().openSampleWorkbook(sampleName);
Sheet sheet = wb.getSheet("Sheet1"); Sheet sheet = wb.getSheet("Sheet1");
assertEquals(3, sheet.getLastRowNum()); assertEquals(3, sheet.getLastRowNum());
// Verify comments are in the position expected // Verify comments are in the position expected
assertNotNull(sheet.getCellComment(0,0)); assertNotNull(sheet.getCellComment(0,0));
assertNull(sheet.getCellComment(1,0)); assertNull(sheet.getCellComment(1,0));
assertNotNull(sheet.getCellComment(2,0)); assertNotNull(sheet.getCellComment(2,0));
assertNotNull(sheet.getCellComment(3,0)); assertNotNull(sheet.getCellComment(3,0));
String comment1 = sheet.getCellComment(0,0).getString().getString(); String comment1 = sheet.getCellComment(0,0).getString().getString();
assertEquals(comment1,"comment top row1 (index0)\n"); assertEquals(comment1,"comment top row1 (index0)\n");
String comment3 = sheet.getCellComment(2,0).getString().getString(); String comment3 = sheet.getCellComment(2,0).getString().getString();
assertEquals(comment3,"comment top row3 (index2)\n"); assertEquals(comment3,"comment top row3 (index2)\n");
String comment4 = sheet.getCellComment(3,0).getString().getString(); String comment4 = sheet.getCellComment(3,0).getString().getString();
assertEquals(comment4,"comment top row4 (index3)\n"); assertEquals(comment4,"comment top row4 (index3)\n");
// Shifting all but first line down to test comments shifting // Shifting all but first line down to test comments shifting
sheet.shiftRows(1, sheet.getLastRowNum(), 1, true, true); sheet.shiftRows(1, sheet.getLastRowNum(), 1, true, true);
// Test that comments were shifted as expected // Test that comments were shifted as expected
assertEquals(4, sheet.getLastRowNum()); assertEquals(4, sheet.getLastRowNum());
assertNotNull(sheet.getCellComment(0,0)); assertNotNull(sheet.getCellComment(0,0));
assertNull(sheet.getCellComment(1,0)); assertNull(sheet.getCellComment(1,0));
assertNull(sheet.getCellComment(2,0)); assertNull(sheet.getCellComment(2,0));
assertNotNull(sheet.getCellComment(3,0)); assertNotNull(sheet.getCellComment(3,0));
assertNotNull(sheet.getCellComment(4,0)); assertNotNull(sheet.getCellComment(4,0));
String comment1_shifted = sheet.getCellComment(0,0).getString().getString(); String comment1_shifted = sheet.getCellComment(0,0).getString().getString();
assertEquals(comment1,comment1_shifted); assertEquals(comment1,comment1_shifted);
String comment3_shifted = sheet.getCellComment(3,0).getString().getString(); String comment3_shifted = sheet.getCellComment(3,0).getString().getString();
assertEquals(comment3,comment3_shifted); assertEquals(comment3,comment3_shifted);
String comment4_shifted = sheet.getCellComment(4,0).getString().getString(); String comment4_shifted = sheet.getCellComment(4,0).getString().getString();
assertEquals(comment4,comment4_shifted); assertEquals(comment4,comment4_shifted);
// Write out and read back in again // Write out and read back in again
// Ensure that the changes were persisted // Ensure that the changes were persisted
wb = getTestDataProvider().writeOutAndReadBack(wb); wb = getTestDataProvider().writeOutAndReadBack(wb);
sheet = wb.getSheet("Sheet1"); sheet = wb.getSheet("Sheet1");
assertEquals(4, sheet.getLastRowNum()); assertEquals(4, sheet.getLastRowNum());
// Verify comments are in the position expected after the shift // Verify comments are in the position expected after the shift
assertNotNull(sheet.getCellComment(0,0)); assertNotNull(sheet.getCellComment(0,0));
assertNull(sheet.getCellComment(1,0)); assertNull(sheet.getCellComment(1,0));
assertNull(sheet.getCellComment(2,0)); assertNull(sheet.getCellComment(2,0));
assertNotNull(sheet.getCellComment(3,0)); assertNotNull(sheet.getCellComment(3,0));
assertNotNull(sheet.getCellComment(4,0)); assertNotNull(sheet.getCellComment(4,0));
comment1_shifted = sheet.getCellComment(0,0).getString().getString(); comment1_shifted = sheet.getCellComment(0,0).getString().getString();
assertEquals(comment1,comment1_shifted); assertEquals(comment1,comment1_shifted);
comment3_shifted = sheet.getCellComment(3,0).getString().getString(); comment3_shifted = sheet.getCellComment(3,0).getString().getString();
assertEquals(comment3,comment3_shifted); assertEquals(comment3,comment3_shifted);
comment4_shifted = sheet.getCellComment(4,0).getString().getString(); comment4_shifted = sheet.getCellComment(4,0).getString().getString();
assertEquals(comment4,comment4_shifted); assertEquals(comment4,comment4_shifted);
} }
public final void baseTestShiftWithNames() { public final void baseTestShiftWithNames() {
Workbook wb = getTestDataProvider().createWorkbook(); Workbook wb = getTestDataProvider().createWorkbook();
Sheet sheet1 = wb.createSheet("Sheet1"); Sheet sheet1 = wb.createSheet("Sheet1");
Sheet sheet2 = wb.createSheet("Sheet2"); wb.createSheet("Sheet2");
Row row = sheet1.createRow(0); Row row = sheet1.createRow(0);
row.createCell(0).setCellValue(1.1); row.createCell(0).setCellValue(1.1);
row.createCell(1).setCellValue(2.2); row.createCell(1).setCellValue(2.2);
Name name1 = wb.createName(); Name name1 = wb.createName();
name1.setNameName("name1"); name1.setNameName("name1");
name1.setRefersToFormula("Sheet1!$A$1+Sheet1!$B$1"); name1.setRefersToFormula("Sheet1!$A$1+Sheet1!$B$1");
Name name2 = wb.createName(); Name name2 = wb.createName();
name2.setNameName("name2"); name2.setNameName("name2");
name2.setRefersToFormula("Sheet1!$A$1"); name2.setRefersToFormula("Sheet1!$A$1");
//refers to A1 but on Sheet2. Should stay unaffected. //refers to A1 but on Sheet2. Should stay unaffected.
Name name3 = wb.createName(); Name name3 = wb.createName();
name3.setNameName("name3"); name3.setNameName("name3");
name3.setRefersToFormula("Sheet2!$A$1"); name3.setRefersToFormula("Sheet2!$A$1");
//The scope of this one is Sheet2. Should stay unaffected. //The scope of this one is Sheet2. Should stay unaffected.
Name name4 = wb.createName(); Name name4 = wb.createName();
name4.setNameName("name4"); name4.setNameName("name4");
name4.setRefersToFormula("A1"); name4.setRefersToFormula("A1");
name4.setSheetIndex(1); name4.setSheetIndex(1);
sheet1.shiftRows(0, 1, 2); //shift down the top row on Sheet1. sheet1.shiftRows(0, 1, 2); //shift down the top row on Sheet1.
name1 = wb.getNameAt(0); name1 = wb.getNameAt(0);
assertEquals("Sheet1!$A$3+Sheet1!$B$3", name1.getRefersToFormula()); assertEquals("Sheet1!$A$3+Sheet1!$B$3", name1.getRefersToFormula());
name2 = wb.getNameAt(1); name2 = wb.getNameAt(1);
assertEquals("Sheet1!$A$3", name2.getRefersToFormula()); assertEquals("Sheet1!$A$3", name2.getRefersToFormula());
//name3 and name4 refer to Sheet2 and should not be affected //name3 and name4 refer to Sheet2 and should not be affected
name3 = wb.getNameAt(2); name3 = wb.getNameAt(2);
assertEquals("Sheet2!$A$1", name3.getRefersToFormula()); assertEquals("Sheet2!$A$1", name3.getRefersToFormula());
name4 = wb.getNameAt(3); name4 = wb.getNameAt(3);
assertEquals("A1", name4.getRefersToFormula()); assertEquals("A1", name4.getRefersToFormula());
} }
public final void baseTestShiftWithMergedRegions() { public final void baseTestShiftWithMergedRegions() {
Workbook wb = getTestDataProvider().createWorkbook(); Workbook wb = getTestDataProvider().createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
row.createCell(0).setCellValue(1.1); row.createCell(0).setCellValue(1.1);
row.createCell(1).setCellValue(2.2); row.createCell(1).setCellValue(2.2);
CellRangeAddress region = new CellRangeAddress(0, 0, 0, 2); CellRangeAddress region = new CellRangeAddress(0, 0, 0, 2);
assertEquals("A1:C1", region.formatAsString()); assertEquals("A1:C1", region.formatAsString());
sheet.addMergedRegion(region); sheet.addMergedRegion(region);
sheet.shiftRows(0, 1, 2); sheet.shiftRows(0, 1, 2);
region = sheet.getMergedRegion(0); region = sheet.getMergedRegion(0);
assertEquals("A3:C3", region.formatAsString()); assertEquals("A3:C3", region.formatAsString());
} }
/** /**
* See bug #34023 * See bug #34023
* *
* @param sampleName the sample file to test against * @param sampleName the sample file to test against
*/ */
public void baseTestShiftWithFormulas(String sampleName) { public void baseTestShiftWithFormulas(String sampleName) {
Workbook wb = getTestDataProvider().openSampleWorkbook(sampleName); Workbook wb = getTestDataProvider().openSampleWorkbook(sampleName);
Sheet sheet = wb.getSheet("Sheet1"); Sheet sheet = wb.getSheet("Sheet1");
assertEquals(20, sheet.getLastRowNum()); assertEquals(20, sheet.getLastRowNum());
confirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)"); confirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)");
confirmRow(sheet, 1, 2, 172, 1, "ROW(D2)", "100+B2", "COUNT(D2:E2)"); confirmRow(sheet, 1, 2, 172, 1, "ROW(D2)", "100+B2", "COUNT(D2:E2)");
confirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)"); confirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)");
confirmCell(sheet, 6, 1, 271, "200+B1"); confirmCell(sheet, 6, 1, 271, "200+B1");
confirmCell(sheet, 7, 1, 272, "200+B2"); confirmCell(sheet, 7, 1, 272, "200+B2");
confirmCell(sheet, 8, 1, 273, "200+B3"); confirmCell(sheet, 8, 1, 273, "200+B3");
confirmCell(sheet, 14, 0, 0.0, "A12"); // the cell referred to by this formula will be replaced confirmCell(sheet, 14, 0, 0.0, "A12"); // the cell referred to by this formula will be replaced
// ----------- // -----------
// Row index 1 -> 11 (row "2" -> row "12") // Row index 1 -> 11 (row "2" -> row "12")
sheet.shiftRows(1, 1, 10); sheet.shiftRows(1, 1, 10);
// Now check what sheet looks like after move // Now check what sheet looks like after move
// no changes on row "1" // no changes on row "1"
confirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)"); confirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)");
// row "2" is now empty // row "2" is now empty
confirmEmptyRow(sheet, 1); confirmEmptyRow(sheet, 1);
// Row "2" moved to row "12", and the formula has been updated. // Row "2" moved to row "12", and the formula has been updated.
// note however that the cached formula result (2) has not been updated. (POI differs from Excel here) // note however that the cached formula result (2) has not been updated. (POI differs from Excel here)
confirmRow(sheet, 11, 2, 172, 1, "ROW(D12)", "100+B12", "COUNT(D12:E12)"); confirmRow(sheet, 11, 2, 172, 1, "ROW(D12)", "100+B12", "COUNT(D12:E12)");
// no changes on row "3" // no changes on row "3"
confirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)"); confirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)");
confirmCell(sheet, 14, 0, 0.0, "#REF!"); confirmCell(sheet, 14, 0, 0.0, "#REF!");
// Formulas on rows that weren't shifted: // Formulas on rows that weren't shifted:
confirmCell(sheet, 6, 1, 271, "200+B1"); confirmCell(sheet, 6, 1, 271, "200+B1");
confirmCell(sheet, 7, 1, 272, "200+B12"); // this one moved confirmCell(sheet, 7, 1, 272, "200+B12"); // this one moved
confirmCell(sheet, 8, 1, 273, "200+B3"); confirmCell(sheet, 8, 1, 273, "200+B3");
// check formulas on other sheets // check formulas on other sheets
Sheet sheet2 = wb.getSheet("Sheet2"); Sheet sheet2 = wb.getSheet("Sheet2");
confirmCell(sheet2, 0, 0, 371, "300+Sheet1!B1"); confirmCell(sheet2, 0, 0, 371, "300+Sheet1!B1");
confirmCell(sheet2, 1, 0, 372, "300+Sheet1!B12"); confirmCell(sheet2, 1, 0, 372, "300+Sheet1!B12");
confirmCell(sheet2, 2, 0, 373, "300+Sheet1!B3"); confirmCell(sheet2, 2, 0, 373, "300+Sheet1!B3");
confirmCell(sheet2, 11, 0, 300, "300+Sheet1!#REF!"); confirmCell(sheet2, 11, 0, 300, "300+Sheet1!#REF!");
// Note - named ranges formulas have not been updated // Note - named ranges formulas have not been updated
} }
private static void confirmRow(Sheet sheet, int rowIx, double valA, double valB, double valC, private static void confirmRow(Sheet sheet, int rowIx, double valA, double valB, double valC,
String formulaA, String formulaB, String formulaC) { String formulaA, String formulaB, String formulaC) {
confirmCell(sheet, rowIx, 4, valA, formulaA); confirmCell(sheet, rowIx, 4, valA, formulaA);
confirmCell(sheet, rowIx, 5, valB, formulaB); confirmCell(sheet, rowIx, 5, valB, formulaB);
confirmCell(sheet, rowIx, 6, valC, formulaC); confirmCell(sheet, rowIx, 6, valC, formulaC);
} }
private static void confirmCell(Sheet sheet, int rowIx, int colIx, private static void confirmCell(Sheet sheet, int rowIx, int colIx,
double expectedValue, String expectedFormula) { double expectedValue, String expectedFormula) {
Cell cell = sheet.getRow(rowIx).getCell(colIx); Cell cell = sheet.getRow(rowIx).getCell(colIx);
assertEquals(expectedValue, cell.getNumericCellValue(), 0.0); assertEquals(expectedValue, cell.getNumericCellValue(), 0.0);
assertEquals(expectedFormula, cell.getCellFormula()); assertEquals(expectedFormula, cell.getCellFormula());
} }
} }

View File

@ -1,355 +1,366 @@
package org.apache.poi.ss.usermodel; /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
import junit.framework.TestCase; contributor license agreements. See the NOTICE file distributed with
import junit.framework.AssertionFailedError; this work for additional information regarding copyright ownership.
import org.apache.poi.ss.ITestDataProvider; The ASF licenses this file to You under the Apache License, Version 2.0
import org.apache.poi.ss.util.CellRangeAddress; (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
/**
* @author Yegor Kozlov http://www.apache.org/licenses/LICENSE-2.0
*/
public abstract class BaseTestWorkbook extends TestCase { Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
protected abstract ITestDataProvider getTestDataProvider(); WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
public void testCreateSheet() { limitations under the License.
Workbook wb = getTestDataProvider().createWorkbook(); ==================================================================== */
assertEquals(0, wb.getNumberOfSheets());
package org.apache.poi.ss.usermodel;
//getting a sheet by invalid index or non-existing name
assertNull(wb.getSheet("Sheet1")); import junit.framework.TestCase;
try { import junit.framework.AssertionFailedError;
wb.getSheetAt(0); import org.apache.poi.ss.ITestDataProvider;
fail("should have thrown exceptiuon due to invalid sheet index"); import org.apache.poi.ss.util.CellRangeAddress;
} catch (IllegalArgumentException e) {
// expected during successful test /**
; * @author Yegor Kozlov
} */
public abstract class BaseTestWorkbook extends TestCase {
Sheet sheet0 = wb.createSheet();
Sheet sheet1 = wb.createSheet(); protected abstract ITestDataProvider getTestDataProvider();
assertEquals("Sheet0", sheet0.getSheetName());
assertEquals("Sheet1", sheet1.getSheetName()); public void testCreateSheet() {
assertEquals(2, wb.getNumberOfSheets()); Workbook wb = getTestDataProvider().createWorkbook();
assertEquals(0, wb.getNumberOfSheets());
//fetching sheets by name is case-insensitive
Sheet originalSheet = wb.createSheet("Sheet3"); //getting a sheet by invalid index or non-existing name
Sheet fetchedSheet = wb.getSheet("sheet3"); assertNull(wb.getSheet("Sheet1"));
if (fetchedSheet == null) { try {
throw new AssertionFailedError("Identified bug 44892"); wb.getSheetAt(0);
} fail("should have thrown exceptiuon due to invalid sheet index");
assertEquals("Sheet3", fetchedSheet.getSheetName()); } catch (IllegalArgumentException e) {
assertEquals(3, wb.getNumberOfSheets()); // expected during successful test
assertSame(originalSheet, fetchedSheet); }
try {
wb.createSheet("sHeeT3"); Sheet sheet0 = wb.createSheet();
fail("should have thrown exceptiuon due to duplicate sheet name"); Sheet sheet1 = wb.createSheet();
} catch (IllegalArgumentException e) { assertEquals("Sheet0", sheet0.getSheetName());
// expected during successful test assertEquals("Sheet1", sheet1.getSheetName());
assertEquals("The workbook already contains a sheet of this name", e.getMessage()); assertEquals(2, wb.getNumberOfSheets());
}
//fetching sheets by name is case-insensitive
//names cannot be blank or contain any of /\*?[] Sheet originalSheet = wb.createSheet("Sheet3");
String[] invalidNames = {"", "Sheet/", "Sheet\\", Sheet fetchedSheet = wb.getSheet("sheet3");
"Sheet?", "Sheet*", "Sheet[", "Sheet]"}; if (fetchedSheet == null) {
for (String sheetName : invalidNames) { throw new AssertionFailedError("Identified bug 44892");
try { }
wb.createSheet(sheetName); assertEquals("Sheet3", fetchedSheet.getSheetName());
fail("should have thrown exceptiuon due to invalid sheet name: " + sheetName); assertEquals(3, wb.getNumberOfSheets());
} catch (IllegalArgumentException e) { assertSame(originalSheet, fetchedSheet);
// expected during successful test try {
; wb.createSheet("sHeeT3");
} fail("should have thrown exceptiuon due to duplicate sheet name");
} } catch (IllegalArgumentException e) {
//still have 3 sheets // expected during successful test
assertEquals(3, wb.getNumberOfSheets()); assertEquals("The workbook already contains a sheet of this name", e.getMessage());
}
//change the name of the 3rd sheet
wb.setSheetName(2, "I changed!"); //names cannot be blank or contain any of /\*?[]
String[] invalidNames = {"", "Sheet/", "Sheet\\",
//try to assign an invalid name to the 2nd sheet "Sheet?", "Sheet*", "Sheet[", "Sheet]"};
try { for (String sheetName : invalidNames) {
wb.setSheetName(1, "[I'm invalid]"); try {
fail("should have thrown exceptiuon due to invalid sheet name"); wb.createSheet(sheetName);
} catch (IllegalArgumentException e) { fail("should have thrown exception due to invalid sheet name: " + sheetName);
; // expected during successful test } catch (IllegalArgumentException e) {
} // expected during successful test
}
//check }
assertEquals(0, wb.getSheetIndex("sheet0")); //still have 3 sheets
assertEquals(1, wb.getSheetIndex("sheet1")); assertEquals(3, wb.getNumberOfSheets());
assertEquals(2, wb.getSheetIndex("I changed!"));
//change the name of the 3rd sheet
assertSame(sheet0, wb.getSheet("sheet0")); wb.setSheetName(2, "I changed!");
assertSame(sheet1, wb.getSheet("sheet1"));
assertSame(originalSheet, wb.getSheet("I changed!")); //try to assign an invalid name to the 2nd sheet
assertNull(wb.getSheet("unknown")); try {
wb.setSheetName(1, "[I'm invalid]");
//serialize and read again fail("should have thrown exceptiuon due to invalid sheet name");
wb = getTestDataProvider().writeOutAndReadBack(wb); } catch (IllegalArgumentException e) {
assertEquals(3, wb.getNumberOfSheets()); ; // expected during successful test
assertEquals(0, wb.getSheetIndex("sheet0")); }
assertEquals(1, wb.getSheetIndex("sheet1"));
assertEquals(2, wb.getSheetIndex("I changed!")); //check
assertEquals(0, wb.getSheetIndex("sheet0"));
} assertEquals(1, wb.getSheetIndex("sheet1"));
assertEquals(2, wb.getSheetIndex("I changed!"));
public void testRemoveSheetAt() {
Workbook workbook = getTestDataProvider().createWorkbook(); assertSame(sheet0, wb.getSheet("sheet0"));
workbook.createSheet("sheet1"); assertSame(sheet1, wb.getSheet("sheet1"));
workbook.createSheet("sheet2"); assertSame(originalSheet, wb.getSheet("I changed!"));
workbook.createSheet("sheet3"); assertNull(wb.getSheet("unknown"));
assertEquals(3, workbook.getNumberOfSheets());
workbook.removeSheetAt(1); //serialize and read again
assertEquals(2, workbook.getNumberOfSheets()); wb = getTestDataProvider().writeOutAndReadBack(wb);
assertEquals("sheet3", workbook.getSheetName(1)); assertEquals(3, wb.getNumberOfSheets());
workbook.removeSheetAt(0); assertEquals(0, wb.getSheetIndex("sheet0"));
assertEquals(1, workbook.getNumberOfSheets()); assertEquals(1, wb.getSheetIndex("sheet1"));
assertEquals("sheet3", workbook.getSheetName(0)); assertEquals(2, wb.getSheetIndex("I changed!"));
workbook.removeSheetAt(0); }
assertEquals(0, workbook.getNumberOfSheets());
public void testRemoveSheetAt() {
//re-create the sheets Workbook workbook = getTestDataProvider().createWorkbook();
workbook.createSheet("sheet1"); workbook.createSheet("sheet1");
workbook.createSheet("sheet2"); workbook.createSheet("sheet2");
workbook.createSheet("sheet3"); workbook.createSheet("sheet3");
assertEquals(3, workbook.getNumberOfSheets()); assertEquals(3, workbook.getNumberOfSheets());
} workbook.removeSheetAt(1);
assertEquals(2, workbook.getNumberOfSheets());
public void testDefaultValues() { assertEquals("sheet3", workbook.getSheetName(1));
Workbook b = getTestDataProvider().createWorkbook(); workbook.removeSheetAt(0);
assertEquals(0, b.getActiveSheetIndex()); assertEquals(1, workbook.getNumberOfSheets());
assertEquals(0, b.getFirstVisibleTab()); assertEquals("sheet3", workbook.getSheetName(0));
assertEquals(0, b.getNumberOfNames()); workbook.removeSheetAt(0);
assertEquals(0, b.getNumberOfSheets()); assertEquals(0, workbook.getNumberOfSheets());
}
//re-create the sheets
workbook.createSheet("sheet1");
public void testSheetSelection() { workbook.createSheet("sheet2");
Workbook b = getTestDataProvider().createWorkbook(); workbook.createSheet("sheet3");
b.createSheet("Sheet One"); assertEquals(3, workbook.getNumberOfSheets());
b.createSheet("Sheet Two"); }
b.setActiveSheet(1);
b.setSelectedTab(1); public void testDefaultValues() {
b.setFirstVisibleTab(1); Workbook b = getTestDataProvider().createWorkbook();
assertEquals(1, b.getActiveSheetIndex()); assertEquals(0, b.getActiveSheetIndex());
assertEquals(1, b.getFirstVisibleTab()); assertEquals(0, b.getFirstVisibleTab());
} assertEquals(0, b.getNumberOfNames());
assertEquals(0, b.getNumberOfSheets());
public void testPrintArea() { }
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet1 = workbook.createSheet("Test Print Area"); public void testSheetSelection() {
String sheetName1 = sheet1.getSheetName(); Workbook b = getTestDataProvider().createWorkbook();
b.createSheet("Sheet One");
// workbook.setPrintArea(0, reference); b.createSheet("Sheet Two");
workbook.setPrintArea(0, 1, 5, 4, 9); b.setActiveSheet(1);
String retrievedPrintArea = workbook.getPrintArea(0); b.setSelectedTab(1);
assertEquals("'" + sheetName1 + "'!$B$5:$F$10", retrievedPrintArea); b.setFirstVisibleTab(1);
assertEquals(1, b.getActiveSheetIndex());
String reference = "$A$1:$B$1"; assertEquals(1, b.getFirstVisibleTab());
workbook.setPrintArea(0, reference); }
retrievedPrintArea = workbook.getPrintArea(0);
assertEquals("'" + sheetName1 + "'!" + reference, retrievedPrintArea); public void testPrintArea() {
Workbook workbook = getTestDataProvider().createWorkbook();
workbook.removePrintArea(0); Sheet sheet1 = workbook.createSheet("Test Print Area");
assertNull(workbook.getPrintArea(0)); String sheetName1 = sheet1.getSheetName();
}
// workbook.setPrintArea(0, reference);
public void testGetSetActiveSheet(){ workbook.setPrintArea(0, 1, 5, 4, 9);
Workbook workbook = getTestDataProvider().createWorkbook(); String retrievedPrintArea = workbook.getPrintArea(0);
assertEquals(0, workbook.getActiveSheetIndex()); assertEquals("'" + sheetName1 + "'!$B$5:$F$10", retrievedPrintArea);
workbook.createSheet("sheet1"); String reference = "$A$1:$B$1";
workbook.createSheet("sheet2"); workbook.setPrintArea(0, reference);
workbook.createSheet("sheet3"); retrievedPrintArea = workbook.getPrintArea(0);
// set second sheet assertEquals("'" + sheetName1 + "'!" + reference, retrievedPrintArea);
workbook.setActiveSheet(1);
// test if second sheet is set up workbook.removePrintArea(0);
assertEquals(1, workbook.getActiveSheetIndex()); assertNull(workbook.getPrintArea(0));
}
workbook.setActiveSheet(0);
// test if second sheet is set up public void testGetSetActiveSheet(){
assertEquals(0, workbook.getActiveSheetIndex()); Workbook workbook = getTestDataProvider().createWorkbook();
} assertEquals(0, workbook.getActiveSheetIndex());
public void testSetSheetOrder() { workbook.createSheet("sheet1");
Workbook wb = getTestDataProvider().createWorkbook(); workbook.createSheet("sheet2");
workbook.createSheet("sheet3");
for (int i=0; i < 10; i++) { // set second sheet
Sheet sh = wb.createSheet("Sheet " + i); workbook.setActiveSheet(1);
} // test if second sheet is set up
assertEquals(1, workbook.getActiveSheetIndex());
// Check the initial order
assertEquals(0, wb.getSheetIndex("Sheet 0")); workbook.setActiveSheet(0);
assertEquals(1, wb.getSheetIndex("Sheet 1")); // test if second sheet is set up
assertEquals(2, wb.getSheetIndex("Sheet 2")); assertEquals(0, workbook.getActiveSheetIndex());
assertEquals(3, wb.getSheetIndex("Sheet 3")); }
assertEquals(4, wb.getSheetIndex("Sheet 4"));
assertEquals(5, wb.getSheetIndex("Sheet 5")); public void testSetSheetOrder() {
assertEquals(6, wb.getSheetIndex("Sheet 6")); Workbook wb = getTestDataProvider().createWorkbook();
assertEquals(7, wb.getSheetIndex("Sheet 7"));
assertEquals(8, wb.getSheetIndex("Sheet 8")); for (int i=0; i < 10; i++) {
assertEquals(9, wb.getSheetIndex("Sheet 9")); wb.createSheet("Sheet " + i);
}
// Change
wb.setSheetOrder("Sheet 6", 0); // Check the initial order
wb.setSheetOrder("Sheet 3", 7); assertEquals(0, wb.getSheetIndex("Sheet 0"));
wb.setSheetOrder("Sheet 1", 9); assertEquals(1, wb.getSheetIndex("Sheet 1"));
assertEquals(2, wb.getSheetIndex("Sheet 2"));
// Check they're currently right assertEquals(3, wb.getSheetIndex("Sheet 3"));
assertEquals(0, wb.getSheetIndex("Sheet 6")); assertEquals(4, wb.getSheetIndex("Sheet 4"));
assertEquals(1, wb.getSheetIndex("Sheet 0")); assertEquals(5, wb.getSheetIndex("Sheet 5"));
assertEquals(2, wb.getSheetIndex("Sheet 2")); assertEquals(6, wb.getSheetIndex("Sheet 6"));
assertEquals(3, wb.getSheetIndex("Sheet 4")); assertEquals(7, wb.getSheetIndex("Sheet 7"));
assertEquals(4, wb.getSheetIndex("Sheet 5")); assertEquals(8, wb.getSheetIndex("Sheet 8"));
assertEquals(5, wb.getSheetIndex("Sheet 7")); assertEquals(9, wb.getSheetIndex("Sheet 9"));
assertEquals(6, wb.getSheetIndex("Sheet 3"));
assertEquals(7, wb.getSheetIndex("Sheet 8")); // Change
assertEquals(8, wb.getSheetIndex("Sheet 9")); wb.setSheetOrder("Sheet 6", 0);
assertEquals(9, wb.getSheetIndex("Sheet 1")); wb.setSheetOrder("Sheet 3", 7);
wb.setSheetOrder("Sheet 1", 9);
Workbook wbr = getTestDataProvider().writeOutAndReadBack(wb);
// Check they're currently right
assertEquals(0, wbr.getSheetIndex("Sheet 6")); assertEquals(0, wb.getSheetIndex("Sheet 6"));
assertEquals(1, wbr.getSheetIndex("Sheet 0")); assertEquals(1, wb.getSheetIndex("Sheet 0"));
assertEquals(2, wbr.getSheetIndex("Sheet 2")); assertEquals(2, wb.getSheetIndex("Sheet 2"));
assertEquals(3, wbr.getSheetIndex("Sheet 4")); assertEquals(3, wb.getSheetIndex("Sheet 4"));
assertEquals(4, wbr.getSheetIndex("Sheet 5")); assertEquals(4, wb.getSheetIndex("Sheet 5"));
assertEquals(5, wbr.getSheetIndex("Sheet 7")); assertEquals(5, wb.getSheetIndex("Sheet 7"));
assertEquals(6, wbr.getSheetIndex("Sheet 3")); assertEquals(6, wb.getSheetIndex("Sheet 3"));
assertEquals(7, wbr.getSheetIndex("Sheet 8")); assertEquals(7, wb.getSheetIndex("Sheet 8"));
assertEquals(8, wbr.getSheetIndex("Sheet 9")); assertEquals(8, wb.getSheetIndex("Sheet 9"));
assertEquals(9, wbr.getSheetIndex("Sheet 1")); assertEquals(9, wb.getSheetIndex("Sheet 1"));
// Now get the index by the sheet, not the name Workbook wbr = getTestDataProvider().writeOutAndReadBack(wb);
for(int i=0; i<10; i++) {
Sheet s = wbr.getSheetAt(i); assertEquals(0, wbr.getSheetIndex("Sheet 6"));
assertEquals(i, wbr.getSheetIndex(s)); assertEquals(1, wbr.getSheetIndex("Sheet 0"));
} assertEquals(2, wbr.getSheetIndex("Sheet 2"));
} assertEquals(3, wbr.getSheetIndex("Sheet 4"));
assertEquals(4, wbr.getSheetIndex("Sheet 5"));
public void testCloneSheet() { assertEquals(5, wbr.getSheetIndex("Sheet 7"));
Workbook book = getTestDataProvider().createWorkbook(); assertEquals(6, wbr.getSheetIndex("Sheet 3"));
Sheet sheet = book.createSheet("TEST"); assertEquals(7, wbr.getSheetIndex("Sheet 8"));
sheet.createRow(0).createCell(0).setCellValue("Test"); assertEquals(8, wbr.getSheetIndex("Sheet 9"));
sheet.createRow(1).createCell(0).setCellValue(36.6); assertEquals(9, wbr.getSheetIndex("Sheet 1"));
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 2));
sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 2)); // Now get the index by the sheet, not the name
assertTrue(sheet.isSelected()); for(int i=0; i<10; i++) {
Sheet s = wbr.getSheetAt(i);
Sheet clonedSheet = book.cloneSheet(0); assertEquals(i, wbr.getSheetIndex(s));
assertEquals("TEST (2)", clonedSheet.getSheetName()); }
assertEquals(2, clonedSheet.getPhysicalNumberOfRows()); }
assertEquals(2, clonedSheet.getNumMergedRegions());
assertFalse(clonedSheet.isSelected()); public void testCloneSheet() {
Workbook book = getTestDataProvider().createWorkbook();
//cloned sheet is a deep copy, adding rows in the original does not affect the clone Sheet sheet = book.createSheet("TEST");
sheet.createRow(2).createCell(0).setCellValue(1); sheet.createRow(0).createCell(0).setCellValue("Test");
sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 2)); sheet.createRow(1).createCell(0).setCellValue(36.6);
assertEquals(2, clonedSheet.getPhysicalNumberOfRows()); sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 2));
assertEquals(2, clonedSheet.getPhysicalNumberOfRows()); sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 2));
assertTrue(sheet.isSelected());
clonedSheet.createRow(2).createCell(0).setCellValue(1);
clonedSheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 2)); Sheet clonedSheet = book.cloneSheet(0);
assertEquals(3, clonedSheet.getPhysicalNumberOfRows()); assertEquals("TEST (2)", clonedSheet.getSheetName());
assertEquals(3, clonedSheet.getPhysicalNumberOfRows()); assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
assertEquals(2, clonedSheet.getNumMergedRegions());
} assertFalse(clonedSheet.isSelected());
public void testParentReferences(){ //cloned sheet is a deep copy, adding rows in the original does not affect the clone
Workbook workbook = getTestDataProvider().createWorkbook(); sheet.createRow(2).createCell(0).setCellValue(1);
Sheet sheet = workbook.createSheet(); sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 2));
assertSame(workbook, sheet.getWorkbook()); assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
Row row = sheet.createRow(0);
assertSame(sheet, row.getSheet()); clonedSheet.createRow(2).createCell(0).setCellValue(1);
clonedSheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 2));
Cell cell = row.createCell(1); assertEquals(3, clonedSheet.getPhysicalNumberOfRows());
assertSame(sheet, cell.getSheet()); assertEquals(3, clonedSheet.getPhysicalNumberOfRows());
assertSame(row, cell.getRow());
}
workbook = getTestDataProvider().writeOutAndReadBack(workbook);
sheet = workbook.getSheetAt(0); public void testParentReferences(){
assertSame(workbook, sheet.getWorkbook()); Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
row = sheet.getRow(0); assertSame(workbook, sheet.getWorkbook());
assertSame(sheet, row.getSheet());
Row row = sheet.createRow(0);
cell = row.getCell(1); assertSame(sheet, row.getSheet());
assertSame(sheet, cell.getSheet());
assertSame(row, cell.getRow()); Cell cell = row.createCell(1);
} assertSame(sheet, cell.getSheet());
assertSame(row, cell.getRow());
/** Tests that all of the unicode capable string fields can be set, written and then read back
* workbook = getTestDataProvider().writeOutAndReadBack(workbook);
* sheet = workbook.getSheetAt(0);
*/ assertSame(workbook, sheet.getWorkbook());
public void testUnicodeInAll() throws Exception {
Workbook wb = getTestDataProvider().createWorkbook(); row = sheet.getRow(0);
CreationHelper factory = wb.getCreationHelper(); assertSame(sheet, row.getSheet());
//Create a unicode dataformat (contains euro symbol)
DataFormat df = wb.createDataFormat(); cell = row.getCell(1);
final String formatStr = "_([$\u20ac-2]\\\\\\ * #,##0.00_);_([$\u20ac-2]\\\\\\ * \\\\\\(#,##0.00\\\\\\);_([$\u20ac-2]\\\\\\ *\\\"\\-\\\\\"??_);_(@_)"; assertSame(sheet, cell.getSheet());
short fmt = df.getFormat(formatStr); assertSame(row, cell.getRow());
}
//Create a unicode sheet name (euro symbol)
Sheet s = wb.createSheet("\u20ac"); /**
* Tests that all of the unicode capable string fields can be set, written and then read back
//Set a unicode header (you guessed it the euro symbol) */
Header h = s.getHeader(); public void testUnicodeInAll() {
h.setCenter("\u20ac"); Workbook wb = getTestDataProvider().createWorkbook();
h.setLeft("\u20ac"); CreationHelper factory = wb.getCreationHelper();
h.setRight("\u20ac"); //Create a unicode dataformat (contains euro symbol)
DataFormat df = wb.createDataFormat();
//Set a unicode footer final String formatStr = "_([$\u20ac-2]\\\\\\ * #,##0.00_);_([$\u20ac-2]\\\\\\ * \\\\\\(#,##0.00\\\\\\);_([$\u20ac-2]\\\\\\ *\\\"\\-\\\\\"??_);_(@_)";
Footer f = s.getFooter(); short fmt = df.getFormat(formatStr);
f.setCenter("\u20ac");
f.setLeft("\u20ac"); //Create a unicode sheet name (euro symbol)
f.setRight("\u20ac"); Sheet s = wb.createSheet("\u20ac");
Row r = s.createRow(0); //Set a unicode header (you guessed it the euro symbol)
Cell c = r.createCell(1); Header h = s.getHeader();
c.setCellValue(12.34); h.setCenter("\u20ac");
c.getCellStyle().setDataFormat(fmt); h.setLeft("\u20ac");
h.setRight("\u20ac");
Cell c2 = r.createCell(2);
c.setCellValue(factory.createRichTextString("\u20ac")); //Set a unicode footer
Footer f = s.getFooter();
Cell c3 = r.createCell(3); f.setCenter("\u20ac");
String formulaString = "TEXT(12.34,\"\u20ac###,##\")"; f.setLeft("\u20ac");
c3.setCellFormula(formulaString); f.setRight("\u20ac");
wb = getTestDataProvider().writeOutAndReadBack(wb); Row r = s.createRow(0);
Cell c = r.createCell(1);
//Test the sheetname c.setCellValue(12.34);
s = wb.getSheet("\u20ac"); c.getCellStyle().setDataFormat(fmt);
assertNotNull(s);
Cell c2 = r.createCell(2); // TODO - c2 unused but changing next line ('c'->'c2') causes test to fail
//Test the header c.setCellValue(factory.createRichTextString("\u20ac"));
h = s.getHeader();
assertEquals(h.getCenter(), "\u20ac"); Cell c3 = r.createCell(3);
assertEquals(h.getLeft(), "\u20ac"); String formulaString = "TEXT(12.34,\"\u20ac###,##\")";
assertEquals(h.getRight(), "\u20ac"); c3.setCellFormula(formulaString);
//Test the footer wb = getTestDataProvider().writeOutAndReadBack(wb);
f = s.getFooter();
assertEquals(f.getCenter(), "\u20ac"); //Test the sheetname
assertEquals(f.getLeft(), "\u20ac"); s = wb.getSheet("\u20ac");
assertEquals(f.getRight(), "\u20ac"); assertNotNull(s);
//Test the dataformat //Test the header
r = s.getRow(0); h = s.getHeader();
c = r.getCell(1); assertEquals(h.getCenter(), "\u20ac");
df = wb.createDataFormat(); assertEquals(h.getLeft(), "\u20ac");
assertEquals(formatStr, df.getFormat(c.getCellStyle().getDataFormat())); assertEquals(h.getRight(), "\u20ac");
//Test the cell string value //Test the footer
c2 = r.getCell(2); f = s.getFooter();
assertEquals(c.getRichStringCellValue().getString(), "\u20ac"); assertEquals(f.getCenter(), "\u20ac");
assertEquals(f.getLeft(), "\u20ac");
//Test the cell formula assertEquals(f.getRight(), "\u20ac");
c3 = r.getCell(3);
assertEquals(c3.getCellFormula(), formulaString); //Test the dataformat
} r = s.getRow(0);
c = r.getCell(1);
} df = wb.createDataFormat();
assertEquals(formatStr, df.getFormat(c.getCellStyle().getDataFormat()));
//Test the cell string value
c2 = r.getCell(2);
assertEquals(c.getRichStringCellValue().getString(), "\u20ac");
//Test the cell formula
c3 = r.getCell(3);
assertEquals(c3.getCellFormula(), formulaString);
}
}

View File

@ -1,55 +1,55 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.ss.util; package org.apache.poi.ss.util;
import junit.framework.TestCase; import junit.framework.TestCase;
/** /**
* Tests that the common CellReference works as we need it to * Tests that the common CellReference works as we need it to
*/ */
public class TestRegion extends TestCase { @SuppressWarnings("deprecation") // the Region class is deprecated in the public API, but still needs to be tested
public final class TestRegion extends TestCase {
public void testGetRegionRef() {
int rowFrom = 3; public void testGetRegionRef() {
short colFrom = 3; int rowFrom = 3;
int rowTo = 9; short colFrom = 3;
short colTo = 9; int rowTo = 9;
Region region = new Region(rowFrom, colFrom, rowTo, colTo); short colTo = 9;
assertEquals("D4:J10", region.getRegionRef()); Region region = new Region(rowFrom, colFrom, rowTo, colTo);
} assertEquals("D4:J10", region.getRegionRef());
}
public void testContains() {
int rowFrom = 3; public void testContains() {
short colFrom = 3; int rowFrom = 3;
int rowTo = 9; short colFrom = 3;
short colTo = 9; int rowTo = 9;
Region region = new Region(rowFrom, colFrom, rowTo, colTo); short colTo = 9;
assertEquals("D4:J10", region.getRegionRef()); Region region = new Region(rowFrom, colFrom, rowTo, colTo);
assertTrue(region.contains(5, (short) 7)); assertEquals("D4:J10", region.getRegionRef());
assertTrue(region.contains(9, (short) 9)); assertTrue(region.contains(5, (short) 7));
assertFalse(region.contains(9, (short) 10)); assertTrue(region.contains(9, (short) 9));
} assertFalse(region.contains(9, (short) 10));
}
public void testConstructors() {
Region region_1 = new Region("A1:E7"); public void testConstructors() {
assertEquals(0, region_1.getColumnFrom()); Region region_1 = new Region("A1:E7");
assertEquals((short)4, region_1.getColumnTo()); assertEquals(0, region_1.getColumnFrom());
} assertEquals((short)4, region_1.getColumnTo());
}
} }

View File

@ -1,53 +1,53 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.util; package org.apache.poi.util;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
/** /**
* Class to test {@link LittleEndianInputStream} and {@link LittleEndianOutputStream} * Class to test {@link LittleEndianInputStream} and {@link LittleEndianOutputStream}
* *
* @author Josh Micich * @author Josh Micich
*/ */
public final class TestLittleEndianStreams extends TestCase { public final class TestLittleEndianStreams extends TestCase {
public void testRead() { public void testRead() {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
LittleEndianOutput leo = new LittleEndianOutputStream(baos); LittleEndianOutput leo = new LittleEndianOutputStream(baos);
leo.writeInt(12345678); leo.writeInt(12345678);
leo.writeShort(12345); leo.writeShort(12345);
leo.writeByte(123); leo.writeByte(123);
leo.writeShort(40000); leo.writeShort(40000);
leo.writeByte(200); leo.writeByte(200);
leo.writeLong(1234567890123456789L); leo.writeLong(1234567890123456789L);
leo.writeDouble(123.456); leo.writeDouble(123.456);
LittleEndianInput lei = new LittleEndianInputStream(new ByteArrayInputStream(baos.toByteArray())); LittleEndianInput lei = new LittleEndianInputStream(new ByteArrayInputStream(baos.toByteArray()));
assertEquals(12345678, lei.readInt()); assertEquals(12345678, lei.readInt());
assertEquals(12345, lei.readShort()); assertEquals(12345, lei.readShort());
assertEquals(123, lei.readByte()); assertEquals(123, lei.readByte());
assertEquals(40000, lei.readUShort()); assertEquals(40000, lei.readUShort());
assertEquals(200, lei.readUByte()); assertEquals(200, lei.readUByte());
assertEquals(1234567890123456789L, lei.readLong()); assertEquals(1234567890123456789L, lei.readLong());
assertEquals(123.456, lei.readDouble(), 0.0); assertEquals(123.456, lei.readDouble(), 0.0);
} }
} }