sonar fixes

close resources in tests
fix gradle warnings

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1892683 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2021-08-28 23:48:48 +00:00
parent 6d9b450ce3
commit f71cebcce5
50 changed files with 1617 additions and 1688 deletions

View File

@ -209,7 +209,7 @@ subprojects {
// make XML test-results available for Jenkins CI
useJUnitPlatform()
reports {
junitXml.enabled = true
junitXml.required = true
}
// Exclude some tests that are not actually tests or do not run cleanly on purpose
@ -238,7 +238,7 @@ subprojects {
"-Dversion.id=${project.version}",
'-ea',
'-Djunit.jupiter.execution.parallel.config.strategy=fixed',
'-Djunit.jupiter.execution.parallel.config.fixed.parallelism=3'
'-Djunit.jupiter.execution.parallel.config.fixed.parallelism=2'
// -Xjit:verbose={compileStart|compileEnd},vlog=build/jit.log${no.jit.sherlock} ... if ${isIBMVM}
]
@ -278,7 +278,7 @@ subprojects {
jacocoTestReport {
reports {
xml.enabled true
xml.required = true
}
}
@ -396,6 +396,7 @@ subprojects {
spotbugs {
ignoreFailures = true
showStackTraces = false
}
}
@ -536,7 +537,7 @@ task replaceVersion() {
task zipJavadocs(type: Zip, dependsOn: allJavaDoc) {
from('build/docs/javadoc/')
destinationDir = file('build/dist')
destinationDirectory = file('build/dist')
archiveBaseName = 'poi'
archiveVersion = subprojects[0].version
archiveAppendix = 'javadoc'

View File

@ -65,6 +65,8 @@ task cacheJava9(type: Copy) {
}
jar {
dependsOn cacheJava9
destinationDirectory = file("../build/dist/maven/${project.archivesBaseName}")
if (JavaVersion.current() == JavaVersion.VERSION_1_8) {

View File

@ -105,6 +105,8 @@ task cacheTest9(type: Copy) {
}
jar {
dependsOn cacheJava9
destinationDirectory = file("../build/dist/maven/${project.archivesBaseName}")
if (JavaVersion.current() == JavaVersion.VERSION_1_8) {
@ -120,7 +122,7 @@ jar {
// Create a separate jar for test-code to depend on it in other projects
// See http://stackoverflow.com/questions/5144325/gradle-test-dependency
task testJar(type: Jar, dependsOn: testClasses) {
task testJar(type: Jar, dependsOn: [ testClasses, cacheTest9 ] ) {
destinationDirectory = file("../build/dist/maven/${project.archivesBaseName}-tests")
classifier 'tests'

View File

@ -96,7 +96,7 @@ jar {
// Create a separate jar for test-code to depend on it in other projects
// See http://stackoverflow.com/questions/5144325/gradle-test-dependency
task testJar(type: Jar, dependsOn: testClasses) {
task testJar(type: Jar, dependsOn: [ testClasses, cacheTest9 ] ) {
destinationDirectory = file("../build/dist/maven/${project.archivesBaseName}-tests")
classifier 'tests'

View File

@ -37,6 +37,7 @@ import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
* types of files/exceptions, e.g. old file formats.
*
*/
@SuppressWarnings({"java:S2187", "unused"})
public class BaseIntegrationTest {
private final File rootDir;
private final String file;

View File

@ -17,6 +17,8 @@
package org.apache.poi.stress;
import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
import static org.apache.poi.xssf.XSSFTestDataSamples.getSampleFile;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ -219,12 +221,14 @@ class XSSFFileHandler extends SpreadsheetHandler {
}
@Test
void testExtracting() throws Exception {
handleExtracting(new File("test-data/spreadsheet/ref-56737.xlsx"));
void testExtracting() {
File testFile = getSampleFile("ref-56737.xlsx");
assertDoesNotThrow(() -> handleExtracting(testFile));
}
@Test
void testAdditional() throws Exception {
handleAdditional(new File("test-data/spreadsheet/poc-xmlbomb.xlsx"));
void testAdditional() {
File testFile = getSampleFile("poc-xmlbomb.xlsx");
assertDoesNotThrow(() -> handleAdditional(testFile));
}
}

View File

@ -141,3 +141,5 @@ jar {
}
}
spotbugsTest.enabled = false
spotbugsMain.enabled = false

View File

@ -66,7 +66,7 @@ import org.ietf.jgss.Oid;
}
public byte[] sign() throws IOException, GeneralSecurityException {
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
bos.write(getHashMagic());
bos.write(md.digest());
@ -74,6 +74,7 @@ import org.ietf.jgss.Oid;
, ChainingMode.ecb, null, Cipher.ENCRYPT_MODE, "PKCS1Padding");
return cipher.doFinal(bos.toByteArray());
}
}
static boolean isMSCapi(final PrivateKey key) {
return key != null && key.getClass().getName().contains("mscapi");
@ -91,10 +92,9 @@ import org.ietf.jgss.Oid;
// in an earlier release the hashMagic (aka DigestAlgorithmIdentifier) contained only
// an object identifier, but to conform with the header generated by the
// javax-signature API, the empty <associated parameters> are also included
try {
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
final byte[] oidBytes = new Oid(algo.rsaOid).getDER();
final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
bos.write(0x30);
bos.write(algo.hashSize+oidBytes.length+6);
bos.write(0x30);

View File

@ -90,13 +90,14 @@ public class OOXMLURIDereferencer implements URIDereferencer {
// although xmlsec has an option to ignore line breaks, currently this
// only affects .rels files, so we only modify these
// http://stackoverflow.com/questions/4728300
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
for (int ch; (ch = dataStream.read()) != -1; ) {
if (ch == 10 || ch == 13) continue;
bos.write(ch);
}
dataStream = bos.toInputStream();
}
}
} catch (IOException e) {
throw new URIReferenceException("I/O error: " + e.getMessage(), e);
}

View File

@ -289,8 +289,7 @@ public class XAdESXLSignatureFacet implements SignatureFacet {
}
public static byte[] getC14nValue(List<Node> nodeList, String c14nAlgoId) {
UnsynchronizedByteArrayOutputStream c14nValue = new UnsynchronizedByteArrayOutputStream();
try {
try (UnsynchronizedByteArrayOutputStream c14nValue = new UnsynchronizedByteArrayOutputStream()) {
for (Node node : nodeList) {
/*
* Re-initialize the c14n else the namespaces will get cached
@ -299,12 +298,12 @@ public class XAdESXLSignatureFacet implements SignatureFacet {
Canonicalizer c14n = Canonicalizer.getInstance(c14nAlgoId);
c14n.canonicalizeSubtree(node, c14nValue);
}
return c14nValue.toByteArray();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("c14n error: " + e.getMessage(), e);
}
return c14nValue.toByteArray();
}
private BigInteger getCrlNumber(X509CRL crl) {

View File

@ -27,7 +27,7 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCfvoType;
* Colour Scale change thresholds
*/
public class XSSFConditionalFormattingThreshold implements org.apache.poi.ss.usermodel.ConditionalFormattingThreshold {
private CTCfvo cfvo;
private final CTCfvo cfvo;
protected XSSFConditionalFormattingThreshold(CTCfvo cfvo) {
this.cfvo = cfvo;
@ -37,24 +37,29 @@ public class XSSFConditionalFormattingThreshold implements org.apache.poi.ss.use
return cfvo;
}
@Override
public RangeType getRangeType() {
return RangeType.byName(cfvo.getType().toString());
}
@Override
public void setRangeType(RangeType type) {
STCfvoType.Enum xtype = STCfvoType.Enum.forString(type.name);
cfvo.setType(xtype);
}
@Override
public String getFormula() {
if (cfvo.getType() == STCfvoType.FORMULA) {
return cfvo.getVal();
}
return null;
}
@Override
public void setFormula(String formula) {
cfvo.setVal(formula);
}
@Override
public Double getValue() {
if (cfvo.getType() == STCfvoType.FORMULA ||
cfvo.getType() == STCfvoType.MIN ||
@ -67,6 +72,7 @@ public class XSSFConditionalFormattingThreshold implements org.apache.poi.ss.use
return null;
}
}
@Override
public void setValue(Double value) {
if (value == null) {
cfvo.unsetVal();

View File

@ -35,33 +35,40 @@ public class XSSFIconMultiStateFormatting implements IconMultiStateFormatting {
_iconset = iconset;
}
@Override
public IconSet getIconSet() {
String set = _iconset.getIconSet().toString();
return IconSet.byName(set);
}
@Override
public void setIconSet(IconSet set) {
STIconSetType.Enum xIconSet = STIconSetType.Enum.forString(set.name);
_iconset.setIconSet(xIconSet);
}
@Override
public boolean isIconOnly() {
if (_iconset.isSetShowValue())
return !_iconset.getShowValue();
return false;
}
@Override
public void setIconOnly(boolean only) {
_iconset.setShowValue(!only);
}
@Override
public boolean isReversed() {
if (_iconset.isSetReverse())
return _iconset.getReverse();
return false;
}
@Override
public void setReversed(boolean reversed) {
_iconset.setReverse(reversed);
}
@Override
public XSSFConditionalFormattingThreshold[] getThresholds() {
CTCfvo[] cfvos = _iconset.getCfvoArray();
XSSFConditionalFormattingThreshold[] t =
@ -71,6 +78,7 @@ public class XSSFIconMultiStateFormatting implements IconMultiStateFormatting {
}
return t;
}
@Override
public void setThresholds(ConditionalFormattingThreshold[] thresholds) {
CTCfvo[] cfvos = new CTCfvo[thresholds.length];
for (int i=0; i<thresholds.length; i++) {
@ -78,6 +86,7 @@ public class XSSFIconMultiStateFormatting implements IconMultiStateFormatting {
}
_iconset.setCfvoArray(cfvos);
}
@Override
public XSSFConditionalFormattingThreshold createThreshold() {
return new XSSFConditionalFormattingThreshold(_iconset.addNewCfvo());
}

View File

@ -139,6 +139,7 @@ public class XSSFWorkbookFactory implements WorkbookProvider {
* @throws IOException if an error occurs while reading the data
* @throws EncryptedDocumentException If the wrong password is given for a protected file
*/
@Override
@SuppressWarnings("resource")
public XSSFWorkbook create(File file, String password, boolean readOnly) throws IOException {
FileMagic fm = FileMagic.valueOf(file);

View File

@ -45,7 +45,6 @@ import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.model.MapInfo;
import org.apache.poi.xssf.usermodel.XSSFMap;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
@ -216,15 +215,13 @@ public final class TestXSSFExportToXML {
}
@Test
@Disabled(value="Fails, but I don't know if it is ok or not...")
void testExportToXMLSingleAttributeNamespace() throws Exception {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx")) {
for (XSSFMap map : wb.getCustomXMLMappings()) {
XSSFExportToXml exporter = new XSSFExportToXml(map);
UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
SAXParseException ex = assertThrows(SAXParseException.class, () -> exporter.exportToXML(os, true));
assertEquals("schema_reference: Failed to read schema document 'Schema11', because 'file' access is not allowed due to restriction set by the accessExternalSchema property.", ex.getMessage().trim());
}
}
}

View File

@ -41,6 +41,8 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook {
@ -90,39 +92,37 @@ public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook {
@Test
void existingWorkbook() throws IOException {
XSSFWorkbook xssfWb1 = new XSSFWorkbook();
try (XSSFWorkbook xssfWb1 = new XSSFWorkbook()) {
xssfWb1.createSheet("S1");
DeferredSXSSFWorkbook wb1 = new DeferredSXSSFWorkbook(xssfWb1);
XSSFWorkbook xssfWb2 = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb1);
try (DeferredSXSSFWorkbook wb1 = new DeferredSXSSFWorkbook(xssfWb1);
XSSFWorkbook xssfWb2 = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb1)) {
assertTrue(wb1.dispose());
DeferredSXSSFWorkbook wb2 = new DeferredSXSSFWorkbook(xssfWb2);
try (DeferredSXSSFWorkbook wb2 = new DeferredSXSSFWorkbook(xssfWb2)) {
assertEquals(1, wb2.getNumberOfSheets());
Sheet sheet = wb2.getStreamingSheetAt(0);
assertNotNull(sheet);
assertEquals("S1", sheet.getSheetName());
assertTrue(wb2.dispose());
xssfWb2.close();
xssfWb1.close();
wb2.close();
wb1.close();
}
}
}
}
@Test
void addToExistingWorkbook() throws IOException {
XSSFWorkbook xssfWb1 = new XSSFWorkbook();
try (XSSFWorkbook xssfWb1 = new XSSFWorkbook()) {
xssfWb1.createSheet("S1");
Sheet sheet = xssfWb1.createSheet("S2");
Row row = sheet.createRow(1);
Cell cell = row.createCell(1);
cell.setCellValue("value 2_1_1");
DeferredSXSSFWorkbook wb1 = new DeferredSXSSFWorkbook(xssfWb1);
XSSFWorkbook xssfWb2 = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb1);
assertTrue(wb1.dispose());
xssfWb1.close();
DeferredSXSSFWorkbook wb2 = new DeferredSXSSFWorkbook(xssfWb2);
try (DeferredSXSSFWorkbook wb1 = new DeferredSXSSFWorkbook(xssfWb1);
XSSFWorkbook xssfWb2 = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb1)) {
assertTrue(wb1.dispose());
try (DeferredSXSSFWorkbook wb2 = new DeferredSXSSFWorkbook(xssfWb2)) {
// Add a row to the existing empty sheet
DeferredSXSSFSheet ssheet1 = wb2.getStreamingSheetAt(0);
ssheet1.setRowGenerator((ssxSheet) -> {
@ -146,8 +146,7 @@ public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook {
cell3_1_1.setCellValue("value 3_1_1");
});
XSSFWorkbook xssfWb3 = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb2);
wb2.close();
try (XSSFWorkbook xssfWb3 = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb2)) {
assertEquals(3, xssfWb3.getNumberOfSheets());
// Verify sheet 1
@ -182,20 +181,20 @@ public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook {
XSSFCell cell3_1_1 = row3_1.getCell(1);
assertNotNull(cell3_1_1);
assertEquals("value 3_1_1", cell3_1_1.getStringCellValue());
xssfWb2.close();
xssfWb3.close();
wb1.close();
}
}
}
}
}
@Test
void sheetdataWriter() throws IOException {
DeferredSXSSFWorkbook wb = new DeferredSXSSFWorkbook();
try (DeferredSXSSFWorkbook wb = new DeferredSXSSFWorkbook()) {
SXSSFSheet sh = wb.createSheet();
assertSame(sh.getClass(), DeferredSXSSFSheet.class);
SheetDataWriter wr = sh.getSheetDataWriter();
assertNull(wr);
wb.close();
}
}
@Test
@ -225,13 +224,13 @@ public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook {
@Test
void gzipSheetdataWriter() throws IOException {
DeferredSXSSFWorkbook wb = new DeferredSXSSFWorkbook();
try (DeferredSXSSFWorkbook wb = new DeferredSXSSFWorkbook()) {
final int rowNum = 1000;
final int sheetNum = 5;
populateData(wb, 1000, 5);
populateData(wb);
XSSFWorkbook xwb = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb);
try (XSSFWorkbook xwb = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb)) {
for (int i = 0; i < sheetNum; i++) {
Sheet sh = xwb.getSheetAt(i);
assertEquals("sheet" + i, sh.getSheetName());
@ -250,26 +249,19 @@ public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook {
}
assertTrue(wb.dispose());
xwb.close();
wb.close();
}
}
}
@Test
void workbookDispose() throws IOException {
DeferredSXSSFWorkbook wb1 = new DeferredSXSSFWorkbook();
// the underlying writer is SheetDataWriter
assertWorkbookDispose(wb1);
wb1.close();
@ParameterizedTest
@ValueSource(booleans = {false, true})
void workbookDispose(boolean compressTempFiles) throws IOException {
try (DeferredSXSSFWorkbook wb = new DeferredSXSSFWorkbook()) {
// compressTempFiles == false: the underlying writer is SheetDataWriter
// compressTempFiles == true: the underlying writer is GZIPSheetDataWriter
wb.setCompressTempFiles(compressTempFiles);
DeferredSXSSFWorkbook wb2 = new DeferredSXSSFWorkbook();
wb2.setCompressTempFiles(true);
// the underlying writer is GZIPSheetDataWriter
assertWorkbookDispose(wb2);
wb2.close();
}
private static void assertWorkbookDispose(DeferredSXSSFWorkbook wb) {
populateData(wb, 1000, 5);
populateData(wb);
for (Sheet sheet : wb) {
DeferredSXSSFSheet sxSheet = (DeferredSXSSFSheet) sheet;
@ -283,13 +275,14 @@ public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook {
assertNull(sxSheet.getSheetDataWriter());
}
}
}
private static void populateData(DeferredSXSSFWorkbook wb, final int rowNum, final int sheetNum) {
for (int i = 0; i < sheetNum; i++) {
private static void populateData(DeferredSXSSFWorkbook wb) {
for (int i = 0; i < 5; i++) {
DeferredSXSSFSheet sheet = wb.createSheet("sheet" + i);
int index = i;
sheet.setRowGenerator((sh) -> {
for (int j = 0; j < rowNum; j++) {
for (int j = 0; j < 1000; j++) {
Row row = sh.createRow(j);
Cell cell1 = row.createCell(0);
cell1.setCellValue(new CellReference(cell1).formatAsString());
@ -304,7 +297,8 @@ public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook {
}
}
void changeSheetNameWithSharedFormulas() {
/* not implemented */
@Override
@Disabled("not implemented")
protected void changeSheetNameWithSharedFormulas() {
}
}

View File

@ -55,6 +55,8 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
@ -98,28 +100,26 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
@Test
void existingWorkbook() throws IOException {
XSSFWorkbook xssfWb1 = new XSSFWorkbook();
try (XSSFWorkbook xssfWb1 = new XSSFWorkbook()) {
xssfWb1.createSheet("S1");
SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1);
XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1);
try (SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1);
XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1)) {
assertTrue(wb1.dispose());
SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2);
try (SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2)) {
assertEquals(1, wb2.getNumberOfSheets());
Sheet sheet = wb2.getSheetAt(0);
assertNotNull(sheet);
assertEquals("S1", sheet.getSheetName());
assertTrue(wb2.dispose());
xssfWb2.close();
xssfWb1.close();
wb2.close();
wb1.close();
}
}
}
}
@Test
void useSharedStringsTable() throws Exception {
SXSSFWorkbook wb = new SXSSFWorkbook(null, 10, false, true);
try (SXSSFWorkbook wb = new SXSSFWorkbook(null, 10, false, true)) {
SharedStringsTable sss = wb.getSharedStringSource();
@ -131,7 +131,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
row.createCell(1).setCellValue("B");
row.createCell(2).setCellValue("A");
XSSFWorkbook xssfWorkbook = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb);
try (XSSFWorkbook xssfWorkbook = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb)) {
sss = wb.getSharedStringSource();
assertEquals(2, sss.getUniqueCount());
assertTrue(wb.dispose());
@ -150,25 +150,23 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
cell = row.getCell(2);
assertNotNull(cell);
assertEquals("A", cell.getStringCellValue());
xssfWorkbook.close();
wb.close();
}
}
}
@Test
void addToExistingWorkbook() throws IOException {
XSSFWorkbook xssfWb1 = new XSSFWorkbook();
try (XSSFWorkbook xssfWb1 = new XSSFWorkbook()) {
xssfWb1.createSheet("S1");
Sheet sheet = xssfWb1.createSheet("S2");
Row row = sheet.createRow(1);
Cell cell = row.createCell(1);
cell.setCellValue("value 2_1_1");
SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1);
XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1);
try (SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1);
XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1)) {
assertTrue(wb1.dispose());
xssfWb1.close();
SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2);
try (SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2)) {
// Add a row to the existing empty sheet
Sheet sheet1 = wb2.getSheetAt(0);
Row row1_1 = sheet1.createRow(1);
@ -187,9 +185,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
Cell cell3_1_1 = row3_1.createCell(1);
cell3_1_1.setCellValue("value 3_1_1");
XSSFWorkbook xssfWb3 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb2);
wb2.close();
try (XSSFWorkbook xssfWb3 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb2)) {
assertEquals(3, xssfWb3.getNumberOfSheets());
// Verify sheet 1
sheet1 = xssfWb3.getSheetAt(0);
@ -223,15 +219,15 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
cell3_1_1 = row3_1.getCell(1);
assertNotNull(cell3_1_1);
assertEquals("value 3_1_1", cell3_1_1.getStringCellValue());
xssfWb2.close();
xssfWb3.close();
wb1.close();
}
}
}
}
}
@Test
void sheetdataWriter() throws IOException{
SXSSFWorkbook wb = new SXSSFWorkbook();
try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
SXSSFSheet sh = wb.createSheet();
SheetDataWriter wr = sh.getSheetDataWriter();
assertSame(wr.getClass(), SheetDataWriter.class);
@ -239,41 +235,40 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
assertStartsWith(tmp.getName(), "poi-sxssf-sheet");
assertEndsWith(tmp.getName(), ".xml");
assertTrue(wb.dispose());
wb.close();
}
wb = new SXSSFWorkbook();
try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
wb.setCompressTempFiles(true);
sh = wb.createSheet();
wr = sh.getSheetDataWriter();
SXSSFSheet sh = wb.createSheet();
SheetDataWriter wr = sh.getSheetDataWriter();
assertSame(wr.getClass(), GZIPSheetDataWriter.class);
tmp = wr.getTempFile();
File tmp = wr.getTempFile();
assertStartsWith(tmp.getName(), "poi-sxssf-sheet-xml");
assertEndsWith(tmp.getName(), ".gz");
assertTrue(wb.dispose());
wb.close();
}
//Test escaping of Unicode control characters
wb = new SXSSFWorkbook();
try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
wb.createSheet("S1").createRow(0).createCell(0).setCellValue("value\u0019");
XSSFWorkbook xssfWorkbook = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb);
try (XSSFWorkbook xssfWorkbook = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb)) {
Cell cell = xssfWorkbook.getSheet("S1").getRow(0).getCell(0);
assertEquals("value?", cell.getStringCellValue());
assertTrue(wb.dispose());
wb.close();
xssfWorkbook.close();
}
}
}
@Test
void gzipSheetdataWriter() throws IOException {
SXSSFWorkbook wb = new SXSSFWorkbook();
try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
wb.setCompressTempFiles(true);
final int rowNum = 1000;
final int sheetNum = 5;
populateData(wb, 1000, 5);
populateData(wb);
XSSFWorkbook xwb = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb);
try (XSSFWorkbook xwb = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb)) {
for (int i = 0; i < sheetNum; i++) {
Sheet sh = xwb.getSheetAt(i);
assertEquals("sheet" + i, sh.getSheetName());
@ -292,31 +287,14 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
}
assertTrue(wb.dispose());
xwb.close();
wb.close();
}
private static void assertWorkbookDispose(SXSSFWorkbook wb)
{
populateData(wb, 1000, 5);
for (Sheet sheet : wb) {
SXSSFSheet sxSheet = (SXSSFSheet) sheet;
assertTrue(sxSheet.getSheetDataWriter().getTempFile().exists());
}
assertTrue(wb.dispose());
for (Sheet sheet : wb) {
SXSSFSheet sxSheet = (SXSSFSheet) sheet;
assertFalse(sxSheet.getSheetDataWriter().getTempFile().exists());
}
}
private static void populateData(Workbook wb, final int rowNum, final int sheetNum) {
for(int i = 0; i < sheetNum; i++){
private static void populateData(Workbook wb) {
for(int i = 0; i < 5; i++){
Sheet sh = wb.createSheet("sheet" + i);
for(int j = 0; j < rowNum; j++){
for(int j = 0; j < 1000; j++){
Row row = sh.createRow(j);
Cell cell1 = row.createCell(0);
cell1.setCellValue(new CellReference(cell1).formatAsString());
@ -330,28 +308,40 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
}
}
@Test
void workbookDispose() throws IOException {
SXSSFWorkbook wb1 = new SXSSFWorkbook();
// the underlying writer is SheetDataWriter
assertWorkbookDispose(wb1);
wb1.close();
@ParameterizedTest
@ValueSource(booleans = {false, true})
void workbookDispose(boolean compressTempFiles) throws IOException {
try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
// compressTempFiles == false: the underlying writer is SheetDataWriter
// compressTempFiles == true: the underlying writer is GZIPSheetDataWriter
wb.setCompressTempFiles(compressTempFiles);
SXSSFWorkbook wb2 = new SXSSFWorkbook();
wb2.setCompressTempFiles(true);
// the underlying writer is GZIPSheetDataWriter
assertWorkbookDispose(wb2);
wb2.close();
populateData(wb);
for (Sheet sheet : wb) {
SXSSFSheet sxSheet = (SXSSFSheet) sheet;
assertTrue(sxSheet.getSheetDataWriter().getTempFile().exists());
}
assertTrue(wb.dispose());
for (Sheet sheet : wb) {
SXSSFSheet sxSheet = (SXSSFSheet) sheet;
assertFalse(sxSheet.getSheetDataWriter().getTempFile().exists());
}
}
}
@Test
void bug53515() throws Exception {
try (Workbook wb1 = new SXSSFWorkbook(10)) {
populateWorkbook(wb1);
saveTwice(wb1);
assertDoesNotThrow(() -> wb1.write(NULL_OUTPUT_STREAM));
assertDoesNotThrow(() -> wb1.write(NULL_OUTPUT_STREAM));
try (Workbook wb2 = new XSSFWorkbook()) {
populateWorkbook(wb2);
saveTwice(wb2);
assertDoesNotThrow(() -> wb2.write(NULL_OUTPUT_STREAM));
assertDoesNotThrow(() -> wb2.write(NULL_OUTPUT_STREAM));
}
}
}
@ -405,18 +395,6 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
}
}
private static void saveTwice(Workbook wb) throws Exception {
for (int i = 0; i < 2; i++) {
try {
wb.write(NULL_OUTPUT_STREAM);
} catch (Exception e) {
throw new Exception("ERROR: failed on " + (i + 1)
+ "th time calling " + wb.getClass().getName()
+ ".write() with exception " + e.getMessage(), e);
}
}
}
@Test
void closeDoesNotModifyWorkbook() throws IOException {
final String filename = "SampleSS.xlsx";
@ -460,10 +438,10 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
char[] useless = new char[32767];
Arrays.fill(useless, ' ');
for (int row = 0; row < 1; row++) {
for (int row = 0; row < 10; row++) {
Row r = s.createRow(row);
for (int col = 0; col < 10; col++) {
char[] prefix = Integer.toHexString(row * 1000 + col).toCharArray();
char[] prefix = Integer.toHexString(row * 10 + col).toCharArray();
Arrays.fill(useless, 0, 10, ' ');
System.arraycopy(prefix, 0, useless, 0, prefix.length);
String ul = new String(useless);
@ -528,8 +506,8 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
}
}
@Override
@Disabled("not implemented")
@Test
void changeSheetNameWithSharedFormulas() {
protected void changeSheetNameWithSharedFormulas() {
}
}

View File

@ -100,7 +100,6 @@ import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.util.LocaleUtil;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.poi.util.TempFile;
import org.apache.poi.util.XMLHelper;
import org.apache.poi.xssf.SXSSFITestDataProvider;
@ -117,7 +116,14 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedNames;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMergeCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMergeCells;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTFontImpl;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
@ -2714,6 +2720,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
CellStyle style = wb.createCellStyle();
style.setRotation((short) -90);
cell.setCellStyle(style);
assertEquals(180, style.getRotation());
XSSFTestDataSamples.writeOut(wb, fileName);
}

View File

@ -259,11 +259,11 @@ public final class TestXSSFFont extends BaseTestFont{
xssfFont.setUnderline(Font.U_DOUBLE);
assertEquals(ctFont.sizeOfUArray(),1);
assertEquals(STUnderlineValues.DOUBLE,ctFont.getUArray(0).getVal());
assertSame(STUnderlineValues.DOUBLE,ctFont.getUArray(0).getVal());
xssfFont.setUnderline(FontUnderline.DOUBLE_ACCOUNTING);
assertEquals(ctFont.sizeOfUArray(),1);
assertEquals(STUnderlineValues.DOUBLE_ACCOUNTING,ctFont.getUArray(0).getVal());
assertSame(STUnderlineValues.DOUBLE_ACCOUNTING,ctFont.getUArray(0).getVal());
}
@Test
@ -342,7 +342,7 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(FontScheme.MAJOR,font.getScheme());
font.setScheme(FontScheme.NONE);
assertEquals(STFontScheme.NONE,ctFont.getSchemeArray(0).getVal());
assertSame(STFontScheme.NONE,ctFont.getSchemeArray(0).getVal());
}
@Test
@ -356,17 +356,15 @@ public final class TestXSSFFont extends BaseTestFont{
assertEquals(Font.SS_NONE,font.getTypeOffset());
font.setTypeOffset(XSSFFont.SS_SUPER);
assertEquals(STVerticalAlignRun.SUPERSCRIPT,ctFont.getVertAlignArray(0).getVal());
assertSame(STVerticalAlignRun.SUPERSCRIPT,ctFont.getVertAlignArray(0).getVal());
}
// store test from TestSheetUtil here as it uses XSSF
@Test
void testCanComputeWidthXSSF() throws IOException {
try (Workbook wb = new XSSFWorkbook()) {
// cannot check on result because on some machines we get back false here!
SheetUtil.canComputeColumnWidth(wb.getFontAt(0));
assertDoesNotThrow(() -> SheetUtil.canComputeColumnWidth(wb.getFontAt(0)));
}
}
@ -377,7 +375,7 @@ public final class TestXSSFFont extends BaseTestFont{
font.setFontName("some non existing font name");
// Even with invalid fonts we still get back useful data most of the time...
SheetUtil.canComputeColumnWidth(font);
assertDoesNotThrow(() -> SheetUtil.canComputeColumnWidth(font));
}
/**

View File

@ -252,14 +252,14 @@ public final class TestXSSFSheet extends BaseTestXSheet {
sheet.createFreezePane(2, 4);
assertEquals(2.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getXSplit(), 0.0);
assertEquals(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane());
assertSame(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane());
sheet.createFreezePane(3, 6, 10, 10);
assertEquals(3.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getXSplit(), 0.0);
// assertEquals(10, sheet.getTopRow());
// assertEquals(10, sheet.getLeftCol());
sheet.createSplitPane(4, 8, 12, 12, 1);
assertEquals(8.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getYSplit(), 0.0);
assertEquals(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane());
assertSame(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane());
workbook.close();
}
@ -1152,7 +1152,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
CTCalcPr calcPr = wb1.getCTWorkbook().addNewCalcPr();
calcPr.setCalcMode(STCalcMode.MANUAL);
sheet.setForceFormulaRecalculation(true);
assertEquals(STCalcMode.AUTO, calcPr.getCalcMode());
assertSame(STCalcMode.AUTO, calcPr.getCalcMode());
// Check
sheet.setForceFormulaRecalculation(false);
@ -1422,9 +1422,10 @@ public final class TestXSSFSheet extends BaseTestXSheet {
wb.close();
}
private void testCopyOneRow(String copyRowsTestWorkbook) throws IOException {
@Test
void testCopyOneRow() throws IOException {
final double FLOAT_PRECISION = 1e-9;
final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook);
try (final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("XSSFSheet.copyRows.xlsx")) {
final XSSFSheet sheet = wb.getSheetAt(0);
final CellCopyPolicy defaultCopyPolicy = new CellCopyPolicy();
sheet.copyRows(1, 1, 6, defaultCopyPolicy);
@ -1504,13 +1505,12 @@ public final class TestXSSFSheet extends BaseTestXSheet {
assertEquals("SUM(H7:I8)", cell.getCellFormula(), "[Cell Formula with Area Reference] M7 cell formula");
// Array Formula
cell = CellUtil.getCell(destRow, col++);
//System.out.println("Array formulas currently unsupported");
col++;
// cell = CellUtil.getCell(destRow, col++);
// Array formulas currently unsupported"
// FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula()
/*
assertEquals(CellType.FORMULA, cell.getCellType(), "[Array Formula] N7 cell type");
assertEquals("{SUM(H7:J7*{1,2,3})}", cell.getCellFormula(), "[Array Formula] N7 cell formula");
*/
// assertEquals(CellType.FORMULA, cell.getCellType(), "[Array Formula] N7 cell type");
// assertEquals("{SUM(H7:J7*{1,2,3})}", cell.getCellFormula(), "[Array Formula] N7 cell formula");
// Data Format
cell = CellUtil.getCell(destRow, col++);
@ -1547,13 +1547,13 @@ public final class TestXSSFSheet extends BaseTestXSheet {
// Make sure other rows are blank (off-by-one errors)
assertNull(sheet.getRow(5));
assertNull(sheet.getRow(7));
wb.close();
}
}
private void testCopyMultipleRows(String copyRowsTestWorkbook) throws IOException {
@Test
void testCopyMultipleRows() throws IOException {
final double FLOAT_PRECISION = 1e-9;
final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook);
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("XSSFSheet.copyRows.xlsx")) {
final XSSFSheet sheet = wb.getSheetAt(0);
final CellCopyPolicy defaultCopyPolicy = new CellCopyPolicy();
sheet.copyRows(0, 3, 8, defaultCopyPolicy);
@ -1704,18 +1704,16 @@ public final class TestXSSFSheet extends BaseTestXSheet {
// Array Formula
col++;
cell = CellUtil.getCell(destRow1, col);
// System.out.println("Array formulas currently unsupported");
/*
// cell = CellUtil.getCell(destRow1, col);
// Array formulas currently unsupported
// FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula()
assertEquals(CellType.FORMULA, cell.getCellType(), "[Array Formula] N10 cell type");
assertEquals("{SUM(H10:J10*{1,2,3})}", cell.getCellFormula(), "[Array Formula] N10 cell formula");
// assertEquals(CellType.FORMULA, cell.getCellType(), "[Array Formula] N10 cell type");
// assertEquals("{SUM(H10:J10*{1,2,3})}", cell.getCellFormula(), "[Array Formula] N10 cell formula");
cell = CellUtil.getCell(destRow2, col);
// cell = CellUtil.getCell(destRow2, col);
// FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula()
assertEquals(CellType.FORMULA, cell.getCellType(). "[Array Formula] N11 cell type");
assertEquals("{SUM(H11:J11*{1,2,3})}", cell.getCellFormula(). "[Array Formula] N11 cell formula");
*/
// assertEquals(CellType.FORMULA, cell.getCellType(). "[Array Formula] N11 cell type");
// assertEquals("{SUM(H11:J11*{1,2,3})}", cell.getCellFormula(). "[Array Formula] N11 cell formula");
// Data Format
col++;
@ -1754,18 +1752,7 @@ public final class TestXSSFSheet extends BaseTestXSheet {
// Make sure other rows are blank (off-by-one errors)
assertNull(sheet.getRow(7), "Off-by-one lower edge case"); //one row above destHeaderRow
assertNull(sheet.getRow(12), "Off-by-one upper edge case"); //one row below destRow3
wb.close();
}
@Test
void testCopyOneRow() throws IOException {
testCopyOneRow("XSSFSheet.copyRows.xlsx");
}
@Test
void testCopyMultipleRows() throws IOException {
testCopyMultipleRows("XSSFSheet.copyRows.xlsx");
}
@Test
@ -1998,26 +1985,34 @@ public final class TestXSSFSheet extends BaseTestXSheet {
@Test
public void bug65120() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
CreationHelper creationHelper = wb.getCreationHelper();
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFCreationHelper creationHelper = wb.getCreationHelper();
Sheet sheet1 = wb.createSheet();
XSSFSheet sheet1 = wb.createSheet();
Cell cell1 = sheet1.createRow(0).createCell(0);
Comment comment1 = sheet1.createDrawingPatriarch().createCellComment(creationHelper.createClientAnchor());
XSSFDrawing dwg1 = sheet1.createDrawingPatriarch();
XSSFComment comment1 = dwg1.createCellComment(creationHelper.createClientAnchor());
cell1.setCellComment(comment1);
XSSFVMLDrawing vml0 = sheet1.getVMLDrawing(false);
assertEquals("/xl/drawings/vmlDrawing0.vml", vml0.getPackagePart().getPartName().getName());
Sheet sheet2 = wb.createSheet();
XSSFSheet sheet2 = wb.createSheet();
Cell cell2 = sheet2.createRow(0).createCell(0);
Comment comment2 = sheet2.createDrawingPatriarch().createCellComment(creationHelper.createClientAnchor());
XSSFDrawing dwg2 = sheet2.createDrawingPatriarch();
Comment comment2 = dwg2.createCellComment(creationHelper.createClientAnchor());
cell2.setCellComment(comment2);
XSSFVMLDrawing vml1 = sheet2.getVMLDrawing(false);
assertEquals("/xl/drawings/vmlDrawing1.vml", vml1.getPackagePart().getPartName().getName());
wb.removeSheetAt(0);
Sheet sheet3 = wb.createSheet();
XSSFSheet sheet3 = wb.createSheet();
Cell cell3 = sheet3.createRow(0).createCell(0);
Comment comment3 = sheet3.createDrawingPatriarch().createCellComment(creationHelper.createClientAnchor());
XSSFDrawing dwg3 = sheet3.createDrawingPatriarch();
Comment comment3 = dwg3.createCellComment(creationHelper.createClientAnchor());
cell3.setCellComment(comment3);
wb.close();
XSSFVMLDrawing vml2 = sheet3.getVMLDrawing(false);
assertEquals("/xl/drawings/vmlDrawing2.vml", vml2.getPackagePart().getPartName().getName());
}
}
}

View File

@ -399,18 +399,17 @@ public class HemfPlusBrush {
}
public byte[] getRawData(List<? extends EmfPlusObjectData> continuedObjectData) {
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try {
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
bos.write(getBrushBytes());
if (continuedObjectData != null) {
for (EmfPlusObjectData od : continuedObjectData) {
bos.write(((EmfPlusBrush)od).getBrushBytes());
}
}
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
return bos.toByteArray();
}

View File

@ -445,18 +445,17 @@ public class HemfPlusImage {
}
public byte[] getRawData(List<? extends EmfPlusObjectData> continuedObjectData) {
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try {
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
bos.write(getImageData());
if (continuedObjectData != null) {
for (EmfPlusObjectData od : continuedObjectData) {
bos.write(((EmfPlusImage)od).getImageData());
}
}
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
return bos.toByteArray();
}
@Override

View File

@ -35,6 +35,7 @@ import org.apache.poi.hemf.record.emf.HemfComment.EmfCommentDataMultiformats;
import org.apache.poi.hemf.record.emf.HemfComment.EmfCommentDataPlus;
import org.apache.poi.hemf.record.emf.HemfComment.EmfCommentDataWMF;
import org.apache.poi.hemf.record.emf.HemfRecord;
import org.apache.poi.hemf.record.emfplus.HemfPlusImage;
import org.apache.poi.hemf.record.emfplus.HemfPlusImage.EmfPlusBitmapDataType;
import org.apache.poi.hemf.record.emfplus.HemfPlusImage.EmfPlusImage;
import org.apache.poi.hemf.record.emfplus.HemfPlusObject.EmfPlusObject;
@ -63,6 +64,10 @@ public class HemfEmbeddedIterator implements Iterator<HwmfEmbedded> {
@Override
public boolean hasNext() {
return moveNext();
}
private boolean moveNext() {
if (iterStack.isEmpty()) {
return false;
}
@ -290,36 +295,33 @@ public class HemfEmbeddedIterator implements Iterator<HwmfEmbedded> {
final int objectId = epo.getObjectId();
HwmfEmbedded emb = new HwmfEmbedded();
final HwmfEmbedded emb = new HwmfEmbedded();
EmfPlusImage img = epo.getObjectData();
assert(img.getImageDataType() != null);
int totalSize = epo.getTotalObjectSize();
// totalSize is only set, if there are multiple chunks
final int totalSize = epo.getTotalObjectSize() == 0
? ((EmfPlusImage)epo.getObjectData()).getImageData().length
: epo.getTotalObjectSize();
IOUtils.safelyAllocateCheck(totalSize, MAX_RECORD_LENGTH);
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(epo.getTotalObjectSize());
try {
for (;;) {
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(totalSize)) {
boolean hasNext = false;
do {
EmfPlusImage img = epo.getObjectData();
assert(img.getImageDataType() != null);
assert(!hasNext || img.getImageDataType() == HemfPlusImage.EmfPlusImageDataType.CONTINUED);
bos.write(img.getImageData());
current = null;
//noinspection ConstantConditions
if (hasNext() &&
hasNext = moveNext() &&
(current instanceof EmfPlusObject) &&
((epo = (EmfPlusObject) current).getObjectId() == objectId) &&
bos.size() < totalSize-16
) {
img = epo.getObjectData();
} else {
bos.size() < totalSize-16;
} while (hasNext);
emb.setData(bos.toByteArray());
return emb;
}
}
} catch (IOException ignored) {
// UnsynchronizedByteArrayOutputStream doesn't throw IOException
return null;
} finally {
emb.setData(bos.toByteArray());
}
}
}

View File

@ -70,9 +70,8 @@ public final class PICT extends Metafile {
@Override
public byte[] getData(){
byte[] rawdata = getRawData();
try {
try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) {
byte[] macheader = new byte[512];
UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
out.write(macheader);
int pos = CHECKSUM_SIZE*getUIDInstanceCount();
byte[] pict = read(rawdata, pos);
@ -93,7 +92,7 @@ public final class PICT extends Metafile {
throw new EOFException();
}
byte[] chunk = new byte[4096];
UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(header.getWmfSize());
try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(header.getWmfSize())) {
try (InflaterInputStream inflater = new InflaterInputStream(bis)) {
int count;
while ((count = inflater.read(chunk)) >= 0) {
@ -103,8 +102,10 @@ public final class PICT extends Metafile {
bytefill(chunk, (byte) 0);
}
} catch (Exception e) {
int lastLen;
for (lastLen = chunk.length - 1; lastLen >= 0 && chunk[lastLen] == 0; lastLen--) ;
int lastLen = chunk.length - 1;
while (lastLen >= 0 && chunk[lastLen] == 0) {
lastLen--;
}
if (++lastLen > 0) {
if (header.getWmfSize() > out.size()) {
// sometimes the wmfsize is smaller than the amount of already successfully read bytes
@ -118,6 +119,7 @@ public final class PICT extends Metafile {
}
return out.toByteArray();
}
}
@Override
protected byte[] formatImageForSlideshow(byte[] data) {

View File

@ -89,12 +89,13 @@ public final class EscherTextboxWrapper extends RecordContainer {
// Write out our children, and stuff them into the Escher layer
// Grab the children's data
UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
for (org.apache.poi.hslf.record.Record r : _children) r.writeOut(baos);
byte[] data = baos.toByteArray();
try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
for (org.apache.poi.hslf.record.Record r : _children) {
r.writeOut(baos);
}
// Save in the escher layer
_escherRecord.setData(data);
_escherRecord.setData(baos.toByteArray());
}
}
/**

View File

@ -27,8 +27,8 @@ import java.util.function.Supplier;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.commons.io.input.BoundedInputStream;
import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.util.GenericRecordUtil;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndian;
@ -124,19 +124,20 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR
* @param data the embedded data.
*/
public void setData(byte[] data) throws IOException {
UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
DeflaterOutputStream def = new DeflaterOutputStream(out)) {
//first four bytes is the length of the raw data
byte[] b = new byte[4];
LittleEndian.putInt(b, 0, data.length);
out.write(b);
DeflaterOutputStream def = new DeflaterOutputStream(out);
def.write(data, 0, data.length);
def.finish();
// TODO: CHECK if it's correct that DeflaterOutputStream is only finished and not closed?
_data = out.toByteArray();
LittleEndian.putInt(_header, 4, _data.length);
}
}
/**
* Gets the record type.

View File

@ -49,7 +49,7 @@ public final class PPDrawingGroup extends RecordAtom {
//cached dgg
private EscherDggRecord dgg;
protected PPDrawingGroup(byte[] source, int start, int len) {
PPDrawingGroup(byte[] source, int start, int len) {
// Get the header
_header = Arrays.copyOfRange(source, start, start+8);
@ -80,24 +80,23 @@ public final class PPDrawingGroup extends RecordAtom {
@Override
public void writeOut(OutputStream out) throws IOException {
UnsynchronizedByteArrayOutputStream bout = new UnsynchronizedByteArrayOutputStream();
byte[] bstorehead = new byte[8];
byte[] recordBytes = new byte[36 + 8];
try (UnsynchronizedByteArrayOutputStream bout = new UnsynchronizedByteArrayOutputStream();
UnsynchronizedByteArrayOutputStream recordBuf = new UnsynchronizedByteArrayOutputStream()) {
for (EscherRecord r : dggContainer) {
if (r.getRecordId() == EscherContainerRecord.BSTORE_CONTAINER) {
EscherContainerRecord bstore = (EscherContainerRecord) r;
UnsynchronizedByteArrayOutputStream b2 = new UnsynchronizedByteArrayOutputStream();
recordBuf.reset();
for (EscherRecord br : bstore) {
byte[] b = new byte[36+8];
br.serialize(0, b);
b2.write(b);
br.serialize(0, recordBytes);
recordBuf.write(recordBytes);
}
byte[] bstorehead = new byte[8];
LittleEndian.putShort(bstorehead, 0, bstore.getOptions());
LittleEndian.putShort(bstorehead, 2, bstore.getRecordId());
LittleEndian.putInt(bstorehead, 4, b2.size());
LittleEndian.putInt(bstorehead, 4, recordBuf.size());
bout.write(bstorehead);
bout.write(b2.toByteArray());
recordBuf.writeTo(bout);
} else {
bout.write(r.serialize());
}
@ -119,6 +118,7 @@ public final class PPDrawingGroup extends RecordAtom {
// Finally, write out the children
bout.writeTo(out);
}
}
public EscherContainerRecord getDggContainer(){
return dggContainer;

View File

@ -227,7 +227,7 @@ public abstract class RecordContainer extends Record
*/
public void writeOut(byte headerA, byte headerB, long type, Record[] children, OutputStream out) throws IOException {
// Create a UnsynchronizedByteArrayOutputStream to hold everything in
UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
// Write out our header, less the size
baos.write(new byte[]{headerA, headerB});
@ -245,13 +245,13 @@ public abstract class RecordContainer extends Record
byte[] toWrite = baos.toByteArray();
// Update our header with the size
// Don't forget to knock 8 more off, since we don't include the
// header in the size
// Don't forget to knock 8 more off, since we don't include the header in the size
LittleEndian.putInt(toWrite, 4, (toWrite.length - 8));
// Write out the bytes
out.write(toWrite);
}
}
/**
* Find the records that are parent-aware, and tell them who their parent is

View File

@ -309,11 +309,8 @@ public final class StyleTextPropAtom extends RecordAtom {
*/
private void updateRawContents() throws IOException {
if (initialised) {
// Only update the style bytes, if the styles have been potentially
// changed
UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
// Only update the style bytes, if the styles have been potentially changed
try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
// First up, we need to serialise the paragraph properties
for (TextPropCollection tpc : paragraphStyles) {
tpc.writeOut(baos);
@ -326,6 +323,7 @@ public final class StyleTextPropAtom extends RecordAtom {
rawContents = baos.toByteArray();
}
}
// Now ensure that the header size is correct
int newSize = rawContents.length + reserved.length;

View File

@ -130,26 +130,28 @@ public final class TextSpecInfoAtom extends RecordAtom {
*/
public void setParentSize(int size) {
assert(size > 0);
int covered = 0;
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
TextSpecInfoRun[] runs = getTextSpecInfoRuns();
assert(runs.length > 0);
for (int i=0; i<runs.length && covered < size; i++) {
TextSpecInfoRun run = runs[i];
if (covered + run.getLength() > size || i == runs.length-1) {
run.setLength(size-covered);
int remaining = size;
int idx = 0;
for (TextSpecInfoRun run : runs) {
int len = run.getLength();
if (len > remaining || idx == runs.length - 1) {
run.setLength(len = remaining);
}
covered += run.getLength();
try {
remaining -= len;
run.writeOut(bos);
} catch (IOException e) {
throw new HSLFException(e);
}
idx++;
}
_data = bos.toByteArray();
// Update the size (header bytes 5-8)
LittleEndian.putInt(_header, 4, _data.length);
} catch (IOException e) {
throw new HSLFException(e);
}
}
/**

View File

@ -110,33 +110,29 @@ public class HwmfEmbeddedIterator implements Iterator<HwmfEmbedded> {
if (!(current instanceof HwmfEscape)) {
return null;
}
final HwmfEscape esc = (HwmfEscape)current;
assert(esc.getEscapeFunction() == EscapeFunction.META_ESCAPE_ENHANCED_METAFILE);
WmfEscapeEMF img = esc.getEscapeData();
assert(img.isValid());
current = null;
final HwmfEmbedded emb = new HwmfEmbedded();
emb.setEmbeddedType(HwmfEmbeddedType.EMF);
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try {
for (;;) {
bos.write(img.getEmfData());
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
WmfEscapeEMF img;
do {
final HwmfEscape esc = (HwmfEscape)current;
assert(esc.getEscapeFunction() == EscapeFunction.META_ESCAPE_ENHANCED_METAFILE);
img = esc.getEscapeData();
assert(img.isValid());
bos.write(img.getEmfData());
current = null;
if (img.getRemainingBytes() > 0 && hasNext() && (current instanceof HwmfEscape)) {
img = ((HwmfEscape)current).getEscapeData();
} else {
} while (img.getRemainingBytes() > 0 && hasNext() && (current instanceof HwmfEscape));
emb.setData(bos.toByteArray());
return emb;
}
}
} catch (IOException ignored) {
// UnsynchronizedByteArrayOutputStream doesn't throw IOException
return null;
} finally {
emb.setData(bos.toByteArray());
}
}
}

View File

@ -104,6 +104,8 @@ task cacheTest9(type: Copy) {
}
jar {
dependsOn cacheJava9
if (JavaVersion.current() == JavaVersion.VERSION_1_8) {
into('META-INF/versions/9') {
from JAVA9_SRC include '*.class'
@ -117,7 +119,7 @@ jar {
// Create a separate jar for test-code to depend on it in other projects
// See http://stackoverflow.com/questions/5144325/gradle-test-dependency
task testJar(type: Jar, dependsOn: testClasses) {
task testJar(type: Jar, dependsOn: [ testClasses, cacheTest9 ]) {
destinationDirectory = file("../build/dist/maven/${project.archivesBaseName}-tests")
classifier 'tests'

View File

@ -49,7 +49,7 @@ public class ClassID implements Duplicatable, GenericRecord {
private final byte[] bytes = new byte[LENGTH];
/**
* Creates a {@link ClassID} and reads its value from a byte array.
* Creates a ClassID and reads its value from a byte array.
*
* @param src The byte array to read from.
* @param offset The offset of the first byte to read.
@ -60,7 +60,7 @@ public class ClassID implements Duplicatable, GenericRecord {
/**
* Creates a {@link ClassID} and initializes its value with 0x00 bytes.
* Creates a ClassID and initializes its value with 0x00 bytes.
*/
public ClassID() {
Arrays.fill(bytes, (byte)0);
@ -77,7 +77,7 @@ public class ClassID implements Duplicatable, GenericRecord {
/**
* Creates a {@link ClassID} from a human-readable representation of the Class ID in standard
* Creates a ClassID from a human-readable representation of the Class ID in standard
* format {@code "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"}.
*
* @param externalForm representation of the Class ID represented by this object.
@ -102,12 +102,11 @@ public class ClassID implements Duplicatable, GenericRecord {
/**
* @return The number of bytes occupied by this object in the byte stream.
*/
@SuppressWarnings("java:S1845")
public int length() {
return LENGTH;
}
/**
* Gets the bytes making out the class ID. They are returned in correct order, i.e. big-endian.
*
@ -117,8 +116,6 @@ public class ClassID implements Duplicatable, GenericRecord {
return bytes;
}
/**
* Sets the bytes making out the class ID.
*
@ -129,8 +126,6 @@ public class ClassID implements Duplicatable, GenericRecord {
System.arraycopy(bytes, 0, this.bytes, 0, LENGTH);
}
/**
* Reads the class ID's value from a byte array by turning little-endian into big-endian.
*
@ -249,10 +244,6 @@ public class ClassID implements Duplicatable, GenericRecord {
;
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
return toString().hashCode();

View File

@ -514,8 +514,8 @@ public class PropertySet {
}
private byte[] toBytes() throws WritingNotSupportedException, IOException {
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
LittleEndianOutputStream leos = new LittleEndianOutputStream(bos);
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
LittleEndianOutputStream leos = new LittleEndianOutputStream(bos)) {
/* Write the number of sections in this property set stream. */
final int nrSections = getSectionCount();
@ -560,6 +560,7 @@ public class PropertySet {
return result;
}
}
/**
* Writes a property set to a document in a POI filesystem directory.

View File

@ -735,8 +735,8 @@ public class Section {
}
final int[][] offsets = new int[properties.size()][2];
final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
final LittleEndianOutputStream leos = new LittleEndianOutputStream(bos);
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
LittleEndianOutputStream leos = new LittleEndianOutputStream(bos)) {
/* Write the section's length - dummy value, fixed later */
leos.writeInt(-1);
@ -783,6 +783,7 @@ public class Section {
return bos.size();
}
}
/**
* Reads a dictionary.

View File

@ -459,7 +459,7 @@ public final class RecordInputStream implements LittleEndianInput {
*/
@Deprecated
public byte[] readAllContinuedRemainder() {
UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(2 * MAX_RECORD_DATA_SIZE);
try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(2 * MAX_RECORD_DATA_SIZE)) {
while (true) {
byte[] b = readRemainder();
@ -470,6 +470,9 @@ public final class RecordInputStream implements LittleEndianInput {
nextRecord();
}
return out.toByteArray();
} catch (IOException ex) {
throw new RecordFormatException(ex);
}
}
/** The remaining number of bytes in the <i>current</i> record.

View File

@ -64,8 +64,8 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
* Only newer style formatting rules have priorities. For older ones,
* we don't know priority for these, other than definition/model order,
* which appears to be what Excel uses.
* @see org.apache.poi.ss.usermodel.ConditionalFormattingRule#getPriority()
*/
@Override
public int getPriority() {
CFRule12Record rule12 = getCFRule12Record(false);
if (rule12 == null) return 0;
@ -74,8 +74,8 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
/**
* Always true for HSSF files, per Microsoft Excel documentation
* @see org.apache.poi.ss.usermodel.ConditionalFormattingRule#getStopIfTrue()
*/
@Override
public boolean getStopIfTrue() {
return true;
}
@ -95,8 +95,8 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
/**
* Always null for HSSF records, until someone figures out where to find it
* @see org.apache.poi.ss.usermodel.ConditionalFormattingRule#getNumberFormat()
*/
@Override
public ExcelNumberFormat getNumberFormat() {
return null;
}
@ -112,16 +112,18 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
}
/**
* @return - font formatting object if defined, <code>null</code> otherwise
* @return - font formatting object if defined, {@code null} otherwise
*/
@Override
public HSSFFontFormatting getFontFormatting() {
return getFontFormatting(false);
}
/**
* create a new font formatting structure if it does not exist,
* otherwise just return existing object.
* @return - font formatting object, never returns <code>null</code>.
* @return - font formatting object, never returns {@code null}.
*/
@Override
public HSSFFontFormatting createFontFormatting() {
return getFontFormatting(true);
}
@ -137,16 +139,18 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
}
/**
* @return - border formatting object if defined, <code>null</code> otherwise
* @return - border formatting object if defined, {@code null} otherwise
*/
@Override
public HSSFBorderFormatting getBorderFormatting() {
return getBorderFormatting(false);
}
/**
* create a new border formatting structure if it does not exist,
* otherwise just return existing object.
* @return - border formatting object, never returns <code>null</code>.
* @return - border formatting object, never returns {@code null}.
*/
@Override
public HSSFBorderFormatting createBorderFormatting() {
return getBorderFormatting(true);
}
@ -162,8 +166,9 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
}
/**
* @return - pattern formatting object if defined, <code>null</code> otherwise
* @return - pattern formatting object if defined, {@code null} otherwise
*/
@Override
public HSSFPatternFormatting getPatternFormatting()
{
return getPatternFormatting(false);
@ -171,8 +176,9 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
/**
* create a new pattern formatting structure if it does not exist,
* otherwise just return existing object.
* @return - pattern formatting object, never returns <code>null</code>.
* @return - pattern formatting object, never returns {@code null}.
*/
@Override
public HSSFPatternFormatting createPatternFormatting()
{
return getPatternFormatting(true);
@ -192,8 +198,9 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
}
/**
* @return databar / data-bar formatting object if defined, <code>null</code> otherwise
* @return databar / data-bar formatting object if defined, {@code null} otherwise
*/
@Override
public HSSFDataBarFormatting getDataBarFormatting() {
return getDataBarFormatting(false);
}
@ -218,8 +225,9 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
}
/**
* @return icon / multi-state formatting object if defined, <code>null</code> otherwise
* @return icon / multi-state formatting object if defined, {@code null} otherwise
*/
@Override
public HSSFIconMultiStateFormatting getMultiStateFormatting() {
return getMultiStateFormatting(false);
}
@ -245,8 +253,9 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
}
/**
* @return color scale / gradient formatting object if defined, <code>null</code> otherwise
* @return color scale / gradient formatting object if defined, {@code null} otherwise
*/
@Override
public HSSFColorScaleFormatting getColorScaleFormatting() {
return getColorScaleFormatting(false);
}
@ -270,12 +279,13 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
/**
* always null (not a filter condition) or {@link ConditionFilterType#FILTER} if it is.
* @see org.apache.poi.ss.usermodel.ConditionalFormattingRule#getConditionFilterType()
*/
@Override
public ConditionFilterType getConditionFilterType() {
return getConditionType() == ConditionType.FILTER ? ConditionFilterType.FILTER : null;
}
@Override
public ConditionFilterData getFilterConfiguration() {
return null;
}
@ -288,11 +298,13 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
return cfRuleRecord.getComparisonOperation();
}
@Override
public String getFormula1()
{
return toFormulaString(cfRuleRecord.getParsedExpression1());
}
@Override
public String getFormula2() {
byte conditionType = cfRuleRecord.getConditionType();
if (conditionType == CELL_COMPARISON) {
@ -306,6 +318,7 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
return null;
}
@Override
public String getText() {
return null; // not available here, unless it exists and is unimplemented in cfRuleRecord
}
@ -325,6 +338,7 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin
* Conditional format rules don't define stripes, so always 0
* @see org.apache.poi.ss.usermodel.DifferentialStyleProvider#getStripeSize()
*/
@Override
public int getStripeSize() {
return 0;
}

View File

@ -31,32 +31,40 @@ public final class HSSFConditionalFormattingThreshold implements org.apache.poi.
private final HSSFSheet sheet;
private final HSSFWorkbook workbook;
protected HSSFConditionalFormattingThreshold(Threshold threshold, HSSFSheet sheet) {
HSSFConditionalFormattingThreshold(Threshold threshold, HSSFSheet sheet) {
this.threshold = threshold;
this.sheet = sheet;
this.workbook = sheet.getWorkbook();
}
protected Threshold getThreshold() {
Threshold getThreshold() {
return threshold;
}
@Override
public RangeType getRangeType() {
return RangeType.byId(threshold.getType());
}
@Override
public void setRangeType(RangeType type) {
threshold.setType((byte)type.id);
}
@Override
public String getFormula() {
return toFormulaString(threshold.getParsedExpression(), workbook);
}
@Override
public void setFormula(String formula) {
threshold.setParsedExpression(parseFormula(formula, sheet));
}
@Override
public Double getValue() {
return threshold.getValue();
}
@Override
public void setValue(Double value) {
threshold.setValue(value);
}

View File

@ -29,36 +29,41 @@ import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold;
*/
public final class HSSFIconMultiStateFormatting implements org.apache.poi.ss.usermodel.IconMultiStateFormatting {
private final HSSFSheet sheet;
private final CFRule12Record cfRule12Record;
private final IconMultiStateFormatting iconFormatting;
protected HSSFIconMultiStateFormatting(CFRule12Record cfRule12Record, HSSFSheet sheet) {
HSSFIconMultiStateFormatting(CFRule12Record cfRule12Record, HSSFSheet sheet) {
this.sheet = sheet;
this.cfRule12Record = cfRule12Record;
this.iconFormatting = this.cfRule12Record.getMultiStateFormatting();
this.iconFormatting = cfRule12Record.getMultiStateFormatting();
}
@Override
public IconSet getIconSet() {
return iconFormatting.getIconSet();
}
@Override
public void setIconSet(IconSet set) {
iconFormatting.setIconSet(set);
}
@Override
public boolean isIconOnly() {
return iconFormatting.isIconOnly();
}
@Override
public void setIconOnly(boolean only) {
iconFormatting.setIconOnly(only);
}
@Override
public boolean isReversed() {
return iconFormatting.isReversed();
}
@Override
public void setReversed(boolean reversed) {
iconFormatting.setReversed(reversed);
}
@Override
public HSSFConditionalFormattingThreshold[] getThresholds() {
Threshold[] t = iconFormatting.getThresholds();
HSSFConditionalFormattingThreshold[] ht = new HSSFConditionalFormattingThreshold[t.length];
@ -68,6 +73,7 @@ public final class HSSFIconMultiStateFormatting implements org.apache.poi.ss.use
return ht;
}
@Override
public void setThresholds(ConditionalFormattingThreshold[] thresholds) {
Threshold[] t = new Threshold[thresholds.length];
for (int i=0; i<t.length; i++) {
@ -76,6 +82,7 @@ public final class HSSFIconMultiStateFormatting implements org.apache.poi.ss.use
iconFormatting.setThresholds(t);
}
@Override
public HSSFConditionalFormattingThreshold createThreshold() {
return new HSSFConditionalFormattingThreshold(new IconMultiStateThreshold(), sheet);
}

View File

@ -48,6 +48,7 @@ public class HSSFWorkbookFactory implements WorkbookProvider {
*
* @return The created workbook
*/
@Override
public HSSFWorkbook create() {
return new HSSFWorkbook();
}
@ -66,6 +67,7 @@ public class HSSFWorkbookFactory implements WorkbookProvider {
* Note that in order to properly release resources the
* Workbook should be closed after use.
*/
@Override
public HSSFWorkbook create(final DirectoryNode root, String password) throws IOException {
boolean passwordSet = false;
if (password != null) {
@ -93,6 +95,7 @@ public class HSSFWorkbookFactory implements WorkbookProvider {
}
@Override
@SuppressWarnings("java:S2095")
public Workbook create(File file, String password, boolean readOnly) throws IOException {
boolean passwordSet = false;
if (password != null) {
@ -104,11 +107,8 @@ public class HSSFWorkbookFactory implements WorkbookProvider {
try {
return new HSSFWorkbook(fs, true);
} catch (RuntimeException e) {
// we need to close the filesystem
// if we encounter an exception to
// not leak file handles
// we need to close the filesystem if we encounter an exception to not leak file handles
fs.close();
throw e;
}
} finally {

View File

@ -28,7 +28,7 @@ import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.commons.io.input.BoundedInputStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.poifs.crypt.ChunkedCipherInputStream;
import org.apache.poi.poifs.crypt.CryptoFunctions;
@ -39,11 +39,9 @@ import org.apache.poi.poifs.crypt.EncryptionVerifier;
import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.DocumentNode;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.BitField;
import org.apache.poi.util.BitFieldFactory;
import org.apache.commons.io.input.BoundedInputStream;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndianInputStream;
@ -170,14 +168,10 @@ public class CryptoAPIDecryptor extends Decryptor {
*/
public POIFSFileSystem getSummaryEntries(DirectoryNode root, String encryptedStream)
throws IOException, GeneralSecurityException {
DocumentNode es = (DocumentNode) root.getEntry(encryptedStream);
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (DocumentInputStream dis = root.createDocumentInputStream(es)) {
IOUtils.copy(dis, bos);
}
POIFSFileSystem fsOut = null;
try (
CryptoAPIDocumentInputStream sbis = new CryptoAPIDocumentInputStream(this, bos.toByteArray());
DocumentInputStream dis = root.createDocumentInputStream(root.getEntry(encryptedStream));
CryptoAPIDocumentInputStream sbis = new CryptoAPIDocumentInputStream(this, IOUtils.toByteArray(dis));
LittleEndianInputStream leis = new LittleEndianInputStream(sbis)
) {
int streamDescriptorArrayOffset = (int) leis.readUInt();

View File

@ -68,6 +68,7 @@ import org.apache.poi.util.StringUtil;
*
* @since 3.15-beta2
*/
@SuppressWarnings("unused")
public class VBAMacroReader implements Closeable {
private static final Logger LOGGER = LogManager.getLogger(VBAMacroReader.class);
@ -667,13 +668,12 @@ public class VBAMacroReader implements Closeable {
private static String readUnicode(InputStream is) throws IOException {
//reads null-terminated unicode string
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
int b0 = IOUtils.readByte(is);
int b1 = IOUtils.readByte(is);
int read = 2;
while ((b0 + b1) != 0 && read < MAX_STRING_LENGTH) {
bos.write(b0);
bos.write(b1);
b0 = IOUtils.readByte(is);
@ -685,9 +685,10 @@ public class VBAMacroReader implements Closeable {
}
return bos.toString(StandardCharsets.UTF_16LE);
}
}
private static String readMBCS(int firstByte, InputStream is, Charset charset) throws IOException {
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
int len = 0;
int b = firstByte;
while (b > 0 && len < MAX_STRING_LENGTH) {
@ -697,6 +698,7 @@ public class VBAMacroReader implements Closeable {
}
return bos.toString(charset);
}
}
/**
* Read {@code length} bytes of MBCS (multi-byte character set) characters from the stream
@ -792,9 +794,7 @@ public class VBAMacroReader implements Closeable {
*/
private static byte[] findCompressedStreamWBruteForce(InputStream is) throws IOException {
//buffer to memory for multiple tries
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
IOUtils.copy(is, bos);
byte[] compressed = bos.toByteArray();
byte[] compressed = IOUtils.toByteArray(is);
byte[] decompressed = null;
for (int i = 0; i < compressed.length; i++) {
if (compressed[i] == 0x01 && i < compressed.length-1) {
@ -821,12 +821,10 @@ public class VBAMacroReader implements Closeable {
}
private static byte[] tryToDecompress(InputStream is) {
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try {
IOUtils.copy(new RLEDecompressingInputStream(is), bos);
try (RLEDecompressingInputStream ris = new RLEDecompressingInputStream(is)) {
return IOUtils.toByteArray(ris);
} catch (IllegalArgumentException | IOException | IllegalStateException e){
return null;
}
return bos.toByteArray();
}
}

View File

@ -162,15 +162,14 @@ public class EmbeddedExtractor implements Iterable<EmbeddedExtractor> {
protected EmbeddedData extract(DirectoryNode dn) throws IOException {
assert(canExtract(dn));
UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(20000);
try (POIFSFileSystem dest = new POIFSFileSystem()) {
try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(20000);
POIFSFileSystem dest = new POIFSFileSystem()) {
copyNodes(dn, dest.getRoot());
// start with a reasonable big size
dest.writeFilesystem(bos);
}
return new EmbeddedData(dn.getName(), bos.toByteArray(), CONTENT_TYPE_BYTES);
}
}
protected EmbeddedData extract(Picture source) throws IOException {
return null;

View File

@ -27,7 +27,7 @@ package org.apache.poi.ss.usermodel;
* icon and which Yellow or Red.</p>
*/
public interface ConditionalFormattingThreshold {
public enum RangeType {
enum RangeType {
/** Number / Parameter */
NUMBER(1, "num"),
/** The minimum value from the range */
@ -61,7 +61,7 @@ public interface ConditionalFormattingThreshold {
return null;
}
private RangeType(int id, String name) {
RangeType(int id, String name) {
this.id = id; this.name = name;
}
}
@ -82,19 +82,19 @@ public interface ConditionalFormattingThreshold {
/**
* Formula to use to calculate the threshold,
* or <code>null</code> if no formula
* or {@code null} if no formula
*/
String getFormula();
/**
* Sets the formula used to calculate the threshold,
* or unsets it if <code>null</code> is given.
* or unsets it if {@code null} is given.
*/
void setFormula(String formula);
/**
* Gets the value used for the threshold, or
* <code>null</code> if there isn't one.
* {@code null} if there isn't one.
*/
Double getValue();
@ -104,7 +104,7 @@ public interface ConditionalFormattingThreshold {
* {@link RangeType#PERCENTILE} it must be between 0 and 100.
* <p>If the type is {@link RangeType#MIN} or {@link RangeType#MAX}
* or {@link RangeType#FORMULA} it shouldn't be set.
* <p>Use <code>null</code> to unset
* <p>Use {@code null} to unset
*/
void setValue(Double value);
}

View File

@ -265,6 +265,7 @@ public class GenericRecordJsonWriter implements Closeable {
return true;
}
@SuppressWarnings("java:S3516")
protected boolean printNumber(String name, Object o) {
Number n = (Number)o;
printName(name);

View File

@ -178,8 +178,7 @@ public final class IOUtils {
}
final int len = Math.min(length, maxLength);
UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(len == Integer.MAX_VALUE ? 4096 : len);
try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(len == Integer.MAX_VALUE ? 4096 : len)) {
byte[] buffer = new byte[4096];
int totalBytes = 0, readBytes;
do {
@ -202,6 +201,7 @@ public final class IOUtils {
return baos.toByteArray();
}
}
private static void checkLength(long length, int maxLength) {
if (BYTE_ARRAY_MAX_OVERRIDE > 0) {

View File

@ -25,8 +25,6 @@ import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.File;
import java.lang.reflect.Field;
@ -47,6 +45,7 @@ import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
* Util class for POI JUnit TestCases, which provide additional features
*/
@Internal
@SuppressWarnings("java:S2187")
public final class POITestCase {
private POITestCase() {
@ -141,68 +140,6 @@ public final class POITestCase {
assertTrue(new ReflectionEquals(expected, "$jacocoData").matches(actual));
}
/**
* Rather than adding {@literal @}Ignore to known-failing tests,
* write the test so that it notifies us if it starts passing.
* This is useful for closing related or forgotten bugs.
*
* An Example:
* <code><pre>
* public static int add(int a, int b) {
* // a known bug in behavior that has not been fixed yet
* raise UnsupportedOperationException("add");
* }
*
* {@literal @}Test
* void knownFailingUnitTest() {
* try {
* assertEquals(2, add(1,1));
* // this test fails because the assumption that this bug had not been fixed is false
* testPassesNow(12345);
* } catch (UnsupportedOperationException e) {
* // test is skipped because the assumption that this bug had not been fixed is true
* skipTest(e);
* }
* }
*
* Once passing, this unit test can be rewritten as:
* {@literal @}Test
* void knownPassingUnitTest() {
* assertEquals(2, add(1,1));
* }
*
* If you have a better idea how to simplify test code while still notifying
* us when a previous known-failing test now passes, please improve these.
* As a bonus, a known-failing test that fails should not be counted as a
* passing test.
*
* One possible alternative is to expect the known exception, but without
* a clear message that it is a good thing to no longer get the expected
* exception once the test passes.
* {@literal @}Test(expected=UnsupportedOperationException.class)
* void knownFailingUnitTest() {
* assertEquals(2, add(1,1));
* }
*
* @param e the exception that was caught that will no longer
* be raised when the bug is fixed
*/
public static void skipTest(Throwable e) {
assumeTrue(e != null, "This test currently fails with");
}
/**
* @see #skipTest(Throwable)
*
* @param bug the bug number corresponding to a known bug in bugzilla
*/
public static void testPassesNow(int bug) {
fail("This test passes now. Please update the unit test and bug " + bug + ".");
}
public static void assertBetween(String message, int value, int min, int max) {
assertTrue(min <= value, message + ": " + value + " is less than the minimum value of " + min);
assertTrue(value <= max, message + ": " + value + " is greater than the maximum value of " + max);
}
/**
* Ensures that the temporary directory is defined and exists and

View File

@ -1382,6 +1382,7 @@ public abstract class BaseTestBugzillaIssues {
}
@Test
@SuppressWarnings("java:S2699")
void test58896() throws IOException {
final int nrows = 160;
final int ncols = 139;
@ -1493,8 +1494,8 @@ public abstract class BaseTestBugzillaIssues {
// *******************************
// First cell of array formula, OK
int rowId = 0;
int cellId = 1;
final int rowId = 0;
final int cellId = 1;
Row row = sheet.getRow(rowId);
Cell cell = row.getCell(cellId);
@ -1507,9 +1508,6 @@ public abstract class BaseTestBugzillaIssues {
// *******************************
// Second cell of array formula, NOT OK for xlsx files
rowId = 1;
cellId = 1;
row = sheet.getRow(rowId);
cell = row.getCell(cellId);
assertEquals("A1", cell.getCellFormula());

View File

@ -17,7 +17,6 @@
package org.apache.poi.ss.usermodel;
import static org.apache.poi.POITestCase.assertBetween;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@ -50,8 +49,7 @@ import org.junit.jupiter.api.Test;
/**
* Common superclass for testing {@link org.apache.poi.hssf.usermodel.HSSFCell},
* {@link org.apache.poi.xssf.usermodel.XSSFCell} and
* {@link org.apache.poi.xssf.streaming.SXSSFCell}
* XSSFCell and SXSSFCell
*/
public abstract class BaseTestSheet {
private static final int ROW_COUNT = 40000;
@ -430,7 +428,7 @@ public abstract class BaseTestSheet {
assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions());
Collection<Integer> removed = Arrays.asList(0, 2, 3, 6, 8);
mergedRegions.keySet().removeAll(removed);
removed.forEach(mergedRegions.keySet()::remove);
sheet.removeMergedRegions(removed);
assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions());
}
@ -1364,4 +1362,9 @@ public abstract class BaseTestSheet {
assertBetween("Date column width", s.getColumnWidth(1), 4750, 7300);
}
}
private static void assertBetween(String message, int value, int min, int max) {
assertTrue(min <= value, message + ": " + value + " is less than the minimum value of " + min);
assertTrue(value <= max, message + ": " + value + " is greater than the maximum value of " + max);
}
}

View File

@ -17,8 +17,6 @@
package org.apache.poi.ss.usermodel;
import static org.apache.poi.POITestCase.skipTest;
import static org.apache.poi.POITestCase.testPassesNow;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@ -60,14 +58,13 @@ public abstract class BaseTestSheetShiftRows {
public final void testShiftRows() throws IOException {
// Read initial file in
String sampleName = "SimpleMultiCell." + _testDataProvider.getStandardFileNameExtension();
Workbook wb1 = _testDataProvider.openSampleWorkbook(sampleName);
try (Workbook wb1 = _testDataProvider.openSampleWorkbook(sampleName)) {
Sheet s = wb1.getSheetAt(0);
// Shift the second row down 1 and write to temp file
s.shiftRows(1, 1, 1);
Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
// Read from temp file and check the number of cells in each
// row (in original file each row was unique)
@ -82,9 +79,7 @@ public abstract class BaseTestSheetShiftRows {
// Shift rows 1-3 down 3 in the current one. This tests when
// 1 row is blank. Write to a another temp file
s.shiftRows(0, 2, 3);
Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2);
wb2.close();
try (Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2)) {
// Read and ensure things are where they should be
s = wb3.getSheetAt(0);
confirmEmptyRow(s, 0);
@ -93,24 +88,25 @@ public abstract class BaseTestSheetShiftRows {
assertEquals(s.getRow(3).getPhysicalNumberOfCells(), 1);
confirmEmptyRow(s, 4);
assertEquals(s.getRow(5).getPhysicalNumberOfCells(), 2);
wb3.close();
}
}
}
// Read the first file again
Workbook wb4 = _testDataProvider.openSampleWorkbook(sampleName);
s = wb4.getSheetAt( 0 );
try (Workbook wb4 = _testDataProvider.openSampleWorkbook(sampleName)) {
Sheet s = wb4.getSheetAt(0);
// Shift rows 3 and 4 up and write to temp file
s.shiftRows(2, 3, -2);
Workbook wb5 = _testDataProvider.writeOutAndReadBack(wb4);
wb4.close();
try (Workbook wb5 = _testDataProvider.writeOutAndReadBack(wb4)) {
s = wb5.getSheetAt(0);
assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 3);
assertEquals(s.getRow(1).getPhysicalNumberOfCells(), 4);
confirmEmptyRow(s, 2);
confirmEmptyRow(s, 3);
assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5);
wb5.close();
}
}
}
private static void confirmEmptyRow(Sheet s, int rowIx) {
Row row = s.getRow(rowIx);
@ -149,7 +145,7 @@ public abstract class BaseTestSheetShiftRows {
@Test
void testShiftWithComments() throws IOException {
Workbook wb1 = _testDataProvider.openSampleWorkbook("comments." + _testDataProvider.getStandardFileNameExtension());
try (Workbook wb1 = _testDataProvider.openSampleWorkbook("comments." + _testDataProvider.getStandardFileNameExtension())) {
Sheet sheet = wb1.getSheet("Sheet1");
assertEquals(3, sheet.getLastRowNum());
@ -189,8 +185,7 @@ public abstract class BaseTestSheetShiftRows {
// Write out and read back in again
// Ensure that the changes were persisted
Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
sheet = wb2.getSheet("Sheet1");
assertEquals(4, sheet.getLastRowNum());
@ -228,13 +223,13 @@ public abstract class BaseTestSheetShiftRows {
assertEquals(comment1, "comment top row3 (index2)\n");
String comment2 = sheet.getCellComment(new CellAddress(2, 0)).getString().getString();
assertEquals(comment2, "comment top row4 (index3)\n");
wb2.close();
}
}
}
@Test
public final void testShiftWithNames() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet1 = wb.createSheet("Sheet1");
wb.createSheet("Sheet2");
Row row = sheet1.createRow(0);
@ -273,13 +268,12 @@ public abstract class BaseTestSheetShiftRows {
name4 = wb.getName("name4");
assertEquals("A1", name4.getRefersToFormula());
wb.close();
}
}
@Test
public final void testShiftWithMergedRegions() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
row.createCell(0).setCellValue(1.1);
@ -292,13 +286,13 @@ public abstract class BaseTestSheetShiftRows {
sheet.shiftRows(0, 1, 2);
region = sheet.getMergedRegion(0);
assertEquals("A3:C3", region.formatAsString());
wb.close();
}
}
//@Disabled("bug 56454: Incorrectly handles merged regions that do not contain column 0")
@Test
public final void shiftWithMergedRegions_bug56454() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet();
// populate sheet cells
for (int i = 0; i < 10; i++) {
@ -331,13 +325,8 @@ public abstract class BaseTestSheetShiftRows {
// This test is written as expected-to-fail and should be rewritten
// as expected-to-pass when the bug is fixed.
// FIXME: remove try, catch, and testPassesNow, skipTest when test passes
try {
assertEquals(expectedMergedRegions, sheet.getMergedRegions());
testPassesNow(56454);
} catch (AssertionError e) {
skipTest(e);
assertNotEquals(expectedMergedRegions, sheet.getMergedRegions());
}
wb.close();
}
@ -347,7 +336,7 @@ public abstract class BaseTestSheetShiftRows {
*/
@Test
public final void testShiftWithFormulas() throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook("ForShifting." + _testDataProvider.getStandardFileNameExtension());
try (Workbook wb = _testDataProvider.openSampleWorkbook("ForShifting." + _testDataProvider.getStandardFileNameExtension())) {
Sheet sheet = wb.getSheet("Sheet1");
assertEquals(20, sheet.getLastRowNum());
@ -398,9 +387,8 @@ public abstract class BaseTestSheetShiftRows {
confirmCell(sheet2, 11, 0, 300, "300+Sheet1!#REF!");
// Note - named ranges formulas have not been updated
wb.close();
}
}
private static void confirmRow(Sheet sheet, int rowIx, double valA, double valB, double valC,
@ -419,7 +407,7 @@ public abstract class BaseTestSheetShiftRows {
@Test
public final void testShiftSharedFormulasBug54206() throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook("54206." + _testDataProvider.getStandardFileNameExtension());
try (Workbook wb = _testDataProvider.openSampleWorkbook("54206." + _testDataProvider.getStandardFileNameExtension())) {
Sheet sheet = wb.getSheetAt(0);
assertEquals("SUMIF($B$19:$B$82,$B4,G$19:G$82)", sheet.getRow(3).getCell(6).getCellFormula());
@ -472,19 +460,19 @@ public abstract class BaseTestSheetShiftRows {
assertEquals("SUM(G29:I29)", sheet.getRow(28).getCell(9).getCellFormula());
assertEquals("SUM(G30:I30)", sheet.getRow(29).getCell(9).getCellFormula());
wb.close();
}
}
@Test
void testBug55280() throws IOException {
Workbook w = _testDataProvider.createWorkbook();
try (Workbook w = _testDataProvider.createWorkbook()) {
Sheet s = w.createSheet();
for (int row = 0; row < 5000; ++row) {
assertEquals(row, s.addMergedRegion(new CellRangeAddress(row, row, 0, 3)));
}
s.shiftRows(0, 4999, 1); // takes a long time...
w.close();
}
}
@Test
@ -504,7 +492,7 @@ public abstract class BaseTestSheetShiftRows {
*/
@Test
void testBug46742_52903_shiftHyperlinks() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet("test");
Row row = sheet.createRow(0);
@ -553,11 +541,8 @@ public abstract class BaseTestSheetShiftRows {
int n = 3;
sheet.shiftRows(startRow, endRow, n);
Workbook read = _testDataProvider.writeOutAndReadBack(wb);
wb.close();
try (Workbook read = _testDataProvider.writeOutAndReadBack(wb)) {
Sheet sh = read.getSheet("test");
Row shiftedRow = sh.getRow(3);
// document link anchored on a shifted cell should be moved
@ -590,14 +575,14 @@ public abstract class BaseTestSheetShiftRows {
unaffectedCell = read.getSheet("other").getRow(0).getCell(0);
assertTrue(cellHasHyperlink(unaffectedCell));
verifyHyperlink(unaffectedCell, HyperlinkType.URL, "http://apache.org/");
read.close();
}
}
}
//@Disabled("bug 56454: Incorrectly handles merged regions that do not contain column 0")
@Test
void shiftRowsWithMergedRegionsThatDoNotContainColumnZero() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet("test");
// populate sheet cells
@ -622,21 +607,15 @@ public abstract class BaseTestSheetShiftRows {
// This test is written as expected-to-fail and should be rewritten
// as expected-to-pass when the bug is fixed.
// FIXME: remove try, catch, and testPassesNow, skipTest when test passes
try {
assertEquals(2, sheet.getNumMergedRegions());
assertEquals(CellRangeAddress.valueOf("A4:B8"), sheet.getMergedRegion(0));
assertEquals(CellRangeAddress.valueOf("C5:D8"), sheet.getMergedRegion(1));
testPassesNow(56454);
} catch (AssertionError e) {
skipTest(e);
assertNotEquals(CellRangeAddress.valueOf("A4:B8"), sheet.getMergedRegion(0));
assertNotEquals(CellRangeAddress.valueOf("C5:D8"), sheet.getMergedRegion(1));
}
wb.close();
}
@Test
void shiftMergedRowsToMergedRowsUp() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet("test");
populateSheetCells(sheet, 2);
@ -653,13 +632,12 @@ public abstract class BaseTestSheetShiftRows {
assertEquals(1, sheet.getNumMergedRegions());
assertEquals(CellRangeAddress.valueOf("A1:C1"), sheet.getMergedRegion(0));
wb.close();
}
}
@Test
void shiftMergedRowsToMergedRowsOverlappingMergedRegion() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet("test");
populateSheetCells(sheet, 10);
@ -675,13 +653,12 @@ public abstract class BaseTestSheetShiftRows {
assertEquals(1, sheet.getNumMergedRegions());
assertEquals(CellRangeAddress.valueOf("A5:E5"), sheet.getMergedRegion(0));
wb.close();
}
}
@Test
void bug60384ShiftMergedRegion() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet("test");
populateSheetCells(sheet, 9);
@ -699,8 +676,7 @@ public abstract class BaseTestSheetShiftRows {
assertEquals(2, sheet.getNumMergedRegions());
assertEquals(CellRangeAddress.valueOf("A9:E9"), sheet.getMergedRegion(0));
assertEquals(CellRangeAddress.valueOf("A10:C10"), sheet.getMergedRegion(1));
wb.close();
}
}
private void populateSheetCells(Sheet sheet, int rowCount) {
@ -716,7 +692,7 @@ public abstract class BaseTestSheetShiftRows {
@Test
void shiftMergedRowsToMergedRowsDown() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet("test");
// populate sheet cells
@ -734,13 +710,12 @@ public abstract class BaseTestSheetShiftRows {
assertEquals(1, sheet.getNumMergedRegions());
assertEquals(CellRangeAddress.valueOf("A2:E2"), sheet.getMergedRegion(0));
wb.close();
}
}
@Test
void test61840_shifting_rows_up_does_not_produce_REF_errors() throws IOException {
Workbook wb = _testDataProvider.createWorkbook();
try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet();
Cell cell = sheet.createRow(4).createCell(0);
@ -756,14 +731,13 @@ public abstract class BaseTestSheetShiftRows {
Cell shiftedCell = sheet.getRow(3).getCell(0);
assertNotNull(shiftedCell);
assertEquals("(B4-C4)/B4", shiftedCell.getCellFormula());
wb.close();
}
}
@Test
void checkMergedRegions56454() {
Workbook wb = _testDataProvider.createWorkbook();
void checkMergedRegions56454() throws IOException {
try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet();
// populate sheet cells
@ -792,6 +766,7 @@ public abstract class BaseTestSheetShiftRows {
assertEquals(cr.getFirstRow(), 3);
}
}
}

View File

@ -724,7 +724,7 @@ public abstract class BaseTestWorkbook {
}
@Test
void changeSheetNameWithSharedFormulas() throws IOException {
protected void changeSheetNameWithSharedFormulas() throws IOException {
String sampleFile = "shared_formulas.xls" + (getClass().getName().contains("xssf") ? "x" : "");
try (Workbook wb = _testDataProvider.openSampleWorkbook(sampleFile)) {