summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAndreas Beeker <kiwiwings@apache.org>2020-08-17 20:25:08 +0000
committerAndreas Beeker <kiwiwings@apache.org>2020-08-17 20:25:08 +0000
commitb7b0a0c21579b38b8f1aa553eda35564cb01e3d2 (patch)
tree8f6d7afee458bdd761965d49f4a8ccb218022361
parentf8040e5f8c0e74b064db13c93ec9c5025542848c (diff)
downloadpoi-b7b0a0c21579b38b8f1aa553eda35564cb01e3d2.tar.gz
poi-b7b0a0c21579b38b8f1aa553eda35564cb01e3d2.zip
Activate Forbidden-Apis-Check also for other tests
Max supported Java version is currently Java 14 Fix the check failures git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1880944 13f79535-47bb-0310-9956-ffa450edef68
-rw-r--r--build.xml29
-rw-r--r--src/examples/src/org/apache/poi/examples/hsmf/Msg2txt.java2
-rw-r--r--src/examples/src/org/apache/poi/examples/ss/BusinessPlan.java6
-rw-r--r--src/examples/src/org/apache/poi/examples/ss/CalendarDemo.java3
-rw-r--r--src/examples/src/org/apache/poi/examples/ss/ExcelComparator.java6
-rw-r--r--src/examples/src/org/apache/poi/examples/ss/SSPerformanceTest.java6
-rw-r--r--src/examples/src/org/apache/poi/examples/ss/ToCSV.java5
-rw-r--r--src/examples/src/org/apache/poi/examples/ss/html/ToHtml.java14
-rw-r--r--src/examples/src/org/apache/poi/examples/xslf/BarChartDemo.java6
-rw-r--r--src/examples/src/org/apache/poi/examples/xslf/ChartFromScratch.java6
-rw-r--r--src/examples/src/org/apache/poi/examples/xslf/PieChartDemo.java6
-rw-r--r--src/examples/src/org/apache/poi/examples/xssf/usermodel/BigGridDemo.java3
-rw-r--r--src/examples/src/org/apache/poi/examples/xssf/usermodel/CalendarDemo.java3
-rw-r--r--src/examples/src/org/apache/poi/examples/xssf/usermodel/CreatePivotTable2.java5
-rw-r--r--src/examples/src/org/apache/poi/examples/xwpf/usermodel/BarChartExample.java6
-rw-r--r--src/examples/src/org/apache/poi/examples/xwpf/usermodel/ChartFromScratch.java6
-rw-r--r--src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java9
-rw-r--r--src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java2
-rw-r--r--src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java8
-rw-r--r--src/integrationtest/org/apache/poi/stress/HeapDump.java2
-rw-r--r--src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java76
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java4
-rw-r--r--src/resources/devtools/forbidden-signatures-prod.txt2
-rw-r--r--src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java4
-rw-r--r--src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java32
-rw-r--r--src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java103
-rw-r--r--src/scratchpad/testcases/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java9
-rw-r--r--src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java4
-rw-r--r--src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java8
-rw-r--r--src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java11
-rw-r--r--src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java3
-rw-r--r--src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java14
-rw-r--r--src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java12
-rw-r--r--src/testcases/org/apache/poi/hssf/dev/TestReSave.java12
-rw-r--r--src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java4
-rw-r--r--src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java1169
-rw-r--r--src/testcases/org/apache/poi/util/NullPrintStream.java88
37 files changed, 836 insertions, 852 deletions
diff --git a/build.xml b/build.xml
index 6613faee44..54537d17fd 100644
--- a/build.xml
+++ b/build.xml
@@ -1549,7 +1549,7 @@ under the License.
<delete dir="build" includes="test-integration.log*"/>
<path id="test-integration.modules">
- <pathelement path="build/dist/maven/poi"/>
+ <pathelement path="build/dist/maven/poi-tests"/>
<pathelement path="build/dist/maven/poi-ooxml"/>
<pathelement path="build/dist/maven/poi-scratchpad"/>
<pathelement path="build/dist/maven/poi-examples"/>
@@ -2252,16 +2252,22 @@ under the License.
<fileset dir="lib/ooxml-provided" includes="*.jar"/>
<fileset dir="lib/excelant" includes="*.jar"/>
<pathelement location="${ooxml.xsds.jar}"/>
+ <pathelement location="build/dist/maven/poi-tests/poi-${version.id}-tests.jar"/>
<pathelement location="build/dist/maven/poi-examples/poi-examples-${version.id}.jar"/>
<path path="${env.CLASSPATH}"/>
</path>
+ <!-- forbiddenapis bundled signatures max supported version is 14 -->
+ <condition property="forbiddenVersion" value="14">
+ <javaversion atleast="15"/>
+ </condition>
+ <property name="forbiddenVersion" value="${ant.java.version}"/>
<!-- first check rules that apply to all the source code -->
<forbiddenapis
classpathref="forbiddenapis.classpath"
suppressAnnotation="org.apache.poi.util.SuppressForbidden"
- targetVersion="${ant.java.version}"
+ targetVersion="${forbiddenVersion}"
>
<bundledsignatures name="jdk-unsafe"/>
<bundledsignatures name="jdk-deprecated"/>
@@ -2272,29 +2278,20 @@ under the License.
<bundledsignatures name="jdk-system-out"/>
-->
<signaturesFileset file="src/resources/devtools/forbidden-signatures.txt"/>
- <!-- sources -->
- <!-- zipfileset src="build/dist/maven/poi/poi-${version.id}.jar"/ -->
- <!-- zipfileset src="build/dist/maven/poi-ooxml/poi-ooxml-${version.id}.jar"/ -->
- <zipfileset src="build/dist/maven/poi-scratchpad/poi-scratchpad-${version.id}.jar"/>
- <zipfileset src="build/dist/maven/poi-excelant/poi-excelant-${version.id}.jar"/>
- <!--
- <fileset dir="${examples.output.dir}"/>
- -->
<!-- test-sources (incl. sources) -->
<zipfileset src="build/dist/maven/poi-tests/poi-${version.id}-tests.jar"/>
<zipfileset src="build/dist/maven/poi-ooxml-tests/poi-ooxml-${version.id}-tests.jar"/>
- <!--
- <fileset dir="${scratchpad.output.test.dir}"/>
- <fileset dir="${excelant.output.test.dir}"/>
- <fileset dir="${integration.output.test.dir}"/>
- -->
+ <zipfileset src="build/dist/maven/poi-scratchpad-tests/poi-scratchpad-${version.id}-tests.jar"/>
+ <zipfileset src="build/dist/maven/poi-excelant-tests/poi-excelant-${version.id}-tests.jar"/>
+ <zipfileset src="build/dist/maven/poi-examples/poi-examples-${version.id}.jar"/>
+ <zipfileset src="build/dist/maven/poi-integration/poi-integration-${version.id}.jar"/>
</forbiddenapis>
<!-- then check some advanced rules which we only apply to the core code and not tests or examples -->
<forbiddenapis
classpathref="forbiddenapis.classpath"
suppressAnnotation="org.apache.poi.util.SuppressForbidden"
- targetVersion="${jdk.version.source}"
+ targetVersion="${forbiddenVersion}"
>
<signaturesFileset file="src/resources/devtools/forbidden-signatures-prod.txt"/>
<!-- sources -->
diff --git a/src/examples/src/org/apache/poi/examples/hsmf/Msg2txt.java b/src/examples/src/org/apache/poi/examples/hsmf/Msg2txt.java
index a4756a27d5..4ab88cf27a 100644
--- a/src/examples/src/org/apache/poi/examples/hsmf/Msg2txt.java
+++ b/src/examples/src/org/apache/poi/examples/hsmf/Msg2txt.java
@@ -62,7 +62,7 @@ public class Msg2txt {
public void processMessage() throws IOException {
String txtFileName = fileNameStem + ".txt";
String attDirName = fileNameStem + "-att";
- try (PrintWriter txtOut = new PrintWriter(txtFileName)) {
+ try (PrintWriter txtOut = new PrintWriter(txtFileName, "UTF-8")) {
try {
String displayFrom = msg.getDisplayFrom();
txtOut.println("From: " + displayFrom);
diff --git a/src/examples/src/org/apache/poi/examples/ss/BusinessPlan.java b/src/examples/src/org/apache/poi/examples/ss/BusinessPlan.java
index 59ccc6f337..a4865a32a3 100644
--- a/src/examples/src/org/apache/poi/examples/ss/BusinessPlan.java
+++ b/src/examples/src/org/apache/poi/examples/ss/BusinessPlan.java
@@ -21,6 +21,7 @@ import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@@ -36,6 +37,7 @@ import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
@@ -96,7 +98,7 @@ public final class BusinessPlan {
if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook();
else wb = new XSSFWorkbook();
- final SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM");
+ final SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM", Locale.ROOT);
Map<String, CellStyle> styles = createStyles(wb);
@@ -124,7 +126,7 @@ public final class BusinessPlan {
cell.setCellStyle(styles.get("header"));
}
//columns for 11 weeks starting from 9-Jul
- Calendar calendar = Calendar.getInstance();
+ Calendar calendar = LocaleUtil.getLocaleCalendar();
int year = calendar.get(Calendar.YEAR);
calendar.setTime(fmt.parse("9-Jul"));
diff --git a/src/examples/src/org/apache/poi/examples/ss/CalendarDemo.java b/src/examples/src/org/apache/poi/examples/ss/CalendarDemo.java
index f11c1e0227..9253153f9e 100644
--- a/src/examples/src/org/apache/poi/examples/ss/CalendarDemo.java
+++ b/src/examples/src/org/apache/poi/examples/ss/CalendarDemo.java
@@ -36,6 +36,7 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
@@ -62,7 +63,7 @@ public final class CalendarDemo {
public static void main(String[] args) throws Exception {
- Calendar calendar = Calendar.getInstance();
+ Calendar calendar = LocaleUtil.getLocaleCalendar();
boolean xlsx = true;
for (String arg : args) {
if (arg.charAt(0) == '-') {
diff --git a/src/examples/src/org/apache/poi/examples/ss/ExcelComparator.java b/src/examples/src/org/apache/poi/examples/ss/ExcelComparator.java
index 825b72b0c2..c09efaec1b 100644
--- a/src/examples/src/org/apache/poi/examples/ss/ExcelComparator.java
+++ b/src/examples/src/org/apache/poi/examples/ss/ExcelComparator.java
@@ -17,6 +17,8 @@
package org.apache.poi.examples.ss;
import java.io.File;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
@@ -94,6 +96,8 @@ public class ExcelComparator {
}
List<String> listOfDifferences = new ArrayList<>();
+ private final DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
+
public static void main(String[] args) throws Exception {
if (args.length != 2 || !(new File(args[0]).exists()) || !(new File(args[1]).exists())) {
@@ -429,7 +433,7 @@ public class ExcelComparator {
Date date1 = loc1.cell.getDateCellValue();
Date date2 = loc2.cell.getDateCellValue();
if (!date1.equals(date2)) {
- addMessage(loc1, loc2, CELL_DATA_DOES_NOT_MATCH, date1.toString(), date2.toString());
+ addMessage(loc1, loc2, CELL_DATA_DOES_NOT_MATCH, dateFormat.format(date1), dateFormat.format(date2));
}
}
diff --git a/src/examples/src/org/apache/poi/examples/ss/SSPerformanceTest.java b/src/examples/src/org/apache/poi/examples/ss/SSPerformanceTest.java
index a5b7eb7170..c041509d45 100644
--- a/src/examples/src/org/apache/poi/examples/ss/SSPerformanceTest.java
+++ b/src/examples/src/org/apache/poi/examples/ss/SSPerformanceTest.java
@@ -23,6 +23,7 @@ import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@@ -39,6 +40,7 @@ import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
+import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@@ -75,7 +77,7 @@ public final class SSPerformanceTest {
runWithArgs(type, rows, cols, saveFile);
long timeFinished = System.currentTimeMillis();
- System.out.printf("Elapsed %.2f seconds for arguments %s\n", ((double)timeFinished - timeStarted) / 1000, Arrays.toString(args));
+ System.out.printf(Locale.ROOT, "Elapsed %.2f seconds for arguments %s\n", ((double)timeFinished - timeStarted) / 1000, Arrays.toString(args));
}
private static void runWithArgs(String type, int rows, int cols, boolean saveFile) throws IOException {
@@ -103,7 +105,7 @@ public final class SSPerformanceTest {
int sheetNo = 0;
int rowIndexInSheet = 1;
double value = 0;
- Calendar calendar = Calendar.getInstance();
+ Calendar calendar = LocaleUtil.getLocaleCalendar();
for (int rowIndex = 0; rowIndex < rows; rowIndex++) {
if (isHType && sheetNo != rowIndex / 0x10000) {
sheet = workBook.createSheet("Spillover from sheet " + (++sheetNo));
diff --git a/src/examples/src/org/apache/poi/examples/ss/ToCSV.java b/src/examples/src/org/apache/poi/examples/ss/ToCSV.java
index 4e4a89732f..91a603f676 100644
--- a/src/examples/src/org/apache/poi/examples/ss/ToCSV.java
+++ b/src/examples/src/org/apache/poi/examples/ss/ToCSV.java
@@ -22,9 +22,10 @@ import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
-import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
import java.util.ArrayList;
import org.apache.poi.ss.usermodel.Cell;
@@ -431,7 +432,7 @@ public class ToCSV {
String csvLineElement;
// Open a writer onto the CSV file.
- try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
+ try (BufferedWriter bw = Files.newBufferedWriter(file.toPath(), StandardCharsets.ISO_8859_1)) {
System.out.println("Saving the CSV file [" + file.getName() + "]");
diff --git a/src/examples/src/org/apache/poi/examples/ss/html/ToHtml.java b/src/examples/src/org/apache/poi/examples/ss/html/ToHtml.java
index 930de56a29..f20604240f 100644
--- a/src/examples/src/org/apache/poi/examples/ss/html/ToHtml.java
+++ b/src/examples/src/org/apache/poi/examples/ss/html/ToHtml.java
@@ -19,15 +19,16 @@ package org.apache.poi.examples.ss.html;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileInputStream;
-import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
+import java.nio.charset.StandardCharsets;
import java.util.Formatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
@@ -189,10 +190,7 @@ public final class ToHtml {
return;
}
- try (
- FileWriter fw = new FileWriter(args[1]);
- PrintWriter pw = new PrintWriter(fw)
- ) {
+ try (PrintWriter pw = new PrintWriter(args[1], "UTF-8")) {
ToHtml toHtml = create(args[0], pw);
toHtml.setCompleteHTML(true);
toHtml.printPage();
@@ -243,7 +241,7 @@ public final class ToHtml {
private void ensureOut() {
if (out == null) {
- out = new Formatter(output);
+ out = new Formatter(output, Locale.ROOT);
}
}
@@ -252,7 +250,7 @@ public final class ToHtml {
// First, copy the base css
try (BufferedReader in = new BufferedReader(new InputStreamReader(
- getClass().getResourceAsStream("excelStyle.css")))){
+ getClass().getResourceAsStream("excelStyle.css"), StandardCharsets.ISO_8859_1))){
String line;
while ((line = in.readLine()) != null) {
out.format("%s%n", line);
@@ -325,7 +323,7 @@ public final class ToHtml {
style = wb.getCellStyleAt((short) 0);
}
StringBuilder sb = new StringBuilder();
- try (Formatter fmt = new Formatter(sb)) {
+ try (Formatter fmt = new Formatter(sb, Locale.ROOT)) {
fmt.format("style_%02x", style.getIndex());
return fmt.toString();
}
diff --git a/src/examples/src/org/apache/poi/examples/xslf/BarChartDemo.java b/src/examples/src/org/apache/poi/examples/xslf/BarChartDemo.java
index 6864c69810..3c8842d7fc 100644
--- a/src/examples/src/org/apache/poi/examples/xslf/BarChartDemo.java
+++ b/src/examples/src/org/apache/poi/examples/xslf/BarChartDemo.java
@@ -22,8 +22,10 @@ package org.apache.poi.examples.xslf;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.FileReader;
import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@@ -62,7 +64,7 @@ public final class BarChartDemo {
}
try (FileInputStream argIS = new FileInputStream(args[0]);
- BufferedReader modelReader = new BufferedReader(new FileReader(args[1]))) {
+ BufferedReader modelReader = Files.newBufferedReader(Paths.get(args[1]), StandardCharsets.ISO_8859_1)) {
String chartTitle = modelReader.readLine(); // first line is chart title
String[] series = modelReader.readLine().split(",");
diff --git a/src/examples/src/org/apache/poi/examples/xslf/ChartFromScratch.java b/src/examples/src/org/apache/poi/examples/xslf/ChartFromScratch.java
index d012744deb..58978a20e0 100644
--- a/src/examples/src/org/apache/poi/examples/xslf/ChartFromScratch.java
+++ b/src/examples/src/org/apache/poi/examples/xslf/ChartFromScratch.java
@@ -23,8 +23,10 @@ import java.awt.geom.Rectangle2D;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.FileReader;
import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@@ -70,7 +72,7 @@ public final class ChartFromScratch {
return;
}
- try (BufferedReader modelReader = new BufferedReader(new FileReader(args[0]))) {
+ try (BufferedReader modelReader = Files.newBufferedReader(Paths.get(args[0]), StandardCharsets.ISO_8859_1)) {
String chartTitle = modelReader.readLine(); // first line is chart title
String[] series = modelReader.readLine().split(",");
diff --git a/src/examples/src/org/apache/poi/examples/xslf/PieChartDemo.java b/src/examples/src/org/apache/poi/examples/xslf/PieChartDemo.java
index 9f0ca73fb6..4e9d799050 100644
--- a/src/examples/src/org/apache/poi/examples/xslf/PieChartDemo.java
+++ b/src/examples/src/org/apache/poi/examples/xslf/PieChartDemo.java
@@ -22,8 +22,10 @@ package org.apache.poi.examples.xslf;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.FileReader;
import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@@ -59,7 +61,7 @@ public final class PieChartDemo {
}
try (FileInputStream argIS = new FileInputStream(args[0]);
- BufferedReader modelReader = new BufferedReader(new FileReader(args[1]))) {
+ BufferedReader modelReader = Files.newBufferedReader(Paths.get(args[1]), StandardCharsets.ISO_8859_1)) {
String chartTitle = modelReader.readLine(); // first line is chart title
try (XMLSlideShow pptx = new XMLSlideShow(argIS)) {
diff --git a/src/examples/src/org/apache/poi/examples/xssf/usermodel/BigGridDemo.java b/src/examples/src/org/apache/poi/examples/xssf/usermodel/BigGridDemo.java
index 2afc73a6ab..574458f7be 100644
--- a/src/examples/src/org/apache/poi/examples/xssf/usermodel/BigGridDemo.java
+++ b/src/examples/src/org/apache/poi/examples/xssf/usermodel/BigGridDemo.java
@@ -40,6 +40,7 @@ import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellReference;
+import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFFont;
@@ -155,7 +156,7 @@ public final class BigGridDemo {
private static void generate(Writer out, Map<String, XSSFCellStyle> styles) throws Exception {
- Calendar calendar = Calendar.getInstance();
+ Calendar calendar = LocaleUtil.getLocaleCalendar();
SpreadsheetWriter sw = new SpreadsheetWriter(out);
sw.beginSheet();
diff --git a/src/examples/src/org/apache/poi/examples/xssf/usermodel/CalendarDemo.java b/src/examples/src/org/apache/poi/examples/xssf/usermodel/CalendarDemo.java
index b97ef1a8b9..28f2c48f27 100644
--- a/src/examples/src/org/apache/poi/examples/xssf/usermodel/CalendarDemo.java
+++ b/src/examples/src/org/apache/poi/examples/xssf/usermodel/CalendarDemo.java
@@ -28,6 +28,7 @@ import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.PrintOrientation;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
@@ -61,7 +62,7 @@ public class CalendarDemo {
public static void main(String[] args) throws Exception {
- Calendar calendar = Calendar.getInstance();
+ Calendar calendar = LocaleUtil.getLocaleCalendar();
if(args.length > 0) calendar.set(Calendar.YEAR, Integer.parseInt(args[0]));
int year = calendar.get(Calendar.YEAR);
diff --git a/src/examples/src/org/apache/poi/examples/xssf/usermodel/CreatePivotTable2.java b/src/examples/src/org/apache/poi/examples/xssf/usermodel/CreatePivotTable2.java
index 7ba0c78bdf..53951d0ebd 100644
--- a/src/examples/src/org/apache/poi/examples/xssf/usermodel/CreatePivotTable2.java
+++ b/src/examples/src/org/apache/poi/examples/xssf/usermodel/CreatePivotTable2.java
@@ -31,6 +31,7 @@ import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
+import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.XSSFPivotTable;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@@ -67,9 +68,9 @@ public class CreatePivotTable2 {
}
public static void setCellData(XSSFSheet sheet){
- Calendar cal1 = Calendar.getInstance();
+ Calendar cal1 = LocaleUtil.getLocaleCalendar();
cal1.set(2017, 0, 1, 0, 0, 0);
- Calendar cal2 = Calendar.getInstance();
+ Calendar cal2 = LocaleUtil.getLocaleCalendar();
cal2.set(2017, 1, 1, 0, 0, 0);
Row row1 = sheet.createRow(0);
// Create a cell and put a value in it.
diff --git a/src/examples/src/org/apache/poi/examples/xwpf/usermodel/BarChartExample.java b/src/examples/src/org/apache/poi/examples/xwpf/usermodel/BarChartExample.java
index 89bd260505..641d3e7bf4 100644
--- a/src/examples/src/org/apache/poi/examples/xwpf/usermodel/BarChartExample.java
+++ b/src/examples/src/org/apache/poi/examples/xwpf/usermodel/BarChartExample.java
@@ -23,8 +23,10 @@ package org.apache.poi.examples.xwpf.usermodel;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.FileReader;
import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@@ -61,7 +63,7 @@ public final class BarChartExample {
}
try (FileInputStream argIS = new FileInputStream(args[0]);
- BufferedReader modelReader = new BufferedReader(new FileReader(args[1]))) {
+ BufferedReader modelReader = Files.newBufferedReader(Paths.get(args[1]), StandardCharsets.ISO_8859_1)) {
String chartTitle = modelReader.readLine(); // first line is chart title
String[] series = modelReader.readLine().split(",");
diff --git a/src/examples/src/org/apache/poi/examples/xwpf/usermodel/ChartFromScratch.java b/src/examples/src/org/apache/poi/examples/xwpf/usermodel/ChartFromScratch.java
index 9eb0e2dd3f..1104c70057 100644
--- a/src/examples/src/org/apache/poi/examples/xwpf/usermodel/ChartFromScratch.java
+++ b/src/examples/src/org/apache/poi/examples/xwpf/usermodel/ChartFromScratch.java
@@ -21,8 +21,10 @@ package org.apache.poi.examples.xwpf.usermodel;
import java.io.BufferedReader;
import java.io.FileOutputStream;
-import java.io.FileReader;
import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@@ -65,7 +67,7 @@ public final class ChartFromScratch {
return;
}
- try (BufferedReader modelReader = new BufferedReader(new FileReader(args[0]))) {
+ try (BufferedReader modelReader = Files.newBufferedReader(Paths.get(args[0]), StandardCharsets.ISO_8859_1)) {
String chartTitle = modelReader.readLine(); // first line is chart title
String[] series = modelReader.readLine().split(",");
diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java b/src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java
index 703b97be04..49f804b4fa 100644
--- a/src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java
+++ b/src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java
@@ -28,6 +28,7 @@ import java.io.File;
import java.io.PrintStream;
import org.apache.poi.POIDataSamples;
+import org.apache.poi.util.NullPrintStream;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildListener;
@@ -140,12 +141,8 @@ public class TestBuildFile {
try {
sysOut.flush();
sysErr.flush();
- StringBuilder outBuffer = new StringBuilder();
- PrintStream out = new PrintStream(new AntOutputStream(outBuffer));
- System.setOut(out);
- StringBuilder errBuffer = new StringBuilder();
- PrintStream err = new PrintStream(new AntOutputStream(errBuffer));
- System.setErr(err);
+ System.setOut(new NullPrintStream());
+ System.setErr(new NullPrintStream());
logBuffer = new StringBuilder();
fullLogBuffer = new StringBuilder();
buildException = null;
diff --git a/src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java
index 2c125db1c0..dbbbea66a7 100644
--- a/src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java
+++ b/src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java
@@ -104,7 +104,7 @@ public class HPSFFileHandler extends POIFSFileHandler {
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
- PrintStream psNew = new PrintStream(bos);
+ PrintStream psNew = new PrintStream(bos, true, "ISO-8859-1");
PrintStream ps = System.out;
try {
System.setOut(psNew);
diff --git a/src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java
index b64105a93b..d4299776cc 100644
--- a/src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java
+++ b/src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java
@@ -22,7 +22,6 @@ import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
-import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.Set;
@@ -34,6 +33,7 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.util.NullPrintStream;
import org.junit.Test;
public class HSSFFileHandler extends SpreadsheetHandler {
@@ -88,11 +88,7 @@ public class HSSFFileHandler extends SpreadsheetHandler {
PrintStream oldOut = System.out;
String fileWithParent = file.getParentFile().getName() + "/" + file.getName();
try {
- System.setOut(new PrintStream(new OutputStream() {
- @Override
- public void write(int b) {
- }
- }));
+ System.setOut(new NullPrintStream());
BiffViewer.main(new String[]{file.getAbsolutePath()});
diff --git a/src/integrationtest/org/apache/poi/stress/HeapDump.java b/src/integrationtest/org/apache/poi/stress/HeapDump.java
index 59a3832b59..47736b504f 100644
--- a/src/integrationtest/org/apache/poi/stress/HeapDump.java
+++ b/src/integrationtest/org/apache/poi/stress/HeapDump.java
@@ -20,7 +20,9 @@ import java.io.IOException;
import java.lang.management.ManagementFactory;
import com.sun.management.HotSpotDiagnosticMXBean;
+import org.apache.poi.util.SuppressForbidden;
+@SuppressForbidden("class only exists for manual tests in XSSFFileHandler")
public class HeapDump {
// This is the name of the HotSpot Diagnostic MBean
private static final String HOTSPOT_BEAN_NAME =
diff --git a/src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java b/src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java
index c0f88768b8..b1aa5b718c 100644
--- a/src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java
+++ b/src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java
@@ -28,11 +28,9 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.Iterator;
-import java.util.Locale;
import java.util.Set;
import javax.xml.transform.TransformerException;
@@ -51,6 +49,7 @@ import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils;
+import org.apache.poi.util.NullPrintStream;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.extractor.XSSFExportToXml;
import org.apache.poi.xssf.usermodel.XSSFMap;
@@ -221,77 +220,4 @@ public class XSSFFileHandler extends SpreadsheetHandler {
public void testAdditional() throws Exception {
handleAdditional(new File("test-data/spreadsheet/poc-xmlbomb.xlsx"));
}
-
- // need to override all methods to omit calls to UTF-handling methods
- static class NullPrintStream extends PrintStream {
- @SuppressWarnings("resource")
- NullPrintStream() {
- super(new OutputStream() {
- @Override
- public void write(int b) {}
- @Override
- public void write(byte[] b) {}
- @Override
- public void write(byte[] b, int off, int len) {}
- });
- }
- @Override
- public void write(int b) {}
- @Override
- public void write(byte[] buf, int off, int len) {}
- @Override
- public void print(boolean b) {}
- @Override
- public void print(char c) {}
- @Override
- public void print(int i) {}
- @Override
- public void print(long l) {}
- @Override
- public void print(float f) {}
- @Override
- public void print(double d) {}
- @Override
- public void print(char[] s) {}
- @Override
- public void print(String s) {}
- @Override
- public void print(Object obj) {}
- @Override
- public void println() {}
- @Override
- public void println(boolean x) {}
- @Override
- public void println(char x) {}
- @Override
- public void println(int x) {}
- @Override
- public void println(long x) {}
- @Override
- public void println(float x) {}
- @Override
- public void println(double x) {}
- @Override
- public void println(char[] x) {}
- @Override
- public void println(String x) {}
- @Override
- public void println(Object x) {}
- @Override
- public PrintStream printf(String format, Object... args) { return this; }
- @Override
- public PrintStream printf(Locale l, String format, Object... args) { return this; }
- @Override
- public PrintStream format(String format, Object... args) { return this; }
- @Override
- public PrintStream format(Locale l, String format, Object... args) { return this; }
- @Override
- public PrintStream append(CharSequence csq) { return this; }
- @Override
- public PrintStream append(CharSequence csq, int start, int end) { return this; }
- @Override
- public PrintStream append(char c) { return this; }
- @Override
- public void write(byte[] b) {}
- }
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java
index 9e592df284..efabb8c00e 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java
@@ -417,10 +417,8 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
private static void saveTwice(Workbook wb) throws Exception {
for (int i = 0; i < 2; i++) {
- try {
- NullOutputStream out = new NullOutputStream();
+ try (NullOutputStream out = new NullOutputStream()) {
wb.write(out);
- out.close();
} catch (Exception e) {
throw new Exception("ERROR: failed on " + (i + 1)
+ "th time calling " + wb.getClass().getName()
diff --git a/src/resources/devtools/forbidden-signatures-prod.txt b/src/resources/devtools/forbidden-signatures-prod.txt
index 59dcf47890..fa1a846088 100644
--- a/src/resources/devtools/forbidden-signatures-prod.txt
+++ b/src/resources/devtools/forbidden-signatures-prod.txt
@@ -17,7 +17,7 @@
# This file contains API signatures which are specific to POI.
# The goal is to minimize implicit defaults
-@defaultMessage POI forbidden APIs which are tolerated in non-production code, e.g. in tests and examples
+@defaultMessage POI forbidden APIs which are not tolerated in production code
# We have applications which use this to return error codes on invalid commandline parameters...
#@defaultMessage Please do not terminate the application
diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java b/src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java
index 95a7d91460..2ef26a66b7 100644
--- a/src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java
+++ b/src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java
@@ -24,7 +24,7 @@ import java.io.File;
import java.io.PrintStream;
import org.apache.poi.POIDataSamples;
-import org.apache.poi.util.NullOutputStream;
+import org.apache.poi.util.NullPrintStream;
import org.junit.Test;
public class TestHMEFDumper {
@@ -48,7 +48,7 @@ public class TestHMEFDumper {
private static void doMain(String... args) throws Exception {
PrintStream ps = System.out;
try {
- System.setOut(new PrintStream(new NullOutputStream(), true, "UTF-8"));
+ System.setOut(new NullPrintStream());
HMEFDumper.main(args);
} finally {
System.setOut(ps);
diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java b/src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java
index 5212221e48..681cd46708 100644
--- a/src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java
+++ b/src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java
@@ -16,22 +16,9 @@
==================================================================== */
package org.apache.poi.hslf.dev;
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException;
-import org.apache.poi.hslf.exceptions.OldPowerPointFormatException;
-import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.LocaleUtil;
-import org.apache.poi.util.NullOutputStream;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import static org.junit.Assert.assertNotNull;
import java.io.File;
-import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
@@ -42,12 +29,21 @@ import java.util.Locale;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertNotNull;
+import org.apache.poi.POIDataSamples;
+import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException;
+import org.apache.poi.hslf.exceptions.OldPowerPointFormatException;
+import org.apache.poi.util.IOUtils;
+import org.apache.poi.util.NullPrintStream;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public abstract class BasePPTIteratingTest {
- protected static final OutputStream NULL_OUTPUT_STREAM = new NullOutputStream();
-
protected static final Set<String> OLD_FILES = new HashSet<>();
static {
OLD_FILES.add("PPT95.ppt");
@@ -89,7 +85,7 @@ public abstract class BasePPTIteratingTest {
IOUtils.setByteArrayMaxOverride(5*1024*1024);
// redirect standard out during the test to avoid spamming the console with output
- System.setOut(new PrintStream(NULL_OUTPUT_STREAM, true, LocaleUtil.CHARSET_1252.name()));
+ System.setOut(new NullPrintStream());
}
@After
diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java
index e23f158703..32ae5077de 100644
--- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java
+++ b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java
@@ -35,16 +35,17 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintStream;
import java.text.AttributedCharacterIterator;
import java.text.AttributedCharacterIterator.Attribute;
import java.text.CharacterIterator;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
@@ -59,7 +60,6 @@ import org.apache.poi.hslf.exceptions.OldPowerPointFormatException;
import org.apache.poi.hslf.model.HeadersFooters;
import org.apache.poi.hslf.record.DocInfoListContainer;
import org.apache.poi.hslf.record.Document;
-import org.apache.poi.hslf.record.Record;
import org.apache.poi.hslf.record.RecordTypes;
import org.apache.poi.hslf.record.SlideListWithText;
import org.apache.poi.hslf.record.SlideListWithText.SlideAtomsSet;
@@ -88,6 +88,7 @@ import org.apache.poi.sl.usermodel.TextParagraph.TextAlign;
import org.apache.poi.sl.usermodel.TextRun;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndian;
+import org.apache.poi.util.NullPrintStream;
import org.apache.poi.util.StringUtil;
import org.apache.poi.util.Units;
import org.junit.Test;
@@ -291,7 +292,7 @@ public final class TestBugs {
}
}
}
-
+
ppt.close();
}
@@ -375,7 +376,7 @@ public final class TestBugs {
HSLFPictureData pict = f.getPictureData();
assertNotNull(pict);
assertEquals(PictureType.JPEG, pict.getType());
-
+
ppt.close();
}
@@ -405,7 +406,7 @@ public final class TestBugs {
List<List<HSLFTextParagraph>> run = slide.getTextParagraphs();
assertEquals(3, run.size());
assertEquals("Fundera, planera och involvera.", HSLFTextParagraph.getRawText(run.get(2)));
-
+
ppt.close();
}
@@ -445,7 +446,7 @@ public final class TestBugs {
HSLFSlideShow ppt = open("41246-1.ppt");
HSLFTestDataSamples.writeOutAndReadBack(ppt).close();
-
+
ppt.close();
}
@@ -454,7 +455,7 @@ public final class TestBugs {
HSLFSlideShow ppt = open("41246-2.ppt");
HSLFTestDataSamples.writeOutAndReadBack(ppt).close();
-
+
ppt.close();
}
@@ -463,31 +464,32 @@ public final class TestBugs {
*/
@Test
public void bug45776() throws IOException {
- HSLFSlideShow ppt = open("45776.ppt");
+ DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
+ try (HSLFSlideShow ppt = open("45776.ppt")) {
+
+ // get slides
+ for (HSLFSlide slide : ppt.getSlides()) {
+ for (HSLFShape shape : slide.getShapes()) {
+ if (!(shape instanceof HSLFTextBox)) {
+ continue;
+ }
+ HSLFTextBox tb = (HSLFTextBox) shape;
+ // work with TextBox
+ String str = tb.getText();
- // get slides
- for (HSLFSlide slide : ppt.getSlides()) {
- for (HSLFShape shape : slide.getShapes()) {
- if (!(shape instanceof HSLFTextBox)) {
- continue;
- }
- HSLFTextBox tb = (HSLFTextBox) shape;
- // work with TextBox
- String str = tb.getText();
+ if (!str.contains("$$DATE$$")) {
+ continue;
+ }
+ str = str.replace("$$DATE$$", df.format(new Date()));
+ tb.setText(str);
- if (!str.contains("$$DATE$$")) {
- continue;
+ List<HSLFTextParagraph> tr = tb.getTextParagraphs();
+ assertEquals(str.length() + 1, tr.get(0).getParagraphStyle().getCharactersCovered());
+ assertEquals(str.length() + 1, tr.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered());
}
- str = str.replace("$$DATE$$", new Date().toString());
- tb.setText(str);
-
- List<HSLFTextParagraph> tr = tb.getTextParagraphs();
- assertEquals(str.length()+1,tr.get(0).getParagraphStyle().getCharactersCovered());
- assertEquals(str.length()+1,tr.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered());
}
+
}
-
- ppt.close();
}
@Test
@@ -501,7 +503,7 @@ public final class TestBugs {
HeadersFooters hf = slide.getHeadersFooters();
/*boolean visible =*/ hf.isHeaderVisible(); // exception happens here
}
-
+
ppt.close();
}
@@ -538,7 +540,7 @@ public final class TestBugs {
}
}
assertEquals(2, str);
-
+
ppt.close();
}
@@ -781,7 +783,7 @@ public final class TestBugs {
HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1);
ppt1.close();
-
+
HSLFTextShape ts = (HSLFTextShape)ppt2.getSlides().get(0).getShapes().get(0);
tp = ts.getTextParagraphs().get(0);
tr = tp.getTextRuns().get(0);
@@ -841,9 +843,9 @@ public final class TestBugs {
@Test
public void bug55030() throws IOException {
HSLFSlideShow ppt = open("bug55030.ppt");
-
+
String expFamily = "\u96b6\u4e66";
-
+
HSLFSlide sl = ppt.getSlides().get(0);
for (List<HSLFTextParagraph> paraList : sl.getTextParagraphs()) {
for (HSLFTextParagraph htp : paraList) {
@@ -853,7 +855,7 @@ public final class TestBugs {
}
}
}
-
+
ppt.close();
}
@@ -873,27 +875,22 @@ public final class TestBugs {
assertEquals(hlRun.getStartIndex(), hlShape.getStartIndex());
assertEquals(hlRun.getEndIndex(), hlShape.getEndIndex());
- OutputStream nullOutput = new OutputStream(){
- @Override
- public void write(int b) throws IOException {}
- };
-
final boolean[] found = {false};
- DummyGraphics2d dgfx = new DummyGraphics2d(new PrintStream(nullOutput)){
+ DummyGraphics2d dgfx = new DummyGraphics2d(new NullPrintStream()){
@Override
public void drawString(AttributedCharacterIterator iterator, float x, float y) {
// For the test file, common sl draws textruns one by one and not mixed
// so we evaluate the whole iterator
Map<Attribute, Object> attributes = null;
StringBuilder sb = new StringBuilder();
-
+
for (char c = iterator.first();
c != CharacterIterator.DONE;
c = iterator.next()) {
sb.append(c);
attributes = iterator.getAttributes();
}
-
+
if ("Jakarta HSSF".equals(sb.toString())) {
// this is a test for a manually modified ppt, for real hyperlink label
// one would need to access the screen tip record
@@ -905,17 +902,17 @@ public final class TestBugs {
}
}
};
-
+
ppt.getSlides().get(1).draw(dgfx);
assertTrue(found[0]);
-
+
ppt.close();
}
@Test
public void bug59056() throws IOException {
HSLFSlideShow ppt = open("54541_cropped_bitmap.ppt");
-
+
for (HSLFShape shape : ppt.getSlides().get(0).getShapes()) {
BufferedImage img = new BufferedImage(500, 300, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = img.createGraphics();
@@ -927,11 +924,11 @@ public final class TestBugs {
graphics.dispose();
// ImageIO.write(img, "png", new File("bla"+shape.getShapeId()+".png"));
}
-
+
ppt.close();
-
+
}
-
+
private static HSLFSlideShow open(String fileName) throws IOException {
File sample = HSLFTestDataSamples.getSampleFile(fileName);
// Note: don't change the code here, it is required for Eclipse to compile the code
@@ -950,10 +947,10 @@ public final class TestBugs {
fs.setPath(new Path2D.Double(el));
Color cExp = new Color(50,100,150,200);
fs.setFillColor(cExp);
-
+
HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1);
ppt1.close();
-
+
sl = ppt2.getSlides().get(0);
fs = (HSLFFreeformShape)sl.getShapes().get(0);
Color cAct = fs.getFillColor();
@@ -961,7 +958,7 @@ public final class TestBugs {
assertEquals(cExp.getGreen(), cAct.getGreen());
assertEquals(cExp.getBlue(), cAct.getBlue());
assertEquals(cExp.getAlpha(), cAct.getAlpha(), 1);
-
+
PaintStyle ps = fs.getFillStyle().getPaint();
assertTrue(ps instanceof SolidPaint);
ColorStyle cs = ((SolidPaint)ps).getSolidColor();
@@ -971,7 +968,7 @@ public final class TestBugs {
assertEquals(cExp.getBlue(), cAct.getBlue());
assertEquals(255, cAct.getAlpha());
assertEquals(cExp.getAlpha()*100000./255., cs.getAlpha(), 1);
-
+
ppt2.close();
}
@@ -1016,7 +1013,7 @@ public final class TestBugs {
}
}
}
-
+
ppt.close();
} finally {
diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java
index 5d6e2f51b6..d44145aedc 100644
--- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java
+++ b/src/scratchpad/testcases/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java
@@ -44,6 +44,7 @@ import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.EntryUtils;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
+import org.apache.poi.util.LocaleUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -53,7 +54,7 @@ public class TestExtractEmbeddedMSG {
/**
* Initialize this test, load up the attachment_msg_pdf.msg mapi message.
- *
+ *
* @throws Exception
*/
@BeforeClass
@@ -70,9 +71,9 @@ public class TestExtractEmbeddedMSG {
/**
* Test to see if embedded message properties can be read, extracted, and
* re-parsed
- *
+ *
* @throws ChunkNotFoundException
- *
+ *
*/
@Test
public void testEmbeddedMSGProperties() throws IOException, ChunkNotFoundException {
@@ -102,7 +103,7 @@ public class TestExtractEmbeddedMSG {
msg.setReturnNullOnMissingChunk(true);
Calendar messageDate = msg.getMessageDate();
assertNotNull(messageDate);
- Calendar expectedMessageDate = Calendar.getInstance();
+ Calendar expectedMessageDate = LocaleUtil.getLocaleCalendar();
expectedMessageDate.set(2010, 05, 17, 23, 52, 19); // 2010/06/17 23:52:19 GMT
expectedMessageDate.setTimeZone(TimeZone.getTimeZone("GMT"));
expectedMessageDate.set(Calendar.MILLISECOND, 0);
diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java
index 007fff036a..c559407a1a 100644
--- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java
+++ b/src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java
@@ -168,7 +168,7 @@ public final class TestFixedSizedProperties {
*/
@Test
public void testReadMessageDateSucceedsWithHSMFDump() throws IOException {
- PrintStream stream = new PrintStream(new ByteArrayOutputStream());
+ PrintStream stream = new PrintStream(new ByteArrayOutputStream(), true, "ISO-8859-1");
HSMFDump dump = new HSMFDump(fsMessageSucceeds);
dump.dump(stream);
}
@@ -178,7 +178,7 @@ public final class TestFixedSizedProperties {
*/
@Test
public void testReadMessageDateFailsWithHSMFDump() throws Exception {
- PrintStream stream = new PrintStream(new ByteArrayOutputStream());
+ PrintStream stream = new PrintStream(new ByteArrayOutputStream(), true, "ISO-8859-1");
HSMFDump dump = new HSMFDump(fsMessageFails);
dump.dump(stream);
}
diff --git a/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java b/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java
index a8b30a001c..262aafdb3b 100644
--- a/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java
+++ b/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java
@@ -20,7 +20,6 @@ import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.FileInputStream;
-import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -29,7 +28,6 @@ import java.util.Map;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.util.NullOutputStream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -46,8 +44,6 @@ import org.junit.runners.Parameterized.Parameters;
*/
@RunWith(Parameterized.class)
public abstract class BaseTestIteratingXLS {
- protected static final OutputStream NULL_OUTPUT_STREAM = new NullOutputStream();
-
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -74,9 +70,9 @@ public abstract class BaseTestIteratingXLS {
assertNotNull("Did not find any xls files in directory " + dir, files);
for(String file : files) {
- list.add(new Object[] { new File(dir, file) });
+ list.add(new Object[]{new File(dir, file)});
+ }
}
- }
@Parameter
public File file;
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java
index 12d7c6fbaf..406266d902 100644
--- a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java
+++ b/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java
@@ -23,6 +23,7 @@ import java.io.InputStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.OldExcelFormatException;
import org.apache.poi.hssf.record.RecordInputStream;
+import org.apache.poi.util.NullOutputStream;
import org.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass;
@@ -30,10 +31,10 @@ public class TestBiffDrawingToXml extends BaseTestIteratingXLS {
@BeforeClass
public static void setup() {
EXCLUDED.clear();
- EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
+ EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
EXCLUDED.put("51832.xls", EncryptedDocumentException.class);
- EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
- EXCLUDED.put("password.xls", EncryptedDocumentException.class);
+ EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
+ EXCLUDED.put("password.xls", EncryptedDocumentException.class);
EXCLUDED.put("46904.xls", OldExcelFormatException.class);
EXCLUDED.put("59074.xls", OldExcelFormatException.class);
EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2
@@ -47,11 +48,11 @@ public class TestBiffDrawingToXml extends BaseTestIteratingXLS {
EXCLUDED.put("61300.xls", RecordFormatException.class);
EXCLUDED.put("64130.xls", OldExcelFormatException.class); // BIFF 5
}
-
+
@Override
void runOneFile(File pFile) throws Exception {
try (InputStream wb = new FileInputStream(pFile)) {
- BiffDrawingToXml.writeToFile(NULL_OUTPUT_STREAM, wb, false, new String[0]);
+ BiffDrawingToXml.writeToFile(new NullOutputStream(), wb, false, new String[0]);
}
}
}
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java
index d4fd62fa99..75adb444a4 100644
--- a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java
+++ b/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java
@@ -28,6 +28,7 @@ import org.apache.poi.hssf.OldExcelFormatException;
import org.apache.poi.hssf.record.RecordInputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.LocaleUtil;
+import org.apache.poi.util.NullOutputStream;
import org.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass;
import org.junit.Ignore;
@@ -62,7 +63,7 @@ public class TestBiffViewer extends BaseTestIteratingXLS {
try (POIFSFileSystem fs = new POIFSFileSystem(fileIn, true);
InputStream is = BiffViewer.getPOIFSInputStream(fs)) {
// use a NullOutputStream to not write the bytes anywhere for best runtime
- PrintWriter dummy = new PrintWriter(new OutputStreamWriter(NULL_OUTPUT_STREAM, LocaleUtil.CHARSET_1252));
+ PrintWriter dummy = new PrintWriter(new OutputStreamWriter(new NullOutputStream(), LocaleUtil.CHARSET_1252));
BiffViewer.runBiffViewer(dummy, is, true, true, true, false);
}
}
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java
index d32e0b71eb..20a7a635c9 100644
--- a/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java
+++ b/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java
@@ -23,7 +23,7 @@ import java.io.PrintStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.OldExcelFormatException;
import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.util.LocaleUtil;
+import org.apache.poi.util.NullPrintStream;
import org.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass;
@@ -31,10 +31,10 @@ public class TestEFBiffViewer extends BaseTestIteratingXLS {
@BeforeClass
public static void setup() {
EXCLUDED.clear();
- EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
+ EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
EXCLUDED.put("51832.xls", EncryptedDocumentException.class);
- EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
- EXCLUDED.put("password.xls", EncryptedDocumentException.class);
+ EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
+ EXCLUDED.put("password.xls", EncryptedDocumentException.class);
EXCLUDED.put("46904.xls", OldExcelFormatException.class);
EXCLUDED.put("59074.xls", OldExcelFormatException.class);
EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2
@@ -45,17 +45,17 @@ public class TestEFBiffViewer extends BaseTestIteratingXLS {
EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95
EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well
EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class);
- EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun"
+ // EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun"
EXCLUDED.put("61300.xls", RecordFormatException.class);
EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5
}
-
+
@Override
void runOneFile(File fileIn) throws IOException {
PrintStream save = System.out;
try {
// redirect standard out during the test to avoid spamming the console with output
- System.setOut(new PrintStream(NULL_OUTPUT_STREAM,true,LocaleUtil.CHARSET_1252.name()));
+ System.setOut(new NullPrintStream());
EFBiffViewer.main(new String[] { fileIn.getAbsolutePath() });
} finally {
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java
index b922230994..a3eae963c8 100644
--- a/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java
+++ b/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java
@@ -24,7 +24,7 @@ import java.io.PrintStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.OldExcelFormatException;
import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.util.LocaleUtil;
+import org.apache.poi.util.NullPrintStream;
import org.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass;
@@ -32,10 +32,10 @@ public class TestFormulaViewer extends BaseTestIteratingXLS {
@BeforeClass
public static void setup() {
EXCLUDED.clear();
- EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
+ EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
EXCLUDED.put("51832.xls", EncryptedDocumentException.class);
- EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
- EXCLUDED.put("password.xls", EncryptedDocumentException.class);
+ EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
+ EXCLUDED.put("password.xls", EncryptedDocumentException.class);
EXCLUDED.put("46904.xls", OldExcelFormatException.class);
EXCLUDED.put("59074.xls", OldExcelFormatException.class);
EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2
@@ -49,13 +49,13 @@ public class TestFormulaViewer extends BaseTestIteratingXLS {
EXCLUDED.put("61300.xls", RecordFormatException.class);
EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5
}
-
+
@Override
void runOneFile(File fileIn) throws Exception {
PrintStream save = System.out;
try {
// redirect standard out during the test to avoid spamming the console with output
- System.setOut(new PrintStream(NULL_OUTPUT_STREAM,true,LocaleUtil.CHARSET_1252.name()));
+ System.setOut(new NullPrintStream());
FormulaViewer viewer = new FormulaViewer();
viewer.setFile(fileIn.getAbsolutePath());
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestReSave.java b/src/testcases/org/apache/poi/hssf/dev/TestReSave.java
index 890ef1e837..8ab108378f 100644
--- a/src/testcases/org/apache/poi/hssf/dev/TestReSave.java
+++ b/src/testcases/org/apache/poi/hssf/dev/TestReSave.java
@@ -25,7 +25,7 @@ import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.OldExcelFormatException;
import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.util.LocaleUtil;
+import org.apache.poi.util.NullPrintStream;
import org.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass;
import org.junit.Ignore;
@@ -35,10 +35,10 @@ public class TestReSave extends BaseTestIteratingXLS {
@BeforeClass
public static void setup() {
EXCLUDED.clear();
- EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
+ EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
EXCLUDED.put("51832.xls", EncryptedDocumentException.class);
- EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
- EXCLUDED.put("password.xls", EncryptedDocumentException.class);
+ EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
+ EXCLUDED.put("password.xls", EncryptedDocumentException.class);
EXCLUDED.put("46904.xls", OldExcelFormatException.class);
EXCLUDED.put("59074.xls", OldExcelFormatException.class);
EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2
@@ -64,12 +64,12 @@ public class TestReSave extends BaseTestIteratingXLS {
PrintStream save = System.out;
try {
// redirect standard out during the test to avoid spamming the console with output
- System.setOut(new PrintStream(NULL_OUTPUT_STREAM,true,LocaleUtil.CHARSET_1252.name()));
+ System.setOut(new NullPrintStream());
File reSavedFile = new File(fileIn.getParentFile(), fileIn.getName().replace(".xls", "-saved.xls"));
try {
ReSave.main(new String[] { fileIn.getAbsolutePath() });
-
+
// also try BiffViewer on the saved file
new TestBiffViewer().runOneFile(reSavedFile);
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java b/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java
index 934eb5b89d..3a1b9bb2fe 100644
--- a/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java
+++ b/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java
@@ -21,7 +21,7 @@ import java.io.IOException;
import java.io.PrintStream;
import org.apache.poi.hssf.OldExcelFormatException;
-import org.apache.poi.util.LocaleUtil;
+import org.apache.poi.util.NullPrintStream;
import org.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass;
@@ -46,7 +46,7 @@ public class TestRecordLister extends BaseTestIteratingXLS {
PrintStream save = System.out;
try {
// redirect standard out during the test to avoid spamming the console with output
- System.setOut(new PrintStream(NULL_OUTPUT_STREAM,true,LocaleUtil.CHARSET_1252.name()));
+ System.setOut(new NullPrintStream());
RecordLister viewer = new RecordLister();
viewer.setFile(fileIn.getAbsolutePath());
diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java
index 6ab7dd52d1..d040cf216f 100644
--- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java
+++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java
@@ -26,8 +26,6 @@ import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ConcurrentModificationException;
@@ -39,8 +37,9 @@ import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.NullOutputStream;
-import org.apache.poi.util.TempFile;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.ExpectedException;
public abstract class BaseTestWorkbook {
@@ -49,21 +48,25 @@ public abstract class BaseTestWorkbook {
protected BaseTestWorkbook(ITestDataProvider testDataProvider) {
_testDataProvider = testDataProvider;
}
-
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+
@Test
public void sheetIterator_forEach() throws IOException {
- final Workbook wb = _testDataProvider.createWorkbook();
- wb.createSheet("Sheet0");
- wb.createSheet("Sheet1");
- wb.createSheet("Sheet2");
- int i = 0;
- for (Sheet sh : wb) {
- assertEquals("Sheet"+i, sh.getSheetName());
- i++;
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
+ wb.createSheet("Sheet0");
+ wb.createSheet("Sheet1");
+ wb.createSheet("Sheet2");
+ int i = 0;
+ for (Sheet sh : wb) {
+ assertEquals("Sheet" + i, sh.getSheetName());
+ i++;
+ }
}
- wb.close();
}
-
+
/**
* Expected ConcurrentModificationException:
* should not be able to advance an iterator when the
@@ -71,23 +74,20 @@ public abstract class BaseTestWorkbook {
*/
@Test(expected=ConcurrentModificationException.class)
public void sheetIterator_sheetsReordered() throws IOException {
- final Workbook wb = _testDataProvider.createWorkbook();
- wb.createSheet("Sheet0");
- wb.createSheet("Sheet1");
- wb.createSheet("Sheet2");
-
- Iterator<Sheet> it = wb.sheetIterator();
- it.next();
- wb.setSheetOrder("Sheet2", 1);
-
- // Iterator order should be fixed when iterator is created
- try {
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
+ wb.createSheet("Sheet0");
+ wb.createSheet("Sheet1");
+ wb.createSheet("Sheet2");
+
+ Iterator<Sheet> it = wb.sheetIterator();
+ it.next();
+ wb.setSheetOrder("Sheet2", 1);
+
+ // Iterator order should be fixed when iterator is created
assertEquals("Sheet1", it.next().getSheetName());
- } finally {
- wb.close();
}
}
-
+
/**
* Expected ConcurrentModificationException:
* should not be able to advance an iterator when the
@@ -95,140 +95,134 @@ public abstract class BaseTestWorkbook {
*/
@Test(expected=ConcurrentModificationException.class)
public void sheetIterator_sheetRemoved() throws IOException {
- final Workbook wb = _testDataProvider.createWorkbook();
- wb.createSheet("Sheet0");
- wb.createSheet("Sheet1");
- wb.createSheet("Sheet2");
-
- Iterator<Sheet> it = wb.sheetIterator();
- wb.removeSheetAt(1);
-
- // Iterator order should be fixed when iterator is created
- try {
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
+ wb.createSheet("Sheet0");
+ wb.createSheet("Sheet1");
+ wb.createSheet("Sheet2");
+
+ Iterator<Sheet> it = wb.sheetIterator();
+ wb.removeSheetAt(1);
+
+ // Iterator order should be fixed when iterator is created
it.next();
- } finally {
- wb.close();
}
}
-
+
/**
* Expected UnsupportedOperationException:
* should not be able to remove sheets from the sheet iterator
*/
@Test(expected=UnsupportedOperationException.class)
public void sheetIterator_remove() throws IOException {
- final Workbook wb = _testDataProvider.createWorkbook();
- wb.createSheet("Sheet0");
-
- Iterator<Sheet> it = wb.sheetIterator();
- it.next(); //Sheet0
- try {
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
+ wb.createSheet("Sheet0");
+
+ Iterator<Sheet> it = wb.sheetIterator();
+ it.next(); //Sheet0
it.remove();
- } finally {
- wb.close();
}
}
@Test
public void createSheet() throws IOException {
- Workbook wb = _testDataProvider.createWorkbook();
- assertEquals(0, wb.getNumberOfSheets());
-
- //getting a sheet by invalid index or non-existing name
- assertNull(wb.getSheet("Sheet1"));
- try {
- wb.getSheetAt(0);
- fail("should have thrown exceptiuon due to invalid sheet index");
- } catch (IllegalArgumentException e) {
- // expected during successful test
- // no negative index in the range message
- assertFalse(e.getMessage().contains("-1"));
- }
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
+ assertEquals(0, wb.getNumberOfSheets());
- Sheet sheet0 = wb.createSheet();
- Sheet sheet1 = wb.createSheet();
- assertEquals("Sheet0", sheet0.getSheetName());
- assertEquals("Sheet1", sheet1.getSheetName());
- assertEquals(2, wb.getNumberOfSheets());
-
- //fetching sheets by name is case-insensitive
- Sheet originalSheet = wb.createSheet("Sheet3");
- Sheet fetchedSheet = wb.getSheet("sheet3");
- if (fetchedSheet == null) {
- fail("Identified bug 44892");
- }
- assertEquals("Sheet3", fetchedSheet.getSheetName());
- assertEquals(3, wb.getNumberOfSheets());
- assertSame(originalSheet, fetchedSheet);
- try {
- wb.createSheet("sHeeT3");
- fail("should have thrown exceptiuon due to duplicate sheet name");
- } catch (IllegalArgumentException e) {
- // expected during successful test
- assertEquals("The workbook already contains a sheet named 'sHeeT3'", e.getMessage());
- }
+ //getting a sheet by invalid index or non-existing name
+ assertNull(wb.getSheet("Sheet1"));
+ try {
+ wb.getSheetAt(0);
+ fail("should have thrown exceptiuon due to invalid sheet index");
+ } catch (IllegalArgumentException e) {
+ // expected during successful test
+ // no negative index in the range message
+ assertFalse(e.getMessage().contains("-1"));
+ }
- //names cannot be blank or contain any of /\*?[]
- String[] invalidNames = {"", "Sheet/", "Sheet\\",
- "Sheet?", "Sheet*", "Sheet[", "Sheet]", "'Sheet'",
- "My:Sheet"};
- for (String sheetName : invalidNames) {
+ Sheet sheet0 = wb.createSheet();
+ Sheet sheet1 = wb.createSheet();
+ assertEquals("Sheet0", sheet0.getSheetName());
+ assertEquals("Sheet1", sheet1.getSheetName());
+ assertEquals(2, wb.getNumberOfSheets());
+
+ //fetching sheets by name is case-insensitive
+ Sheet originalSheet = wb.createSheet("Sheet3");
+ Sheet fetchedSheet = wb.getSheet("sheet3");
+ if (fetchedSheet == null) {
+ fail("Identified bug 44892");
+ }
+ assertEquals("Sheet3", fetchedSheet.getSheetName());
+ assertEquals(3, wb.getNumberOfSheets());
+ assertSame(originalSheet, fetchedSheet);
try {
- wb.createSheet(sheetName);
- fail("should have thrown exception due to invalid sheet name: " + sheetName);
+ wb.createSheet("sHeeT3");
+ fail("should have thrown exceptiuon due to duplicate sheet name");
} catch (IllegalArgumentException e) {
// expected during successful test
+ assertEquals("The workbook already contains a sheet named 'sHeeT3'", e.getMessage());
}
- }
- //still have 3 sheets
- assertEquals(3, wb.getNumberOfSheets());
-
- //change the name of the 3rd sheet
- wb.setSheetName(2, "I changed!");
-
- //try to assign an invalid name to the 2nd sheet
- try {
- wb.setSheetName(1, "[I'm invalid]");
- fail("should have thrown exceptiuon due to invalid sheet name");
- } catch (IllegalArgumentException e) {
- // expected during successful test
- }
- //try to assign an invalid name to the 2nd sheet
- try {
- wb.createSheet(null);
- fail("should have thrown exceptiuon due to invalid sheet name");
- } catch (IllegalArgumentException e) {
- // expected during successful test
- }
+ //names cannot be blank or contain any of /\*?[]
+ String[] invalidNames = {"", "Sheet/", "Sheet\\",
+ "Sheet?", "Sheet*", "Sheet[", "Sheet]", "'Sheet'",
+ "My:Sheet"};
+ for (String sheetName : invalidNames) {
+ try {
+ wb.createSheet(sheetName);
+ fail("should have thrown exception due to invalid sheet name: " + sheetName);
+ } catch (IllegalArgumentException e) {
+ // expected during successful test
+ }
+ }
+ //still have 3 sheets
+ assertEquals(3, wb.getNumberOfSheets());
- try {
- wb.setSheetName(2, null);
+ //change the name of the 3rd sheet
+ wb.setSheetName(2, "I changed!");
- fail("should have thrown exceptiuon due to invalid sheet name");
- } catch (IllegalArgumentException e) {
- // expected during successful test
- }
+ //try to assign an invalid name to the 2nd sheet
+ try {
+ wb.setSheetName(1, "[I'm invalid]");
+ fail("should have thrown exceptiuon due to invalid sheet name");
+ } catch (IllegalArgumentException e) {
+ // expected during successful test
+ }
+
+ //try to assign an invalid name to the 2nd sheet
+ try {
+ wb.createSheet(null);
+ fail("should have thrown exceptiuon due to invalid sheet name");
+ } catch (IllegalArgumentException e) {
+ // expected during successful test
+ }
- //check
- assertEquals(0, wb.getSheetIndex("sheet0"));
- assertEquals(1, wb.getSheetIndex("sheet1"));
- assertEquals(2, wb.getSheetIndex("I changed!"));
+ try {
+ wb.setSheetName(2, null);
- assertSame(sheet0, wb.getSheet("sheet0"));
- assertSame(sheet1, wb.getSheet("sheet1"));
- assertSame(originalSheet, wb.getSheet("I changed!"));
- assertNull(wb.getSheet("unknown"));
+ fail("should have thrown exceptiuon due to invalid sheet name");
+ } catch (IllegalArgumentException e) {
+ // expected during successful test
+ }
- //serialize and read again
- Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb);
- wb.close();
- assertEquals(3, wb2.getNumberOfSheets());
- assertEquals(0, wb2.getSheetIndex("sheet0"));
- assertEquals(1, wb2.getSheetIndex("sheet1"));
- assertEquals(2, wb2.getSheetIndex("I changed!"));
- wb2.close();
+ //check
+ assertEquals(0, wb.getSheetIndex("sheet0"));
+ assertEquals(1, wb.getSheetIndex("sheet1"));
+ assertEquals(2, wb.getSheetIndex("I changed!"));
+
+ assertSame(sheet0, wb.getSheet("sheet0"));
+ assertSame(sheet1, wb.getSheet("sheet1"));
+ assertSame(originalSheet, wb.getSheet("I changed!"));
+ assertNull(wb.getSheet("unknown"));
+
+ //serialize and read again
+ try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb)) {
+ assertEquals(3, wb2.getNumberOfSheets());
+ assertEquals(0, wb2.getSheetIndex("sheet0"));
+ assertEquals(1, wb2.getSheetIndex("sheet1"));
+ assertEquals(2, wb2.getSheetIndex("I changed!"));
+ }
+ }
}
/**
@@ -241,41 +235,42 @@ public abstract class BaseTestWorkbook {
*/
@Test
public void createSheetWithLongNames() throws IOException {
- Workbook wb1 = _testDataProvider.createWorkbook();
-
- String sheetName1 = "My very long sheet name which is longer than 31 chars";
- String truncatedSheetName1 = sheetName1.substring(0, 31);
- Sheet sh1 = wb1.createSheet(sheetName1);
- assertEquals(truncatedSheetName1, sh1.getSheetName());
- assertSame(sh1, wb1.getSheet(truncatedSheetName1));
- // now via wb.setSheetName
- wb1.setSheetName(0, sheetName1);
- assertEquals(truncatedSheetName1, sh1.getSheetName());
- assertSame(sh1, wb1.getSheet(truncatedSheetName1));
-
- String sheetName2 = "My very long sheet name which is longer than 31 chars " +
- "and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)";
- try {
- /*Sheet sh2 =*/ wb1.createSheet(sheetName2);
- fail("expected exception");
- } catch (IllegalArgumentException e) {
- // expected during successful test
- assertEquals("The workbook already contains a sheet named 'My very long sheet name which is longer than 31 chars and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)'", e.getMessage());
- }
+ try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+
+ String sheetName1 = "My very long sheet name which is longer than 31 chars";
+ String truncatedSheetName1 = sheetName1.substring(0, 31);
+ Sheet sh1 = wb1.createSheet(sheetName1);
+ assertEquals(truncatedSheetName1, sh1.getSheetName());
+ assertSame(sh1, wb1.getSheet(truncatedSheetName1));
+ // now via wb.setSheetName
+ wb1.setSheetName(0, sheetName1);
+ assertEquals(truncatedSheetName1, sh1.getSheetName());
+ assertSame(sh1, wb1.getSheet(truncatedSheetName1));
+
+ String sheetName2 = "My very long sheet name which is longer than 31 chars " +
+ "and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)";
+ try {
+ /*Sheet sh2 =*/
+ wb1.createSheet(sheetName2);
+ fail("expected exception");
+ } catch (IllegalArgumentException e) {
+ // expected during successful test
+ assertEquals("The workbook already contains a sheet named 'My very long sheet name which is longer than 31 chars and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)'", e.getMessage());
+ }
- String sheetName3 = "POI allows creating sheets with names longer than 31 characters";
- String truncatedSheetName3 = sheetName3.substring(0, 31);
- Sheet sh3 = wb1.createSheet(sheetName3);
- assertEquals(truncatedSheetName3, sh3.getSheetName());
- assertSame(sh3, wb1.getSheet(truncatedSheetName3));
-
- //serialize and read again
- Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
- wb1.close();
- assertEquals(2, wb2.getNumberOfSheets());
- assertEquals(0, wb2.getSheetIndex(truncatedSheetName1));
- assertEquals(1, wb2.getSheetIndex(truncatedSheetName3));
- wb2.close();
+ String sheetName3 = "POI allows creating sheets with names longer than 31 characters";
+ String truncatedSheetName3 = sheetName3.substring(0, 31);
+ Sheet sh3 = wb1.createSheet(sheetName3);
+ assertEquals(truncatedSheetName3, sh3.getSheetName());
+ assertSame(sh3, wb1.getSheet(truncatedSheetName3));
+
+ //serialize and read again
+ try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+ assertEquals(2, wb2.getNumberOfSheets());
+ assertEquals(0, wb2.getSheetIndex(truncatedSheetName1));
+ assertEquals(1, wb2.getSheetIndex(truncatedSheetName3));
+ }
+ }
}
@Test
@@ -339,225 +334,222 @@ public abstract class BaseTestWorkbook {
Workbook wbr = _testDataProvider.writeOutAndReadBack(wb);
sheet = wbr.getSheet("new sheet");
assertEquals(new CellAddress("E11"), sheet.getActiveCell());
-
- //wbr.write(new FileOutputStream("c:/temp/yyy." + _testDataProvider.getStandardFileNameExtension()));
}
}
@Test
public void defaultValues() throws IOException {
- Workbook b = _testDataProvider.createWorkbook();
- assertEquals(0, b.getActiveSheetIndex());
- assertEquals(0, b.getFirstVisibleTab());
- assertEquals(0, b.getNumberOfNames());
- assertEquals(0, b.getNumberOfSheets());
- b.close();
+ try (Workbook b = _testDataProvider.createWorkbook()) {
+ assertEquals(0, b.getActiveSheetIndex());
+ assertEquals(0, b.getFirstVisibleTab());
+ assertEquals(0, b.getNumberOfNames());
+ assertEquals(0, b.getNumberOfSheets());
+ }
}
@Test
public void sheetSelection() throws IOException {
- Workbook b = _testDataProvider.createWorkbook();
- b.createSheet("Sheet One");
- b.createSheet("Sheet Two");
- b.setActiveSheet(1);
- b.setSelectedTab(1);
- b.setFirstVisibleTab(1);
- assertEquals(1, b.getActiveSheetIndex());
- assertEquals(1, b.getFirstVisibleTab());
- b.close();
+ try (Workbook b = _testDataProvider.createWorkbook()) {
+ b.createSheet("Sheet One");
+ b.createSheet("Sheet Two");
+ b.setActiveSheet(1);
+ b.setSelectedTab(1);
+ b.setFirstVisibleTab(1);
+ assertEquals(1, b.getActiveSheetIndex());
+ assertEquals(1, b.getFirstVisibleTab());
+ }
}
@Test
public void printArea() throws IOException {
- Workbook workbook = _testDataProvider.createWorkbook();
- Sheet sheet1 = workbook.createSheet("Test Print Area");
- String sheetName1 = sheet1.getSheetName();
-
- // workbook.setPrintArea(0, reference);
- workbook.setPrintArea(0, 1, 5, 4, 9);
- String retrievedPrintArea = workbook.getPrintArea(0);
- assertEquals("'" + sheetName1 + "'!$B$5:$F$10", retrievedPrintArea);
-
- String reference = "$A$1:$B$1";
- workbook.setPrintArea(0, reference);
- retrievedPrintArea = workbook.getPrintArea(0);
- assertEquals("'" + sheetName1 + "'!" + reference, retrievedPrintArea);
-
- workbook.removePrintArea(0);
- assertNull(workbook.getPrintArea(0));
- workbook.close();
+ try (Workbook workbook = _testDataProvider.createWorkbook()) {
+ Sheet sheet1 = workbook.createSheet("Test Print Area");
+ String sheetName1 = sheet1.getSheetName();
+
+ // workbook.setPrintArea(0, reference);
+ workbook.setPrintArea(0, 1, 5, 4, 9);
+ String retrievedPrintArea = workbook.getPrintArea(0);
+ assertEquals("'" + sheetName1 + "'!$B$5:$F$10", retrievedPrintArea);
+
+ String reference = "$A$1:$B$1";
+ workbook.setPrintArea(0, reference);
+ retrievedPrintArea = workbook.getPrintArea(0);
+ assertEquals("'" + sheetName1 + "'!" + reference, retrievedPrintArea);
+
+ workbook.removePrintArea(0);
+ assertNull(workbook.getPrintArea(0));
+ }
}
@Test
public void getSetActiveSheet() throws IOException {
- Workbook workbook = _testDataProvider.createWorkbook();
- assertEquals(0, workbook.getActiveSheetIndex());
-
- workbook.createSheet("sheet1");
- workbook.createSheet("sheet2");
- workbook.createSheet("sheet3");
- // set second sheet
- workbook.setActiveSheet(1);
- // test if second sheet is set up
- assertEquals(1, workbook.getActiveSheetIndex());
-
- workbook.setActiveSheet(0);
- // test if second sheet is set up
- assertEquals(0, workbook.getActiveSheetIndex());
- workbook.close();
+ try (Workbook workbook = _testDataProvider.createWorkbook()) {
+ assertEquals(0, workbook.getActiveSheetIndex());
+
+ workbook.createSheet("sheet1");
+ workbook.createSheet("sheet2");
+ workbook.createSheet("sheet3");
+ // set second sheet
+ workbook.setActiveSheet(1);
+ // test if second sheet is set up
+ assertEquals(1, workbook.getActiveSheetIndex());
+
+ workbook.setActiveSheet(0);
+ // test if second sheet is set up
+ assertEquals(0, workbook.getActiveSheetIndex());
+ }
}
@Test
public void setSheetOrder() throws IOException {
- Workbook wb = _testDataProvider.createWorkbook();
-
- for (int i=0; i < 10; i++) {
- wb.createSheet("Sheet " + i);
- }
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
- // Check the initial order
- assertEquals(0, wb.getSheetIndex("Sheet 0"));
- assertEquals(1, wb.getSheetIndex("Sheet 1"));
- assertEquals(2, wb.getSheetIndex("Sheet 2"));
- assertEquals(3, wb.getSheetIndex("Sheet 3"));
- assertEquals(4, wb.getSheetIndex("Sheet 4"));
- assertEquals(5, wb.getSheetIndex("Sheet 5"));
- assertEquals(6, wb.getSheetIndex("Sheet 6"));
- assertEquals(7, wb.getSheetIndex("Sheet 7"));
- assertEquals(8, wb.getSheetIndex("Sheet 8"));
- assertEquals(9, wb.getSheetIndex("Sheet 9"));
-
- // check active sheet
- assertEquals(0, wb.getActiveSheetIndex());
-
- // Change
- wb.setSheetOrder("Sheet 6", 0);
- assertEquals(1, wb.getActiveSheetIndex());
- wb.setSheetOrder("Sheet 3", 7);
- wb.setSheetOrder("Sheet 1", 9);
-
- // now the first sheet is at index 1
- assertEquals(1, wb.getActiveSheetIndex());
-
- // Check they're currently right
- assertEquals(0, wb.getSheetIndex("Sheet 6"));
- assertEquals(1, wb.getSheetIndex("Sheet 0"));
- assertEquals(2, wb.getSheetIndex("Sheet 2"));
- assertEquals(3, wb.getSheetIndex("Sheet 4"));
- assertEquals(4, wb.getSheetIndex("Sheet 5"));
- assertEquals(5, wb.getSheetIndex("Sheet 7"));
- assertEquals(6, wb.getSheetIndex("Sheet 3"));
- assertEquals(7, wb.getSheetIndex("Sheet 8"));
- assertEquals(8, wb.getSheetIndex("Sheet 9"));
- assertEquals(9, wb.getSheetIndex("Sheet 1"));
-
- Workbook wbr = _testDataProvider.writeOutAndReadBack(wb);
- wb.close();
+ for (int i = 0; i < 10; i++) {
+ wb.createSheet("Sheet " + i);
+ }
- assertEquals(0, wbr.getSheetIndex("Sheet 6"));
- assertEquals(1, wbr.getSheetIndex("Sheet 0"));
- assertEquals(2, wbr.getSheetIndex("Sheet 2"));
- assertEquals(3, wbr.getSheetIndex("Sheet 4"));
- assertEquals(4, wbr.getSheetIndex("Sheet 5"));
- assertEquals(5, wbr.getSheetIndex("Sheet 7"));
- assertEquals(6, wbr.getSheetIndex("Sheet 3"));
- assertEquals(7, wbr.getSheetIndex("Sheet 8"));
- assertEquals(8, wbr.getSheetIndex("Sheet 9"));
- assertEquals(9, wbr.getSheetIndex("Sheet 1"));
-
- assertEquals(1, wb.getActiveSheetIndex());
-
- // Now get the index by the sheet, not the name
- for(int i=0; i<10; i++) {
- Sheet s = wbr.getSheetAt(i);
- assertEquals(i, wbr.getSheetIndex(s));
+ // Check the initial order
+ assertEquals(0, wb.getSheetIndex("Sheet 0"));
+ assertEquals(1, wb.getSheetIndex("Sheet 1"));
+ assertEquals(2, wb.getSheetIndex("Sheet 2"));
+ assertEquals(3, wb.getSheetIndex("Sheet 3"));
+ assertEquals(4, wb.getSheetIndex("Sheet 4"));
+ assertEquals(5, wb.getSheetIndex("Sheet 5"));
+ assertEquals(6, wb.getSheetIndex("Sheet 6"));
+ assertEquals(7, wb.getSheetIndex("Sheet 7"));
+ assertEquals(8, wb.getSheetIndex("Sheet 8"));
+ assertEquals(9, wb.getSheetIndex("Sheet 9"));
+
+ // check active sheet
+ assertEquals(0, wb.getActiveSheetIndex());
+
+ // Change
+ wb.setSheetOrder("Sheet 6", 0);
+ assertEquals(1, wb.getActiveSheetIndex());
+ wb.setSheetOrder("Sheet 3", 7);
+ wb.setSheetOrder("Sheet 1", 9);
+
+ // now the first sheet is at index 1
+ assertEquals(1, wb.getActiveSheetIndex());
+
+ // Check they're currently right
+ assertEquals(0, wb.getSheetIndex("Sheet 6"));
+ assertEquals(1, wb.getSheetIndex("Sheet 0"));
+ assertEquals(2, wb.getSheetIndex("Sheet 2"));
+ assertEquals(3, wb.getSheetIndex("Sheet 4"));
+ assertEquals(4, wb.getSheetIndex("Sheet 5"));
+ assertEquals(5, wb.getSheetIndex("Sheet 7"));
+ assertEquals(6, wb.getSheetIndex("Sheet 3"));
+ assertEquals(7, wb.getSheetIndex("Sheet 8"));
+ assertEquals(8, wb.getSheetIndex("Sheet 9"));
+ assertEquals(9, wb.getSheetIndex("Sheet 1"));
+
+ try (Workbook wbr = _testDataProvider.writeOutAndReadBack(wb)) {
+
+ assertEquals(0, wbr.getSheetIndex("Sheet 6"));
+ assertEquals(1, wbr.getSheetIndex("Sheet 0"));
+ assertEquals(2, wbr.getSheetIndex("Sheet 2"));
+ assertEquals(3, wbr.getSheetIndex("Sheet 4"));
+ assertEquals(4, wbr.getSheetIndex("Sheet 5"));
+ assertEquals(5, wbr.getSheetIndex("Sheet 7"));
+ assertEquals(6, wbr.getSheetIndex("Sheet 3"));
+ assertEquals(7, wbr.getSheetIndex("Sheet 8"));
+ assertEquals(8, wbr.getSheetIndex("Sheet 9"));
+ assertEquals(9, wbr.getSheetIndex("Sheet 1"));
+
+ assertEquals(1, wb.getActiveSheetIndex());
+
+ // Now get the index by the sheet, not the name
+ for (int i = 0; i < 10; i++) {
+ Sheet s = wbr.getSheetAt(i);
+ assertEquals(i, wbr.getSheetIndex(s));
+ }
+ }
}
-
- wbr.close();
}
@Test
public void cloneSheet() throws IOException {
- Workbook book = _testDataProvider.createWorkbook();
- Sheet sheet = book.createSheet("TEST");
- sheet.createRow(0).createCell(0).setCellValue("Test");
- sheet.createRow(1).createCell(0).setCellValue(36.6);
- assertEquals(0, sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 2)));
- assertEquals(1, sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 2)));
- assertTrue(sheet.isSelected());
-
- Sheet clonedSheet = book.cloneSheet(0);
- assertEquals("TEST (2)", clonedSheet.getSheetName());
- assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
- assertEquals(2, clonedSheet.getNumMergedRegions());
- assertFalse(clonedSheet.isSelected());
-
- //cloned sheet is a deep copy, adding rows or merged regions in the original does not affect the clone
- sheet.createRow(2).createCell(0).setCellValue(1);
- assertEquals(2, sheet.addMergedRegion(new CellRangeAddress(4, 5, 0, 2)));
- assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
- assertEquals(2, clonedSheet.getNumMergedRegions());
-
- clonedSheet.createRow(2).createCell(0).setCellValue(1);
- assertEquals(2, clonedSheet.addMergedRegion(new CellRangeAddress(6, 7, 0, 2)));
- assertEquals(3, clonedSheet.getPhysicalNumberOfRows());
- assertEquals(3, clonedSheet.getNumMergedRegions());
- book.close();
+ try (Workbook book = _testDataProvider.createWorkbook()) {
+ Sheet sheet = book.createSheet("TEST");
+ sheet.createRow(0).createCell(0).setCellValue("Test");
+ sheet.createRow(1).createCell(0).setCellValue(36.6);
+ assertEquals(0, sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 2)));
+ assertEquals(1, sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 2)));
+ assertTrue(sheet.isSelected());
+
+ Sheet clonedSheet = book.cloneSheet(0);
+ assertEquals("TEST (2)", clonedSheet.getSheetName());
+ assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
+ assertEquals(2, clonedSheet.getNumMergedRegions());
+ assertFalse(clonedSheet.isSelected());
+
+ //cloned sheet is a deep copy, adding rows or merged regions in the original does not affect the clone
+ sheet.createRow(2).createCell(0).setCellValue(1);
+ assertEquals(2, sheet.addMergedRegion(new CellRangeAddress(4, 5, 0, 2)));
+ assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
+ assertEquals(2, clonedSheet.getNumMergedRegions());
+
+ clonedSheet.createRow(2).createCell(0).setCellValue(1);
+ assertEquals(2, clonedSheet.addMergedRegion(new CellRangeAddress(6, 7, 0, 2)));
+ assertEquals(3, clonedSheet.getPhysicalNumberOfRows());
+ assertEquals(3, clonedSheet.getNumMergedRegions());
+ }
}
@Test
public void parentReferences() throws IOException {
- Workbook wb1 = _testDataProvider.createWorkbook();
- Sheet sheet = wb1.createSheet();
- assertSame(wb1, sheet.getWorkbook());
+ try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+ Sheet sheet = wb1.createSheet();
+ assertSame(wb1, sheet.getWorkbook());
- Row row = sheet.createRow(0);
- assertSame(sheet, row.getSheet());
+ Row row = sheet.createRow(0);
+ assertSame(sheet, row.getSheet());
- Cell cell = row.createCell(1);
- assertSame(sheet, cell.getSheet());
- assertSame(row, cell.getRow());
+ Cell cell = row.createCell(1);
+ assertSame(sheet, cell.getSheet());
+ assertSame(row, cell.getRow());
- Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- assertSame(wb2, sheet.getWorkbook());
+ try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+ wb1.close();
+ sheet = wb2.getSheetAt(0);
+ assertSame(wb2, sheet.getWorkbook());
- row = sheet.getRow(0);
- assertSame(sheet, row.getSheet());
+ row = sheet.getRow(0);
+ assertSame(sheet, row.getSheet());
- cell = row.getCell(1);
- assertSame(sheet, cell.getSheet());
- assertSame(row, cell.getRow());
- wb2.close();
+ cell = row.getCell(1);
+ assertSame(sheet, cell.getSheet());
+ assertSame(row, cell.getRow());
+ }
+ }
}
/**
* Test to validate that replacement for removed setRepeatingRowsAnsColumns() methods
- * is still working correctly
+ * is still working correctly
*/
@Test
public void setRepeatingRowsAnsColumns() throws IOException {
- Workbook wb = _testDataProvider.createWorkbook();
-
- CellRangeAddress cra = new CellRangeAddress(0, 3, 0, 0);
- String expRows = "1:4", expCols = "A:A";
-
-
- Sheet sheet1 = wb.createSheet();
- sheet1.setRepeatingRows(cra);
- sheet1.setRepeatingColumns(cra);
- assertEquals(expRows, sheet1.getRepeatingRows().formatAsString());
- assertEquals(expCols, sheet1.getRepeatingColumns().formatAsString());
-
- //must handle sheets with quotas, see Bugzilla #47294
- Sheet sheet2 = wb.createSheet("My' Sheet");
- sheet2.setRepeatingRows(cra);
- sheet2.setRepeatingColumns(cra);
- assertEquals(expRows, sheet2.getRepeatingRows().formatAsString());
- assertEquals(expCols, sheet2.getRepeatingColumns().formatAsString());
- wb.close();
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
+ CellRangeAddress cra = new CellRangeAddress(0, 3, 0, 0);
+ String expRows = "1:4", expCols = "A:A";
+
+
+ Sheet sheet1 = wb.createSheet();
+ sheet1.setRepeatingRows(cra);
+ sheet1.setRepeatingColumns(cra);
+ assertEquals(expRows, sheet1.getRepeatingRows().formatAsString());
+ assertEquals(expCols, sheet1.getRepeatingColumns().formatAsString());
+
+ //must handle sheets with quotas, see Bugzilla #47294
+ Sheet sheet2 = wb.createSheet("My' Sheet");
+ sheet2.setRepeatingRows(cra);
+ sheet2.setRepeatingColumns(cra);
+ assertEquals(expRows, sheet2.getRepeatingRows().formatAsString());
+ assertEquals(expCols, sheet2.getRepeatingColumns().formatAsString());
+ }
}
/**
@@ -565,73 +557,74 @@ public abstract class BaseTestWorkbook {
*/
@Test
public void unicodeInAll() throws IOException {
- Workbook wb1 = _testDataProvider.createWorkbook();
- CreationHelper factory = wb1.getCreationHelper();
- //Create a unicode dataformat (contains euro symbol)
- DataFormat df = wb1.createDataFormat();
- final String formatStr = "_([$\u20ac-2]\\\\\\ * #,##0.00_);_([$\u20ac-2]\\\\\\ * \\\\\\(#,##0.00\\\\\\);_([$\u20ac-2]\\\\\\ *\\\"\\-\\\\\"??_);_(@_)";
- short fmt = df.getFormat(formatStr);
-
- //Create a unicode sheet name (euro symbol)
- Sheet s = wb1.createSheet("\u20ac");
-
- //Set a unicode header (you guessed it the euro symbol)
- Header h = s.getHeader();
- h.setCenter("\u20ac");
- h.setLeft("\u20ac");
- h.setRight("\u20ac");
-
- //Set a unicode footer
- Footer f = s.getFooter();
- f.setCenter("\u20ac");
- f.setLeft("\u20ac");
- f.setRight("\u20ac");
-
- Row r = s.createRow(0);
- Cell c = r.createCell(1);
- c.setCellValue(12.34);
- c.getCellStyle().setDataFormat(fmt);
-
- /*Cell c2 =*/ r.createCell(2); // TODO - c2 unused but changing next line ('c'->'c2') causes test to fail
- c.setCellValue(factory.createRichTextString("\u20ac"));
-
- Cell c3 = r.createCell(3);
- String formulaString = "TEXT(12.34,\"\u20ac###,##\")";
- c3.setCellFormula(formulaString);
-
- Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
- wb1.close();
-
- //Test the sheetname
- s = wb2.getSheet("\u20ac");
- assertNotNull(s);
-
- //Test the header
- h = s.getHeader();
- assertEquals(h.getCenter(), "\u20ac");
- assertEquals(h.getLeft(), "\u20ac");
- assertEquals(h.getRight(), "\u20ac");
-
- //Test the footer
- f = s.getFooter();
- assertEquals(f.getCenter(), "\u20ac");
- assertEquals(f.getLeft(), "\u20ac");
- assertEquals(f.getRight(), "\u20ac");
-
- //Test the dataformat
- r = s.getRow(0);
- c = r.getCell(1);
- df = wb2.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);
- wb2.close();
+ try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+ CreationHelper factory = wb1.getCreationHelper();
+ //Create a unicode dataformat (contains euro symbol)
+ DataFormat df = wb1.createDataFormat();
+ final String formatStr = "_([$\u20ac-2]\\\\\\ * #,##0.00_);_([$\u20ac-2]\\\\\\ * \\\\\\(#,##0.00\\\\\\);_([$\u20ac-2]\\\\\\ *\\\"\\-\\\\\"??_);_(@_)";
+ short fmt = df.getFormat(formatStr);
+
+ //Create a unicode sheet name (euro symbol)
+ Sheet s = wb1.createSheet("\u20ac");
+
+ //Set a unicode header (you guessed it the euro symbol)
+ Header h = s.getHeader();
+ h.setCenter("\u20ac");
+ h.setLeft("\u20ac");
+ h.setRight("\u20ac");
+
+ //Set a unicode footer
+ Footer f = s.getFooter();
+ f.setCenter("\u20ac");
+ f.setLeft("\u20ac");
+ f.setRight("\u20ac");
+
+ Row r = s.createRow(0);
+ Cell c = r.createCell(1);
+ c.setCellValue(12.34);
+ c.getCellStyle().setDataFormat(fmt);
+
+ /*Cell c2 =*/
+ r.createCell(2); // TODO - c2 unused but changing next line ('c'->'c2') causes test to fail
+ c.setCellValue(factory.createRichTextString("\u20ac"));
+
+ Cell c3 = r.createCell(3);
+ String formulaString = "TEXT(12.34,\"\u20ac###,##\")";
+ c3.setCellFormula(formulaString);
+
+ try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+ //Test the sheetname
+ s = wb2.getSheet("\u20ac");
+ assertNotNull(s);
+
+ //Test the header
+ h = s.getHeader();
+ assertEquals(h.getCenter(), "\u20ac");
+ assertEquals(h.getLeft(), "\u20ac");
+ assertEquals(h.getRight(), "\u20ac");
+
+ //Test the footer
+ f = s.getFooter();
+ assertEquals(f.getCenter(), "\u20ac");
+ assertEquals(f.getLeft(), "\u20ac");
+ assertEquals(f.getRight(), "\u20ac");
+
+ //Test the dataformat
+ r = s.getRow(0);
+ c = r.getCell(1);
+ df = wb2.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);
+ }
+ }
}
private Workbook newSetSheetNameTestingWorkbook() {
@@ -671,7 +664,6 @@ public abstract class BaseTestWorkbook {
sh3.createRow(4).createCell(0).setCellValue(5);
sh3.createRow(5).createCell(0).setCellFormula("sale_3");
sh3.createRow(6).createCell(0).setCellFormula("'Testing 47100'!C1");
-
return wb;
}
@@ -682,110 +674,107 @@ public abstract class BaseTestWorkbook {
*/
@Test
public void setSheetName() throws IOException {
-
- Workbook wb1 = newSetSheetNameTestingWorkbook();
-
- Sheet sh1 = wb1.getSheetAt(0);
-
- Name sale_2 = wb1.getName("sale_2");
- Name sale_3 = wb1.getName("sale_3");
- Name sale_4 = wb1.getName("sale_4");
-
- assertEquals("sale_2", sale_2.getNameName());
- assertEquals("'Testing 47100'!$A$1", sale_2.getRefersToFormula());
- assertEquals("sale_3", sale_3.getNameName());
- assertEquals("'Testing 47100'!$B$1", sale_3.getRefersToFormula());
- assertEquals("sale_4", sale_4.getNameName());
- assertEquals("'To be renamed'!$A$3", sale_4.getRefersToFormula());
-
- FormulaEvaluator evaluator = wb1.getCreationHelper().createFormulaEvaluator();
-
- Cell cell0 = sh1.getRow(0).getCell(0);
- Cell cell1 = sh1.getRow(1).getCell(0);
- Cell cell2 = sh1.getRow(2).getCell(0);
-
- assertEquals("SUM('Testing 47100'!A1:C1)", cell0.getCellFormula());
- assertEquals("SUM('Testing 47100'!A1:C1,'To be renamed'!A1:A5)", cell1.getCellFormula());
- assertEquals("sale_2+sale_3+'Testing 47100'!C1", cell2.getCellFormula());
-
- assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0);
- assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0);
- assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0);
-
- wb1.setSheetName(1, "47100 - First");
- wb1.setSheetName(2, "47100 - Second");
-
- assertEquals("sale_2", sale_2.getNameName());
- assertEquals("'47100 - First'!$A$1", sale_2.getRefersToFormula());
- assertEquals("sale_3", sale_3.getNameName());
- assertEquals("'47100 - First'!$B$1", sale_3.getRefersToFormula());
- assertEquals("sale_4", sale_4.getNameName());
- assertEquals("'47100 - Second'!$A$3", sale_4.getRefersToFormula());
-
- assertEquals("SUM('47100 - First'!A1:C1)", cell0.getCellFormula());
- assertEquals("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.getCellFormula());
- assertEquals("sale_2+sale_3+'47100 - First'!C1", cell2.getCellFormula());
-
- evaluator.clearAllCachedResultValues();
- assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0);
- assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0);
- assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0);
-
- Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
- wb1.close();
-
- sh1 = wb2.getSheetAt(0);
-
- sale_2 = wb2.getName("sale_2");
- sale_3 = wb2.getName("sale_3");
- sale_4 = wb2.getName("sale_4");
-
- cell0 = sh1.getRow(0).getCell(0);
- cell1 = sh1.getRow(1).getCell(0);
- cell2 = sh1.getRow(2).getCell(0);
-
- assertEquals("sale_2", sale_2.getNameName());
- assertEquals("'47100 - First'!$A$1", sale_2.getRefersToFormula());
- assertEquals("sale_3", sale_3.getNameName());
- assertEquals("'47100 - First'!$B$1", sale_3.getRefersToFormula());
- assertEquals("sale_4", sale_4.getNameName());
- assertEquals("'47100 - Second'!$A$3", sale_4.getRefersToFormula());
-
- assertEquals("SUM('47100 - First'!A1:C1)", cell0.getCellFormula());
- assertEquals("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.getCellFormula());
- assertEquals("sale_2+sale_3+'47100 - First'!C1", cell2.getCellFormula());
-
- evaluator = wb2.getCreationHelper().createFormulaEvaluator();
- assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0);
- assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0);
- assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0);
- wb2.close();
+ try (Workbook wb1 = newSetSheetNameTestingWorkbook()) {
+ Sheet sh1 = wb1.getSheetAt(0);
+
+ Name sale_2 = wb1.getName("sale_2");
+ Name sale_3 = wb1.getName("sale_3");
+ Name sale_4 = wb1.getName("sale_4");
+
+ assertEquals("sale_2", sale_2.getNameName());
+ assertEquals("'Testing 47100'!$A$1", sale_2.getRefersToFormula());
+ assertEquals("sale_3", sale_3.getNameName());
+ assertEquals("'Testing 47100'!$B$1", sale_3.getRefersToFormula());
+ assertEquals("sale_4", sale_4.getNameName());
+ assertEquals("'To be renamed'!$A$3", sale_4.getRefersToFormula());
+
+ FormulaEvaluator evaluator = wb1.getCreationHelper().createFormulaEvaluator();
+
+ Cell cell0 = sh1.getRow(0).getCell(0);
+ Cell cell1 = sh1.getRow(1).getCell(0);
+ Cell cell2 = sh1.getRow(2).getCell(0);
+
+ assertEquals("SUM('Testing 47100'!A1:C1)", cell0.getCellFormula());
+ assertEquals("SUM('Testing 47100'!A1:C1,'To be renamed'!A1:A5)", cell1.getCellFormula());
+ assertEquals("sale_2+sale_3+'Testing 47100'!C1", cell2.getCellFormula());
+
+ assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0);
+ assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0);
+ assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0);
+
+ wb1.setSheetName(1, "47100 - First");
+ wb1.setSheetName(2, "47100 - Second");
+
+ assertEquals("sale_2", sale_2.getNameName());
+ assertEquals("'47100 - First'!$A$1", sale_2.getRefersToFormula());
+ assertEquals("sale_3", sale_3.getNameName());
+ assertEquals("'47100 - First'!$B$1", sale_3.getRefersToFormula());
+ assertEquals("sale_4", sale_4.getNameName());
+ assertEquals("'47100 - Second'!$A$3", sale_4.getRefersToFormula());
+
+ assertEquals("SUM('47100 - First'!A1:C1)", cell0.getCellFormula());
+ assertEquals("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.getCellFormula());
+ assertEquals("sale_2+sale_3+'47100 - First'!C1", cell2.getCellFormula());
+
+ evaluator.clearAllCachedResultValues();
+ assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0);
+ assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0);
+ assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0);
+
+ try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+ sh1 = wb2.getSheetAt(0);
+
+ sale_2 = wb2.getName("sale_2");
+ sale_3 = wb2.getName("sale_3");
+ sale_4 = wb2.getName("sale_4");
+
+ cell0 = sh1.getRow(0).getCell(0);
+ cell1 = sh1.getRow(1).getCell(0);
+ cell2 = sh1.getRow(2).getCell(0);
+
+ assertEquals("sale_2", sale_2.getNameName());
+ assertEquals("'47100 - First'!$A$1", sale_2.getRefersToFormula());
+ assertEquals("sale_3", sale_3.getNameName());
+ assertEquals("'47100 - First'!$B$1", sale_3.getRefersToFormula());
+ assertEquals("sale_4", sale_4.getNameName());
+ assertEquals("'47100 - Second'!$A$3", sale_4.getRefersToFormula());
+
+ assertEquals("SUM('47100 - First'!A1:C1)", cell0.getCellFormula());
+ assertEquals("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.getCellFormula());
+ assertEquals("sale_2+sale_3+'47100 - First'!C1", cell2.getCellFormula());
+
+ evaluator = wb2.getCreationHelper().createFormulaEvaluator();
+ assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0);
+ assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0);
+ assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0);
+ }
+ }
}
protected void changeSheetNameWithSharedFormulas(String sampleFile) throws IOException {
- Workbook wb = _testDataProvider.openSampleWorkbook(sampleFile);
+ try (Workbook wb = _testDataProvider.openSampleWorkbook(sampleFile)) {
- FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
+ FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
- Sheet sheet = wb.getSheetAt(0);
+ Sheet sheet = wb.getSheetAt(0);
- for (int rownum = 1; rownum <= 40; rownum++) {
- Cell cellA = sheet.getRow(1).getCell(0);
- Cell cellB = sheet.getRow(1).getCell(1);
+ for (int rownum = 1; rownum <= 40; rownum++) {
+ Cell cellA = sheet.getRow(1).getCell(0);
+ Cell cellB = sheet.getRow(1).getCell(1);
- assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue());
- }
+ assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue());
+ }
- wb.setSheetName(0, "Renamed by POI");
- evaluator.clearAllCachedResultValues();
+ wb.setSheetName(0, "Renamed by POI");
+ evaluator.clearAllCachedResultValues();
- for (int rownum = 1; rownum <= 40; rownum++) {
- Cell cellA = sheet.getRow(1).getCell(0);
- Cell cellB = sheet.getRow(1).getCell(1);
+ for (int rownum = 1; rownum <= 40; rownum++) {
+ Cell cellA = sheet.getRow(1).getCell(0);
+ Cell cellB = sheet.getRow(1).getCell(1);
- assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue());
+ assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue());
+ }
}
- wb.close();
}
protected void assertSheetOrder(Workbook wb, String... sheets) {
@@ -803,43 +792,37 @@ public abstract class BaseTestWorkbook {
@Test
public void test58499() throws IOException {
- Workbook workbook = _testDataProvider.createWorkbook();
- Sheet sheet = workbook.createSheet();
- for (int i = 0; i < 900; i++) {
- Row r = sheet.createRow(i);
- Cell c = r.createCell(0);
- CellStyle cs = workbook.createCellStyle();
- c.setCellStyle(cs);
- c.setCellValue("AAA");
- }
- try (OutputStream os = new NullOutputStream()) {
+ try (Workbook workbook = _testDataProvider.createWorkbook();
+ OutputStream os = new NullOutputStream()) {
+ Sheet sheet = workbook.createSheet();
+ for (int i = 0; i < 900; i++) {
+ Row r = sheet.createRow(i);
+ Cell c = r.createCell(0);
+ CellStyle cs = workbook.createCellStyle();
+ c.setCellStyle(cs);
+ c.setCellValue("AAA");
+ }
workbook.write(os);
}
- //workbook.dispose();
- workbook.close();
}
@Test
public void windowOneDefaults() throws IOException {
- Workbook b = _testDataProvider.createWorkbook();
- try {
+ try (Workbook b = _testDataProvider.createWorkbook()) {
assertEquals(b.getActiveSheetIndex(), 0);
assertEquals(b.getFirstVisibleTab(), 0);
- } catch (NullPointerException npe) {
- fail("WindowOneRecord in Workbook is probably not initialized");
+ // throws NullPointerException when WindowOneRecord in Workbook is not probably initialized
}
-
- b.close();
}
@Test
public void getSpreadsheetVersion() throws IOException {
- final Workbook wb = _testDataProvider.createWorkbook();
- assertEquals(_testDataProvider.getSpreadsheetVersion(), wb.getSpreadsheetVersion());
- wb.close();
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
+ assertEquals(_testDataProvider.getSpreadsheetVersion(), wb.getSpreadsheetVersion());
+ }
}
-
+
/* FIXME copied from {@link org.apache.poi.ss.TestWorkbookFactory} */
protected static void assertCloseDoesNotModifyFile(String filename, Workbook wb) throws IOException {
final byte[] before = HSSFTestDataSamples.getTestDataFileContent(filename);
@@ -852,23 +835,21 @@ public abstract class BaseTestWorkbook {
@Test
public void sheetClone() throws IOException {
// First up, try a simple file
- final Workbook b = _testDataProvider.createWorkbook();
- assertEquals(0, b.getNumberOfSheets());
- b.createSheet("Sheet One");
- b.createSheet("Sheet Two");
-
- assertEquals(2, b.getNumberOfSheets());
- b.cloneSheet(0);
- assertEquals(3, b.getNumberOfSheets());
-
- // Now try a problem one with drawing records in it
- Workbook bBack = HSSFTestDataSamples.openSampleWorkbook("SheetWithDrawing.xls");
- assertEquals(1, bBack.getNumberOfSheets());
- bBack.cloneSheet(0);
- assertEquals(2, bBack.getNumberOfSheets());
-
- bBack.close();
- b.close();
+ try (Workbook b = _testDataProvider.createWorkbook();
+ Workbook bBack = HSSFTestDataSamples.openSampleWorkbook("SheetWithDrawing.xls")) {
+ assertEquals(0, b.getNumberOfSheets());
+ b.createSheet("Sheet One");
+ b.createSheet("Sheet Two");
+
+ assertEquals(2, b.getNumberOfSheets());
+ b.cloneSheet(0);
+ assertEquals(3, b.getNumberOfSheets());
+
+ // Now try a problem one with drawing records in it
+ assertEquals(1, bBack.getNumberOfSheets());
+ bBack.cloneSheet(0);
+ assertEquals(2, bBack.getNumberOfSheets());
+ }
}
@Test
@@ -899,71 +880,57 @@ public abstract class BaseTestWorkbook {
@Test
public void addSheetTwice() throws IOException {
- final Workbook wb = _testDataProvider.createWorkbook();
- Sheet sheet1 = wb.createSheet("Sheet1");
- assertNotNull(sheet1);
- try {
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
+ Sheet sheet1 = wb.createSheet("Sheet1");
+ assertNotNull(sheet1);
+
+ thrown.expect(IllegalArgumentException.class);
+ thrown.expectMessage("already contains a sheet named 'Sheet1'");
wb.createSheet("Sheet1");
- fail("Should fail if we add the same sheet twice");
- } catch (IllegalArgumentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("already contains a sheet named 'Sheet1'"));
}
-
- wb.close();
}
-
+
// bug 51233 and 55075: correctly size image if added to a row with a custom height
@Test
public void createDrawing() throws Exception {
- Workbook wb = _testDataProvider.createWorkbook();
- Sheet sheet = wb.createSheet("Main Sheet");
- Row row0 = sheet.createRow(0);
- Row row1 = sheet.createRow(1);
- row1.createCell(0);
- row0.createCell(1);
- row1.createCell(0);
- row1.createCell(1);
-
- byte[] pictureData = _testDataProvider.getTestDataFileContent("logoKarmokar4.png");
-
- int handle = wb.addPicture(pictureData, Workbook.PICTURE_TYPE_PNG);
- Drawing<?> drawing = sheet.createDrawingPatriarch();
- CreationHelper helper = wb.getCreationHelper();
- ClientAnchor anchor = helper.createClientAnchor();
- anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
- anchor.setCol1(0);
- anchor.setRow1(0);
- Picture picture = drawing.createPicture(anchor, handle);
-
- row0.setHeightInPoints(144);
- // set a column width so that XSSF and SXSSF have the same width (default widths may be different otherwise)
- sheet.setColumnWidth(0, 100*256);
- picture.resize();
-
- // The actual dimensions don't matter as much as having XSSF and SXSSF produce the same size drawings
-
- // Check drawing height
- assertEquals(0, anchor.getRow1());
- assertEquals(0, anchor.getRow2());
- assertEquals(0, anchor.getDy1());
- assertEquals(1609725, anchor.getDy2()); //HSSF: 225
-
- // Check drawing width
- assertEquals(0, anchor.getCol1());
- assertEquals(0, anchor.getCol2());
- assertEquals(0, anchor.getDx1());
- assertEquals(1114425, anchor.getDx2()); //HSSF: 171
-
- final boolean writeOut = false;
- if (writeOut) {
- String ext = "." + _testDataProvider.getStandardFileNameExtension();
- String prefix = wb.getClass().getName() + "-createDrawing";
- File f = TempFile.createTempFile(prefix, ext);
- FileOutputStream out = new FileOutputStream(f);
- wb.write(out);
- out.close();
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
+ Sheet sheet = wb.createSheet("Main Sheet");
+ Row row0 = sheet.createRow(0);
+ Row row1 = sheet.createRow(1);
+ row1.createCell(0);
+ row0.createCell(1);
+ row1.createCell(0);
+ row1.createCell(1);
+
+ byte[] pictureData = _testDataProvider.getTestDataFileContent("logoKarmokar4.png");
+
+ int handle = wb.addPicture(pictureData, Workbook.PICTURE_TYPE_PNG);
+ Drawing<?> drawing = sheet.createDrawingPatriarch();
+ CreationHelper helper = wb.getCreationHelper();
+ ClientAnchor anchor = helper.createClientAnchor();
+ anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
+ anchor.setCol1(0);
+ anchor.setRow1(0);
+ Picture picture = drawing.createPicture(anchor, handle);
+
+ row0.setHeightInPoints(144);
+ // set a column width so that XSSF and SXSSF have the same width (default widths may be different otherwise)
+ sheet.setColumnWidth(0, 100 * 256);
+ picture.resize();
+
+ // The actual dimensions don't matter as much as having XSSF and SXSSF produce the same size drawings
+
+ // Check drawing height
+ assertEquals(0, anchor.getRow1());
+ assertEquals(0, anchor.getRow2());
+ assertEquals(0, anchor.getDy1());
+ assertEquals(1609725, anchor.getDy2()); //HSSF: 225
+
+ // Check drawing width
+ assertEquals(0, anchor.getCol1());
+ assertEquals(0, anchor.getCol2());
+ assertEquals(0, anchor.getDx1());
+ assertEquals(1114425, anchor.getDx2()); //HSSF: 171
}
- wb.close();
}
-
}
diff --git a/src/testcases/org/apache/poi/util/NullPrintStream.java b/src/testcases/org/apache/poi/util/NullPrintStream.java
new file mode 100644
index 0000000000..5fd6bc64ad
--- /dev/null
+++ b/src/testcases/org/apache/poi/util/NullPrintStream.java
@@ -0,0 +1,88 @@
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ 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 obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+==================================================================== */
+
+package org.apache.poi.util;
+
+import java.io.PrintStream;
+import java.util.Locale;
+
+// need to override all methods to omit calls to UTF-handling methods
+@SuppressForbidden("ignore super constructor with charset - omits declaring UnsupportedEncodingException")
+public class NullPrintStream extends PrintStream {
+ @SuppressWarnings("resource")
+ public NullPrintStream() {
+ super(new NullOutputStream(), true);
+ }
+ @Override
+ public void write(int b) {}
+ @Override
+ public void write(byte[] buf, int off, int len) {}
+ @Override
+ public void print(boolean b) {}
+ @Override
+ public void print(char c) {}
+ @Override
+ public void print(int i) {}
+ @Override
+ public void print(long l) {}
+ @Override
+ public void print(float f) {}
+ @Override
+ public void print(double d) {}
+ @Override
+ public void print(char[] s) {}
+ @Override
+ public void print(String s) {}
+ @Override
+ public void print(Object obj) {}
+ @Override
+ public void println() {}
+ @Override
+ public void println(boolean x) {}
+ @Override
+ public void println(char x) {}
+ @Override
+ public void println(int x) {}
+ @Override
+ public void println(long x) {}
+ @Override
+ public void println(float x) {}
+ @Override
+ public void println(double x) {}
+ @Override
+ public void println(char[] x) {}
+ @Override
+ public void println(String x) {}
+ @Override
+ public void println(Object x) {}
+ @Override
+ public PrintStream printf(String format, Object... args) { return this; }
+ @Override
+ public PrintStream printf(Locale l, String format, Object... args) { return this; }
+ @Override
+ public PrintStream format(String format, Object... args) { return this; }
+ @Override
+ public PrintStream format(Locale l, String format, Object... args) { return this; }
+ @Override
+ public PrintStream append(CharSequence csq) { return this; }
+ @Override
+ public PrintStream append(CharSequence csq, int start, int end) { return this; }
+ @Override
+ public PrintStream append(char c) { return this; }
+ @Override
+ public void write(byte[] b) {}
+}