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
This commit is contained in:
Andreas Beeker 2020-08-17 20:25:08 +00:00
parent f8040e5f8c
commit b7b0a0c215
37 changed files with 802 additions and 818 deletions

View File

@ -1549,7 +1549,7 @@ under the License.
<delete dir="build" includes="test-integration.log*"/> <delete dir="build" includes="test-integration.log*"/>
<path id="test-integration.modules"> <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-ooxml"/>
<pathelement path="build/dist/maven/poi-scratchpad"/> <pathelement path="build/dist/maven/poi-scratchpad"/>
<pathelement path="build/dist/maven/poi-examples"/> <pathelement path="build/dist/maven/poi-examples"/>
@ -2252,16 +2252,22 @@ under the License.
<fileset dir="lib/ooxml-provided" includes="*.jar"/> <fileset dir="lib/ooxml-provided" includes="*.jar"/>
<fileset dir="lib/excelant" includes="*.jar"/> <fileset dir="lib/excelant" includes="*.jar"/>
<pathelement location="${ooxml.xsds.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"/> <pathelement location="build/dist/maven/poi-examples/poi-examples-${version.id}.jar"/>
<path path="${env.CLASSPATH}"/> <path path="${env.CLASSPATH}"/>
</path> </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 --> <!-- first check rules that apply to all the source code -->
<forbiddenapis <forbiddenapis
classpathref="forbiddenapis.classpath" classpathref="forbiddenapis.classpath"
suppressAnnotation="org.apache.poi.util.SuppressForbidden" suppressAnnotation="org.apache.poi.util.SuppressForbidden"
targetVersion="${ant.java.version}" targetVersion="${forbiddenVersion}"
> >
<bundledsignatures name="jdk-unsafe"/> <bundledsignatures name="jdk-unsafe"/>
<bundledsignatures name="jdk-deprecated"/> <bundledsignatures name="jdk-deprecated"/>
@ -2272,29 +2278,20 @@ under the License.
<bundledsignatures name="jdk-system-out"/> <bundledsignatures name="jdk-system-out"/>
--> -->
<signaturesFileset file="src/resources/devtools/forbidden-signatures.txt"/> <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) --> <!-- test-sources (incl. sources) -->
<zipfileset src="build/dist/maven/poi-tests/poi-${version.id}-tests.jar"/> <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"/> <zipfileset src="build/dist/maven/poi-ooxml-tests/poi-ooxml-${version.id}-tests.jar"/>
<!-- <zipfileset src="build/dist/maven/poi-scratchpad-tests/poi-scratchpad-${version.id}-tests.jar"/>
<fileset dir="${scratchpad.output.test.dir}"/> <zipfileset src="build/dist/maven/poi-excelant-tests/poi-excelant-${version.id}-tests.jar"/>
<fileset dir="${excelant.output.test.dir}"/> <zipfileset src="build/dist/maven/poi-examples/poi-examples-${version.id}.jar"/>
<fileset dir="${integration.output.test.dir}"/> <zipfileset src="build/dist/maven/poi-integration/poi-integration-${version.id}.jar"/>
-->
</forbiddenapis> </forbiddenapis>
<!-- then check some advanced rules which we only apply to the core code and not tests or examples --> <!-- then check some advanced rules which we only apply to the core code and not tests or examples -->
<forbiddenapis <forbiddenapis
classpathref="forbiddenapis.classpath" classpathref="forbiddenapis.classpath"
suppressAnnotation="org.apache.poi.util.SuppressForbidden" suppressAnnotation="org.apache.poi.util.SuppressForbidden"
targetVersion="${jdk.version.source}" targetVersion="${forbiddenVersion}"
> >
<signaturesFileset file="src/resources/devtools/forbidden-signatures-prod.txt"/> <signaturesFileset file="src/resources/devtools/forbidden-signatures-prod.txt"/>
<!-- sources --> <!-- sources -->

View File

@ -62,7 +62,7 @@ public class Msg2txt {
public void processMessage() throws IOException { public void processMessage() throws IOException {
String txtFileName = fileNameStem + ".txt"; String txtFileName = fileNameStem + ".txt";
String attDirName = fileNameStem + "-att"; String attDirName = fileNameStem + "-att";
try (PrintWriter txtOut = new PrintWriter(txtFileName)) { try (PrintWriter txtOut = new PrintWriter(txtFileName, "UTF-8")) {
try { try {
String displayFrom = msg.getDisplayFrom(); String displayFrom = msg.getDisplayFrom();
txtOut.println("From: " + displayFrom); txtOut.println("From: " + displayFrom);

View File

@ -21,6 +21,7 @@ import java.io.FileOutputStream;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Calendar; import java.util.Calendar;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 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.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 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(); if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook();
else wb = new XSSFWorkbook(); 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); Map<String, CellStyle> styles = createStyles(wb);
@ -124,7 +126,7 @@ public final class BusinessPlan {
cell.setCellStyle(styles.get("header")); cell.setCellStyle(styles.get("header"));
} }
//columns for 11 weeks starting from 9-Jul //columns for 11 weeks starting from 9-Jul
Calendar calendar = Calendar.getInstance(); Calendar calendar = LocaleUtil.getLocaleCalendar();
int year = calendar.get(Calendar.YEAR); int year = calendar.get(Calendar.YEAR);
calendar.setTime(fmt.parse("9-Jul")); calendar.setTime(fmt.parse("9-Jul"));

View File

@ -36,6 +36,7 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
@ -62,7 +63,7 @@ public final class CalendarDemo {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Calendar calendar = Calendar.getInstance(); Calendar calendar = LocaleUtil.getLocaleCalendar();
boolean xlsx = true; boolean xlsx = true;
for (String arg : args) { for (String arg : args) {
if (arg.charAt(0) == '-') { if (arg.charAt(0) == '-') {

View File

@ -17,6 +17,8 @@
package org.apache.poi.examples.ss; package org.apache.poi.examples.ss;
import java.io.File; import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.Iterator; import java.util.Iterator;
@ -94,6 +96,8 @@ public class ExcelComparator {
} }
List<String> listOfDifferences = new ArrayList<>(); 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 { public static void main(String[] args) throws Exception {
if (args.length != 2 || !(new File(args[0]).exists()) || !(new File(args[1]).exists())) { 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 date1 = loc1.cell.getDateCellValue();
Date date2 = loc2.cell.getDateCellValue(); Date date2 = loc2.cell.getDateCellValue();
if (!date1.equals(date2)) { 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));
} }
} }

View File

@ -23,6 +23,7 @@ import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 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.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference; 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.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@ -75,7 +77,7 @@ public final class SSPerformanceTest {
runWithArgs(type, rows, cols, saveFile); runWithArgs(type, rows, cols, saveFile);
long timeFinished = System.currentTimeMillis(); 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 { 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 sheetNo = 0;
int rowIndexInSheet = 1; int rowIndexInSheet = 1;
double value = 0; double value = 0;
Calendar calendar = Calendar.getInstance(); Calendar calendar = LocaleUtil.getLocaleCalendar();
for (int rowIndex = 0; rowIndex < rows; rowIndex++) { for (int rowIndex = 0; rowIndex < rows; rowIndex++) {
if (isHType && sheetNo != rowIndex / 0x10000) { if (isHType && sheetNo != rowIndex / 0x10000) {
sheet = workBook.createSheet("Spillover from sheet " + (++sheetNo)); sheet = workBook.createSheet("Spillover from sheet " + (++sheetNo));

View File

@ -22,9 +22,10 @@ import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList; import java.util.ArrayList;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
@ -431,7 +432,7 @@ public class ToCSV {
String csvLineElement; String csvLineElement;
// Open a writer onto the CSV file. // 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() + "]"); System.out.println("Saving the CSV file [" + file.getName() + "]");

View File

@ -19,15 +19,16 @@ package org.apache.poi.examples.ss.html;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.Closeable; import java.io.Closeable;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Formatter; import java.util.Formatter;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
@ -189,10 +190,7 @@ public final class ToHtml {
return; return;
} }
try ( try (PrintWriter pw = new PrintWriter(args[1], "UTF-8")) {
FileWriter fw = new FileWriter(args[1]);
PrintWriter pw = new PrintWriter(fw)
) {
ToHtml toHtml = create(args[0], pw); ToHtml toHtml = create(args[0], pw);
toHtml.setCompleteHTML(true); toHtml.setCompleteHTML(true);
toHtml.printPage(); toHtml.printPage();
@ -243,7 +241,7 @@ public final class ToHtml {
private void ensureOut() { private void ensureOut() {
if (out == null) { 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 // First, copy the base css
try (BufferedReader in = new BufferedReader(new InputStreamReader( try (BufferedReader in = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream("excelStyle.css")))){ getClass().getResourceAsStream("excelStyle.css"), StandardCharsets.ISO_8859_1))){
String line; String line;
while ((line = in.readLine()) != null) { while ((line = in.readLine()) != null) {
out.format("%s%n", line); out.format("%s%n", line);
@ -325,7 +323,7 @@ public final class ToHtml {
style = wb.getCellStyleAt((short) 0); style = wb.getCellStyleAt((short) 0);
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
try (Formatter fmt = new Formatter(sb)) { try (Formatter fmt = new Formatter(sb, Locale.ROOT)) {
fmt.format("style_%02x", style.getIndex()); fmt.format("style_%02x", style.getIndex());
return fmt.toString(); return fmt.toString();
} }

View File

@ -22,8 +22,10 @@ package org.apache.poi.examples.xslf;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream; 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.ArrayList;
import java.util.List; import java.util.List;
@ -62,7 +64,7 @@ public final class BarChartDemo {
} }
try (FileInputStream argIS = new FileInputStream(args[0]); 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 chartTitle = modelReader.readLine(); // first line is chart title
String[] series = modelReader.readLine().split(","); String[] series = modelReader.readLine().split(",");

View File

@ -23,8 +23,10 @@ import java.awt.geom.Rectangle2D;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream; 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.ArrayList;
import java.util.List; import java.util.List;
@ -70,7 +72,7 @@ public final class ChartFromScratch {
return; 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 chartTitle = modelReader.readLine(); // first line is chart title
String[] series = modelReader.readLine().split(","); String[] series = modelReader.readLine().split(",");

View File

@ -22,8 +22,10 @@ package org.apache.poi.examples.xslf;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream; 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.ArrayList;
import java.util.List; import java.util.List;
@ -59,7 +61,7 @@ public final class PieChartDemo {
} }
try (FileInputStream argIS = new FileInputStream(args[0]); 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 chartTitle = modelReader.readLine(); // first line is chart title
try (XMLSlideShow pptx = new XMLSlideShow(argIS)) { try (XMLSlideShow pptx = new XMLSlideShow(argIS)) {

View File

@ -40,6 +40,7 @@ import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellReference; 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.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataFormat; import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFFont; 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 { 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); SpreadsheetWriter sw = new SpreadsheetWriter(out);
sw.beginSheet(); sw.beginSheet();

View File

@ -28,6 +28,7 @@ import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.PrintOrientation; import org.apache.poi.ss.usermodel.PrintOrientation;
import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress; 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.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFColor;
@ -61,7 +62,7 @@ public class CalendarDemo {
public static void main(String[] args) throws Exception { 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])); if(args.length > 0) calendar.set(Calendar.YEAR, Integer.parseInt(args[0]));
int year = calendar.get(Calendar.YEAR); int year = calendar.get(Calendar.YEAR);

View File

@ -31,6 +31,7 @@ import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference; import org.apache.poi.ss.util.CellReference;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.XSSFPivotTable; import org.apache.poi.xssf.usermodel.XSSFPivotTable;
import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@ -67,9 +68,9 @@ public class CreatePivotTable2 {
} }
public static void setCellData(XSSFSheet sheet){ public static void setCellData(XSSFSheet sheet){
Calendar cal1 = Calendar.getInstance(); Calendar cal1 = LocaleUtil.getLocaleCalendar();
cal1.set(2017, 0, 1, 0, 0, 0); cal1.set(2017, 0, 1, 0, 0, 0);
Calendar cal2 = Calendar.getInstance(); Calendar cal2 = LocaleUtil.getLocaleCalendar();
cal2.set(2017, 1, 1, 0, 0, 0); cal2.set(2017, 1, 1, 0, 0, 0);
Row row1 = sheet.createRow(0); Row row1 = sheet.createRow(0);
// Create a cell and put a value in it. // Create a cell and put a value in it.

View File

@ -23,8 +23,10 @@ package org.apache.poi.examples.xwpf.usermodel;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream; 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.ArrayList;
import java.util.List; import java.util.List;
@ -61,7 +63,7 @@ public final class BarChartExample {
} }
try (FileInputStream argIS = new FileInputStream(args[0]); 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 chartTitle = modelReader.readLine(); // first line is chart title
String[] series = modelReader.readLine().split(","); String[] series = modelReader.readLine().split(",");

View File

@ -21,8 +21,10 @@ package org.apache.poi.examples.xwpf.usermodel;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream; 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.ArrayList;
import java.util.List; import java.util.List;
@ -65,7 +67,7 @@ public final class ChartFromScratch {
return; 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 chartTitle = modelReader.readLine(); // first line is chart title
String[] series = modelReader.readLine().split(","); String[] series = modelReader.readLine().split(",");

View File

@ -28,6 +28,7 @@ import java.io.File;
import java.io.PrintStream; import java.io.PrintStream;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.util.NullPrintStream;
import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildListener; import org.apache.tools.ant.BuildListener;
@ -140,12 +141,8 @@ public class TestBuildFile {
try { try {
sysOut.flush(); sysOut.flush();
sysErr.flush(); sysErr.flush();
StringBuilder outBuffer = new StringBuilder(); System.setOut(new NullPrintStream());
PrintStream out = new PrintStream(new AntOutputStream(outBuffer)); System.setErr(new NullPrintStream());
System.setOut(out);
StringBuilder errBuffer = new StringBuilder();
PrintStream err = new PrintStream(new AntOutputStream(errBuffer));
System.setErr(err);
logBuffer = new StringBuilder(); logBuffer = new StringBuilder();
fullLogBuffer = new StringBuilder(); fullLogBuffer = new StringBuilder();
buildException = null; buildException = null;

View File

@ -104,7 +104,7 @@ public class HPSFFileHandler extends POIFSFileHandler {
} }
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintStream psNew = new PrintStream(bos); PrintStream psNew = new PrintStream(bos, true, "ISO-8859-1");
PrintStream ps = System.out; PrintStream ps = System.out;
try { try {
System.setOut(psNew); System.setOut(psNew);

View File

@ -22,7 +22,6 @@ import static org.junit.Assert.assertNotNull;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; 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.Cell;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.util.NullPrintStream;
import org.junit.Test; import org.junit.Test;
public class HSSFFileHandler extends SpreadsheetHandler { public class HSSFFileHandler extends SpreadsheetHandler {
@ -88,11 +88,7 @@ public class HSSFFileHandler extends SpreadsheetHandler {
PrintStream oldOut = System.out; PrintStream oldOut = System.out;
String fileWithParent = file.getParentFile().getName() + "/" + file.getName(); String fileWithParent = file.getParentFile().getName() + "/" + file.getName();
try { try {
System.setOut(new PrintStream(new OutputStream() { System.setOut(new NullPrintStream());
@Override
public void write(int b) {
}
}));
BiffViewer.main(new String[]{file.getAbsolutePath()}); BiffViewer.main(new String[]{file.getAbsolutePath()});

View File

@ -20,7 +20,9 @@ import java.io.IOException;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import com.sun.management.HotSpotDiagnosticMXBean; import com.sun.management.HotSpotDiagnosticMXBean;
import org.apache.poi.util.SuppressForbidden;
@SuppressForbidden("class only exists for manual tests in XSSFFileHandler")
public class HeapDump { public class HeapDump {
// This is the name of the HotSpot Diagnostic MBean // This is the name of the HotSpot Diagnostic MBean
private static final String HOTSPOT_BEAN_NAME = private static final String HOTSPOT_BEAN_NAME =

View File

@ -28,11 +28,9 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Locale;
import java.util.Set; import java.util.Set;
import javax.xml.transform.TransformerException; 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.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils; import org.apache.poi.util.IOUtils;
import org.apache.poi.util.NullPrintStream;
import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.extractor.XSSFExportToXml; import org.apache.poi.xssf.extractor.XSSFExportToXml;
import org.apache.poi.xssf.usermodel.XSSFMap; import org.apache.poi.xssf.usermodel.XSSFMap;
@ -221,77 +220,4 @@ public class XSSFFileHandler extends SpreadsheetHandler {
public void testAdditional() throws Exception { public void testAdditional() throws Exception {
handleAdditional(new File("test-data/spreadsheet/poc-xmlbomb.xlsx")); 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) {}
}
} }

View File

@ -417,10 +417,8 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
private static void saveTwice(Workbook wb) throws Exception { private static void saveTwice(Workbook wb) throws Exception {
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
try { try (NullOutputStream out = new NullOutputStream()) {
NullOutputStream out = new NullOutputStream();
wb.write(out); wb.write(out);
out.close();
} catch (Exception e) { } catch (Exception e) {
throw new Exception("ERROR: failed on " + (i + 1) throw new Exception("ERROR: failed on " + (i + 1)
+ "th time calling " + wb.getClass().getName() + "th time calling " + wb.getClass().getName()

View File

@ -17,7 +17,7 @@
# This file contains API signatures which are specific to POI. # This file contains API signatures which are specific to POI.
# The goal is to minimize implicit defaults # 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... # We have applications which use this to return error codes on invalid commandline parameters...
#@defaultMessage Please do not terminate the application #@defaultMessage Please do not terminate the application

View File

@ -24,7 +24,7 @@ import java.io.File;
import java.io.PrintStream; import java.io.PrintStream;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.util.NullOutputStream; import org.apache.poi.util.NullPrintStream;
import org.junit.Test; import org.junit.Test;
public class TestHMEFDumper { public class TestHMEFDumper {
@ -48,7 +48,7 @@ public class TestHMEFDumper {
private static void doMain(String... args) throws Exception { private static void doMain(String... args) throws Exception {
PrintStream ps = System.out; PrintStream ps = System.out;
try { try {
System.setOut(new PrintStream(new NullOutputStream(), true, "UTF-8")); System.setOut(new NullPrintStream());
HMEFDumper.main(args); HMEFDumper.main(args);
} finally { } finally {
System.setOut(ps); System.setOut(ps);

View File

@ -16,22 +16,9 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.hslf.dev; package org.apache.poi.hslf.dev;
import org.apache.poi.POIDataSamples; import static org.junit.Assert.assertNotNull;
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 java.io.File; import java.io.File;
import java.io.OutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.ArrayList; import java.util.ArrayList;
@ -42,12 +29,21 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; 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) @RunWith(Parameterized.class)
public abstract class BasePPTIteratingTest { public abstract class BasePPTIteratingTest {
protected static final OutputStream NULL_OUTPUT_STREAM = new NullOutputStream();
protected static final Set<String> OLD_FILES = new HashSet<>(); protected static final Set<String> OLD_FILES = new HashSet<>();
static { static {
OLD_FILES.add("PPT95.ppt"); OLD_FILES.add("PPT95.ppt");
@ -89,7 +85,7 @@ public abstract class BasePPTIteratingTest {
IOUtils.setByteArrayMaxOverride(5*1024*1024); IOUtils.setByteArrayMaxOverride(5*1024*1024);
// redirect standard out during the test to avoid spamming the console with output // 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 @After

View File

@ -35,16 +35,17 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.text.AttributedCharacterIterator; import java.text.AttributedCharacterIterator;
import java.text.AttributedCharacterIterator.Attribute; import java.text.AttributedCharacterIterator.Attribute;
import java.text.CharacterIterator; import java.text.CharacterIterator;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; 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.model.HeadersFooters;
import org.apache.poi.hslf.record.DocInfoListContainer; import org.apache.poi.hslf.record.DocInfoListContainer;
import org.apache.poi.hslf.record.Document; 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.RecordTypes;
import org.apache.poi.hslf.record.SlideListWithText; import org.apache.poi.hslf.record.SlideListWithText;
import org.apache.poi.hslf.record.SlideListWithText.SlideAtomsSet; 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.sl.usermodel.TextRun;
import org.apache.poi.util.IOUtils; import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.NullPrintStream;
import org.apache.poi.util.StringUtil; import org.apache.poi.util.StringUtil;
import org.apache.poi.util.Units; import org.apache.poi.util.Units;
import org.junit.Test; import org.junit.Test;
@ -463,7 +464,8 @@ public final class TestBugs {
*/ */
@Test @Test
public void bug45776() throws IOException { 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 // get slides
for (HSLFSlide slide : ppt.getSlides()) { for (HSLFSlide slide : ppt.getSlides()) {
@ -478,7 +480,7 @@ public final class TestBugs {
if (!str.contains("$$DATE$$")) { if (!str.contains("$$DATE$$")) {
continue; continue;
} }
str = str.replace("$$DATE$$", new Date().toString()); str = str.replace("$$DATE$$", df.format(new Date()));
tb.setText(str); tb.setText(str);
List<HSLFTextParagraph> tr = tb.getTextParagraphs(); List<HSLFTextParagraph> tr = tb.getTextParagraphs();
@ -487,7 +489,7 @@ public final class TestBugs {
} }
} }
ppt.close(); }
} }
@Test @Test
@ -873,13 +875,8 @@ public final class TestBugs {
assertEquals(hlRun.getStartIndex(), hlShape.getStartIndex()); assertEquals(hlRun.getStartIndex(), hlShape.getStartIndex());
assertEquals(hlRun.getEndIndex(), hlShape.getEndIndex()); assertEquals(hlRun.getEndIndex(), hlShape.getEndIndex());
OutputStream nullOutput = new OutputStream(){
@Override
public void write(int b) throws IOException {}
};
final boolean[] found = {false}; final boolean[] found = {false};
DummyGraphics2d dgfx = new DummyGraphics2d(new PrintStream(nullOutput)){ DummyGraphics2d dgfx = new DummyGraphics2d(new NullPrintStream()){
@Override @Override
public void drawString(AttributedCharacterIterator iterator, float x, float y) { public void drawString(AttributedCharacterIterator iterator, float x, float y) {
// For the test file, common sl draws textruns one by one and not mixed // For the test file, common sl draws textruns one by one and not mixed

View File

@ -44,6 +44,7 @@ import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.Entry; import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.EntryUtils; import org.apache.poi.poifs.filesystem.EntryUtils;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.LocaleUtil;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
@ -102,7 +103,7 @@ public class TestExtractEmbeddedMSG {
msg.setReturnNullOnMissingChunk(true); msg.setReturnNullOnMissingChunk(true);
Calendar messageDate = msg.getMessageDate(); Calendar messageDate = msg.getMessageDate();
assertNotNull(messageDate); 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.set(2010, 05, 17, 23, 52, 19); // 2010/06/17 23:52:19 GMT
expectedMessageDate.setTimeZone(TimeZone.getTimeZone("GMT")); expectedMessageDate.setTimeZone(TimeZone.getTimeZone("GMT"));
expectedMessageDate.set(Calendar.MILLISECOND, 0); expectedMessageDate.set(Calendar.MILLISECOND, 0);

View File

@ -168,7 +168,7 @@ public final class TestFixedSizedProperties {
*/ */
@Test @Test
public void testReadMessageDateSucceedsWithHSMFDump() throws IOException { 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); HSMFDump dump = new HSMFDump(fsMessageSucceeds);
dump.dump(stream); dump.dump(stream);
} }
@ -178,7 +178,7 @@ public final class TestFixedSizedProperties {
*/ */
@Test @Test
public void testReadMessageDateFailsWithHSMFDump() throws Exception { 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); HSMFDump dump = new HSMFDump(fsMessageFails);
dump.dump(stream); dump.dump(stream);
} }

View File

@ -20,7 +20,6 @@ import static org.junit.Assert.assertNotNull;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -29,7 +28,6 @@ import java.util.Map;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.util.NullOutputStream;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
@ -46,8 +44,6 @@ import org.junit.runners.Parameterized.Parameters;
*/ */
@RunWith(Parameterized.class) @RunWith(Parameterized.class)
public abstract class BaseTestIteratingXLS { public abstract class BaseTestIteratingXLS {
protected static final OutputStream NULL_OUTPUT_STREAM = new NullOutputStream();
@Rule @Rule
public ExpectedException thrown = ExpectedException.none(); public ExpectedException thrown = ExpectedException.none();

View File

@ -23,6 +23,7 @@ import java.io.InputStream;
import org.apache.poi.EncryptedDocumentException; import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.OldExcelFormatException; import org.apache.poi.hssf.OldExcelFormatException;
import org.apache.poi.hssf.record.RecordInputStream; import org.apache.poi.hssf.record.RecordInputStream;
import org.apache.poi.util.NullOutputStream;
import org.apache.poi.util.RecordFormatException; import org.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass; import org.junit.BeforeClass;
@ -51,7 +52,7 @@ public class TestBiffDrawingToXml extends BaseTestIteratingXLS {
@Override @Override
void runOneFile(File pFile) throws Exception { void runOneFile(File pFile) throws Exception {
try (InputStream wb = new FileInputStream(pFile)) { 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]);
} }
} }
} }

View File

@ -28,6 +28,7 @@ import org.apache.poi.hssf.OldExcelFormatException;
import org.apache.poi.hssf.record.RecordInputStream; import org.apache.poi.hssf.record.RecordInputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.LocaleUtil;
import org.apache.poi.util.NullOutputStream;
import org.apache.poi.util.RecordFormatException; import org.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Ignore; import org.junit.Ignore;
@ -62,7 +63,7 @@ public class TestBiffViewer extends BaseTestIteratingXLS {
try (POIFSFileSystem fs = new POIFSFileSystem(fileIn, true); try (POIFSFileSystem fs = new POIFSFileSystem(fileIn, true);
InputStream is = BiffViewer.getPOIFSInputStream(fs)) { InputStream is = BiffViewer.getPOIFSInputStream(fs)) {
// use a NullOutputStream to not write the bytes anywhere for best runtime // 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); BiffViewer.runBiffViewer(dummy, is, true, true, true, false);
} }
} }

View File

@ -23,7 +23,7 @@ import java.io.PrintStream;
import org.apache.poi.EncryptedDocumentException; import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.OldExcelFormatException; import org.apache.poi.hssf.OldExcelFormatException;
import org.apache.poi.hssf.record.RecordInputStream; 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.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass; import org.junit.BeforeClass;
@ -45,7 +45,7 @@ public class TestEFBiffViewer extends BaseTestIteratingXLS {
EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 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("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well
EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); 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("61300.xls", RecordFormatException.class);
EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5 EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5
} }
@ -55,7 +55,7 @@ public class TestEFBiffViewer extends BaseTestIteratingXLS {
PrintStream save = System.out; PrintStream save = System.out;
try { try {
// redirect standard out during the test to avoid spamming the console with output // 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() }); EFBiffViewer.main(new String[] { fileIn.getAbsolutePath() });
} finally { } finally {

View File

@ -24,7 +24,7 @@ import java.io.PrintStream;
import org.apache.poi.EncryptedDocumentException; import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.OldExcelFormatException; import org.apache.poi.hssf.OldExcelFormatException;
import org.apache.poi.hssf.record.RecordInputStream; 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.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass; import org.junit.BeforeClass;
@ -55,7 +55,7 @@ public class TestFormulaViewer extends BaseTestIteratingXLS {
PrintStream save = System.out; PrintStream save = System.out;
try { try {
// redirect standard out during the test to avoid spamming the console with output // 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(); FormulaViewer viewer = new FormulaViewer();
viewer.setFile(fileIn.getAbsolutePath()); viewer.setFile(fileIn.getAbsolutePath());

View File

@ -25,7 +25,7 @@ import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.POIDataSamples; import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.OldExcelFormatException; import org.apache.poi.hssf.OldExcelFormatException;
import org.apache.poi.hssf.record.RecordInputStream; 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.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Ignore; import org.junit.Ignore;
@ -64,7 +64,7 @@ public class TestReSave extends BaseTestIteratingXLS {
PrintStream save = System.out; PrintStream save = System.out;
try { try {
// redirect standard out during the test to avoid spamming the console with output // 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")); File reSavedFile = new File(fileIn.getParentFile(), fileIn.getName().replace(".xls", "-saved.xls"));
try { try {

View File

@ -21,7 +21,7 @@ import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import org.apache.poi.hssf.OldExcelFormatException; 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.apache.poi.util.RecordFormatException;
import org.junit.BeforeClass; import org.junit.BeforeClass;
@ -46,7 +46,7 @@ public class TestRecordLister extends BaseTestIteratingXLS {
PrintStream save = System.out; PrintStream save = System.out;
try { try {
// redirect standard out during the test to avoid spamming the console with output // 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(); RecordLister viewer = new RecordLister();
viewer.setFile(fileIn.getAbsolutePath()); viewer.setFile(fileIn.getAbsolutePath());

View File

@ -26,8 +26,6 @@ import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.ConcurrentModificationException; 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.CellAddress;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.NullOutputStream; import org.apache.poi.util.NullOutputStream;
import org.apache.poi.util.TempFile; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
public abstract class BaseTestWorkbook { public abstract class BaseTestWorkbook {
@ -50,9 +49,13 @@ public abstract class BaseTestWorkbook {
_testDataProvider = testDataProvider; _testDataProvider = testDataProvider;
} }
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test @Test
public void sheetIterator_forEach() throws IOException { public void sheetIterator_forEach() throws IOException {
final Workbook wb = _testDataProvider.createWorkbook(); try (Workbook wb = _testDataProvider.createWorkbook()) {
wb.createSheet("Sheet0"); wb.createSheet("Sheet0");
wb.createSheet("Sheet1"); wb.createSheet("Sheet1");
wb.createSheet("Sheet2"); wb.createSheet("Sheet2");
@ -61,7 +64,7 @@ public abstract class BaseTestWorkbook {
assertEquals("Sheet" + i, sh.getSheetName()); assertEquals("Sheet" + i, sh.getSheetName());
i++; i++;
} }
wb.close(); }
} }
/** /**
@ -71,7 +74,7 @@ public abstract class BaseTestWorkbook {
*/ */
@Test(expected=ConcurrentModificationException.class) @Test(expected=ConcurrentModificationException.class)
public void sheetIterator_sheetsReordered() throws IOException { public void sheetIterator_sheetsReordered() throws IOException {
final Workbook wb = _testDataProvider.createWorkbook(); try (Workbook wb = _testDataProvider.createWorkbook()) {
wb.createSheet("Sheet0"); wb.createSheet("Sheet0");
wb.createSheet("Sheet1"); wb.createSheet("Sheet1");
wb.createSheet("Sheet2"); wb.createSheet("Sheet2");
@ -81,10 +84,7 @@ public abstract class BaseTestWorkbook {
wb.setSheetOrder("Sheet2", 1); wb.setSheetOrder("Sheet2", 1);
// Iterator order should be fixed when iterator is created // Iterator order should be fixed when iterator is created
try {
assertEquals("Sheet1", it.next().getSheetName()); assertEquals("Sheet1", it.next().getSheetName());
} finally {
wb.close();
} }
} }
@ -95,7 +95,7 @@ public abstract class BaseTestWorkbook {
*/ */
@Test(expected=ConcurrentModificationException.class) @Test(expected=ConcurrentModificationException.class)
public void sheetIterator_sheetRemoved() throws IOException { public void sheetIterator_sheetRemoved() throws IOException {
final Workbook wb = _testDataProvider.createWorkbook(); try (Workbook wb = _testDataProvider.createWorkbook()) {
wb.createSheet("Sheet0"); wb.createSheet("Sheet0");
wb.createSheet("Sheet1"); wb.createSheet("Sheet1");
wb.createSheet("Sheet2"); wb.createSheet("Sheet2");
@ -104,10 +104,7 @@ public abstract class BaseTestWorkbook {
wb.removeSheetAt(1); wb.removeSheetAt(1);
// Iterator order should be fixed when iterator is created // Iterator order should be fixed when iterator is created
try {
it.next(); it.next();
} finally {
wb.close();
} }
} }
@ -117,22 +114,19 @@ public abstract class BaseTestWorkbook {
*/ */
@Test(expected=UnsupportedOperationException.class) @Test(expected=UnsupportedOperationException.class)
public void sheetIterator_remove() throws IOException { public void sheetIterator_remove() throws IOException {
final Workbook wb = _testDataProvider.createWorkbook(); try (Workbook wb = _testDataProvider.createWorkbook()) {
wb.createSheet("Sheet0"); wb.createSheet("Sheet0");
Iterator<Sheet> it = wb.sheetIterator(); Iterator<Sheet> it = wb.sheetIterator();
it.next(); //Sheet0 it.next(); //Sheet0
try {
it.remove(); it.remove();
} finally {
wb.close();
} }
} }
@Test @Test
public void createSheet() throws IOException { public void createSheet() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); try (Workbook wb = _testDataProvider.createWorkbook()) {
assertEquals(0, wb.getNumberOfSheets()); assertEquals(0, wb.getNumberOfSheets());
//getting a sheet by invalid index or non-existing name //getting a sheet by invalid index or non-existing name
@ -222,13 +216,13 @@ public abstract class BaseTestWorkbook {
assertNull(wb.getSheet("unknown")); assertNull(wb.getSheet("unknown"));
//serialize and read again //serialize and read again
Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb); try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb)) {
wb.close();
assertEquals(3, wb2.getNumberOfSheets()); assertEquals(3, wb2.getNumberOfSheets());
assertEquals(0, wb2.getSheetIndex("sheet0")); assertEquals(0, wb2.getSheetIndex("sheet0"));
assertEquals(1, wb2.getSheetIndex("sheet1")); assertEquals(1, wb2.getSheetIndex("sheet1"));
assertEquals(2, wb2.getSheetIndex("I changed!")); assertEquals(2, wb2.getSheetIndex("I changed!"));
wb2.close(); }
}
} }
/** /**
@ -241,7 +235,7 @@ public abstract class BaseTestWorkbook {
*/ */
@Test @Test
public void createSheetWithLongNames() throws IOException { public void createSheetWithLongNames() throws IOException {
Workbook wb1 = _testDataProvider.createWorkbook(); try (Workbook wb1 = _testDataProvider.createWorkbook()) {
String sheetName1 = "My very long sheet name which is longer than 31 chars"; String sheetName1 = "My very long sheet name which is longer than 31 chars";
String truncatedSheetName1 = sheetName1.substring(0, 31); String truncatedSheetName1 = sheetName1.substring(0, 31);
@ -256,7 +250,8 @@ public abstract class BaseTestWorkbook {
String sheetName2 = "My very long sheet name which is longer than 31 chars " + String sheetName2 = "My very long sheet name which is longer than 31 chars " +
"and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)"; "and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)";
try { try {
/*Sheet sh2 =*/ wb1.createSheet(sheetName2); /*Sheet sh2 =*/
wb1.createSheet(sheetName2);
fail("expected exception"); fail("expected exception");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// expected during successful test // expected during successful test
@ -270,12 +265,12 @@ public abstract class BaseTestWorkbook {
assertSame(sh3, wb1.getSheet(truncatedSheetName3)); assertSame(sh3, wb1.getSheet(truncatedSheetName3));
//serialize and read again //serialize and read again
Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
wb1.close();
assertEquals(2, wb2.getNumberOfSheets()); assertEquals(2, wb2.getNumberOfSheets());
assertEquals(0, wb2.getSheetIndex(truncatedSheetName1)); assertEquals(0, wb2.getSheetIndex(truncatedSheetName1));
assertEquals(1, wb2.getSheetIndex(truncatedSheetName3)); assertEquals(1, wb2.getSheetIndex(truncatedSheetName3));
wb2.close(); }
}
} }
@Test @Test
@ -339,24 +334,22 @@ public abstract class BaseTestWorkbook {
Workbook wbr = _testDataProvider.writeOutAndReadBack(wb); Workbook wbr = _testDataProvider.writeOutAndReadBack(wb);
sheet = wbr.getSheet("new sheet"); sheet = wbr.getSheet("new sheet");
assertEquals(new CellAddress("E11"), sheet.getActiveCell()); assertEquals(new CellAddress("E11"), sheet.getActiveCell());
//wbr.write(new FileOutputStream("c:/temp/yyy." + _testDataProvider.getStandardFileNameExtension()));
} }
} }
@Test @Test
public void defaultValues() throws IOException { public void defaultValues() throws IOException {
Workbook b = _testDataProvider.createWorkbook(); try (Workbook b = _testDataProvider.createWorkbook()) {
assertEquals(0, b.getActiveSheetIndex()); assertEquals(0, b.getActiveSheetIndex());
assertEquals(0, b.getFirstVisibleTab()); assertEquals(0, b.getFirstVisibleTab());
assertEquals(0, b.getNumberOfNames()); assertEquals(0, b.getNumberOfNames());
assertEquals(0, b.getNumberOfSheets()); assertEquals(0, b.getNumberOfSheets());
b.close(); }
} }
@Test @Test
public void sheetSelection() throws IOException { public void sheetSelection() throws IOException {
Workbook b = _testDataProvider.createWorkbook(); try (Workbook b = _testDataProvider.createWorkbook()) {
b.createSheet("Sheet One"); b.createSheet("Sheet One");
b.createSheet("Sheet Two"); b.createSheet("Sheet Two");
b.setActiveSheet(1); b.setActiveSheet(1);
@ -364,12 +357,12 @@ public abstract class BaseTestWorkbook {
b.setFirstVisibleTab(1); b.setFirstVisibleTab(1);
assertEquals(1, b.getActiveSheetIndex()); assertEquals(1, b.getActiveSheetIndex());
assertEquals(1, b.getFirstVisibleTab()); assertEquals(1, b.getFirstVisibleTab());
b.close(); }
} }
@Test @Test
public void printArea() throws IOException { public void printArea() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); try (Workbook workbook = _testDataProvider.createWorkbook()) {
Sheet sheet1 = workbook.createSheet("Test Print Area"); Sheet sheet1 = workbook.createSheet("Test Print Area");
String sheetName1 = sheet1.getSheetName(); String sheetName1 = sheet1.getSheetName();
@ -385,12 +378,12 @@ public abstract class BaseTestWorkbook {
workbook.removePrintArea(0); workbook.removePrintArea(0);
assertNull(workbook.getPrintArea(0)); assertNull(workbook.getPrintArea(0));
workbook.close(); }
} }
@Test @Test
public void getSetActiveSheet() throws IOException { public void getSetActiveSheet() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); try (Workbook workbook = _testDataProvider.createWorkbook()) {
assertEquals(0, workbook.getActiveSheetIndex()); assertEquals(0, workbook.getActiveSheetIndex());
workbook.createSheet("sheet1"); workbook.createSheet("sheet1");
@ -404,12 +397,12 @@ public abstract class BaseTestWorkbook {
workbook.setActiveSheet(0); workbook.setActiveSheet(0);
// test if second sheet is set up // test if second sheet is set up
assertEquals(0, workbook.getActiveSheetIndex()); assertEquals(0, workbook.getActiveSheetIndex());
workbook.close(); }
} }
@Test @Test
public void setSheetOrder() throws IOException { public void setSheetOrder() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); try (Workbook wb = _testDataProvider.createWorkbook()) {
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
wb.createSheet("Sheet " + i); wb.createSheet("Sheet " + i);
@ -451,8 +444,7 @@ public abstract class BaseTestWorkbook {
assertEquals(8, wb.getSheetIndex("Sheet 9")); assertEquals(8, wb.getSheetIndex("Sheet 9"));
assertEquals(9, wb.getSheetIndex("Sheet 1")); assertEquals(9, wb.getSheetIndex("Sheet 1"));
Workbook wbr = _testDataProvider.writeOutAndReadBack(wb); try (Workbook wbr = _testDataProvider.writeOutAndReadBack(wb)) {
wb.close();
assertEquals(0, wbr.getSheetIndex("Sheet 6")); assertEquals(0, wbr.getSheetIndex("Sheet 6"));
assertEquals(1, wbr.getSheetIndex("Sheet 0")); assertEquals(1, wbr.getSheetIndex("Sheet 0"));
@ -472,13 +464,13 @@ public abstract class BaseTestWorkbook {
Sheet s = wbr.getSheetAt(i); Sheet s = wbr.getSheetAt(i);
assertEquals(i, wbr.getSheetIndex(s)); assertEquals(i, wbr.getSheetIndex(s));
} }
}
wbr.close(); }
} }
@Test @Test
public void cloneSheet() throws IOException { public void cloneSheet() throws IOException {
Workbook book = _testDataProvider.createWorkbook(); try (Workbook book = _testDataProvider.createWorkbook()) {
Sheet sheet = book.createSheet("TEST"); Sheet sheet = book.createSheet("TEST");
sheet.createRow(0).createCell(0).setCellValue("Test"); sheet.createRow(0).createCell(0).setCellValue("Test");
sheet.createRow(1).createCell(0).setCellValue(36.6); sheet.createRow(1).createCell(0).setCellValue(36.6);
@ -502,12 +494,12 @@ public abstract class BaseTestWorkbook {
assertEquals(2, clonedSheet.addMergedRegion(new CellRangeAddress(6, 7, 0, 2))); assertEquals(2, clonedSheet.addMergedRegion(new CellRangeAddress(6, 7, 0, 2)));
assertEquals(3, clonedSheet.getPhysicalNumberOfRows()); assertEquals(3, clonedSheet.getPhysicalNumberOfRows());
assertEquals(3, clonedSheet.getNumMergedRegions()); assertEquals(3, clonedSheet.getNumMergedRegions());
book.close(); }
} }
@Test @Test
public void parentReferences() throws IOException { public void parentReferences() throws IOException {
Workbook wb1 = _testDataProvider.createWorkbook(); try (Workbook wb1 = _testDataProvider.createWorkbook()) {
Sheet sheet = wb1.createSheet(); Sheet sheet = wb1.createSheet();
assertSame(wb1, sheet.getWorkbook()); assertSame(wb1, sheet.getWorkbook());
@ -518,7 +510,7 @@ public abstract class BaseTestWorkbook {
assertSame(sheet, cell.getSheet()); assertSame(sheet, cell.getSheet());
assertSame(row, cell.getRow()); assertSame(row, cell.getRow());
Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
wb1.close(); wb1.close();
sheet = wb2.getSheetAt(0); sheet = wb2.getSheetAt(0);
assertSame(wb2, sheet.getWorkbook()); assertSame(wb2, sheet.getWorkbook());
@ -529,7 +521,8 @@ public abstract class BaseTestWorkbook {
cell = row.getCell(1); cell = row.getCell(1);
assertSame(sheet, cell.getSheet()); assertSame(sheet, cell.getSheet());
assertSame(row, cell.getRow()); assertSame(row, cell.getRow());
wb2.close(); }
}
} }
@ -539,8 +532,7 @@ public abstract class BaseTestWorkbook {
*/ */
@Test @Test
public void setRepeatingRowsAnsColumns() throws IOException { public void setRepeatingRowsAnsColumns() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); try (Workbook wb = _testDataProvider.createWorkbook()) {
CellRangeAddress cra = new CellRangeAddress(0, 3, 0, 0); CellRangeAddress cra = new CellRangeAddress(0, 3, 0, 0);
String expRows = "1:4", expCols = "A:A"; String expRows = "1:4", expCols = "A:A";
@ -557,7 +549,7 @@ public abstract class BaseTestWorkbook {
sheet2.setRepeatingColumns(cra); sheet2.setRepeatingColumns(cra);
assertEquals(expRows, sheet2.getRepeatingRows().formatAsString()); assertEquals(expRows, sheet2.getRepeatingRows().formatAsString());
assertEquals(expCols, sheet2.getRepeatingColumns().formatAsString()); assertEquals(expCols, sheet2.getRepeatingColumns().formatAsString());
wb.close(); }
} }
/** /**
@ -565,7 +557,7 @@ public abstract class BaseTestWorkbook {
*/ */
@Test @Test
public void unicodeInAll() throws IOException { public void unicodeInAll() throws IOException {
Workbook wb1 = _testDataProvider.createWorkbook(); try (Workbook wb1 = _testDataProvider.createWorkbook()) {
CreationHelper factory = wb1.getCreationHelper(); CreationHelper factory = wb1.getCreationHelper();
//Create a unicode dataformat (contains euro symbol) //Create a unicode dataformat (contains euro symbol)
DataFormat df = wb1.createDataFormat(); DataFormat df = wb1.createDataFormat();
@ -592,16 +584,15 @@ public abstract class BaseTestWorkbook {
c.setCellValue(12.34); c.setCellValue(12.34);
c.getCellStyle().setDataFormat(fmt); c.getCellStyle().setDataFormat(fmt);
/*Cell c2 =*/ r.createCell(2); // TODO - c2 unused but changing next line ('c'->'c2') causes test to fail /*Cell c2 =*/
r.createCell(2); // TODO - c2 unused but changing next line ('c'->'c2') causes test to fail
c.setCellValue(factory.createRichTextString("\u20ac")); c.setCellValue(factory.createRichTextString("\u20ac"));
Cell c3 = r.createCell(3); Cell c3 = r.createCell(3);
String formulaString = "TEXT(12.34,\"\u20ac###,##\")"; String formulaString = "TEXT(12.34,\"\u20ac###,##\")";
c3.setCellFormula(formulaString); c3.setCellFormula(formulaString);
Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
wb1.close();
//Test the sheetname //Test the sheetname
s = wb2.getSheet("\u20ac"); s = wb2.getSheet("\u20ac");
assertNotNull(s); assertNotNull(s);
@ -625,13 +616,15 @@ public abstract class BaseTestWorkbook {
assertEquals(formatStr, df.getFormat(c.getCellStyle().getDataFormat())); assertEquals(formatStr, df.getFormat(c.getCellStyle().getDataFormat()));
//Test the cell string value //Test the cell string value
/*c2 =*/ r.getCell(2); /*c2 =*/
r.getCell(2);
assertEquals(c.getRichStringCellValue().getString(), "\u20ac"); assertEquals(c.getRichStringCellValue().getString(), "\u20ac");
//Test the cell formula //Test the cell formula
c3 = r.getCell(3); c3 = r.getCell(3);
assertEquals(c3.getCellFormula(), formulaString); assertEquals(c3.getCellFormula(), formulaString);
wb2.close(); }
}
} }
private Workbook newSetSheetNameTestingWorkbook() { private Workbook newSetSheetNameTestingWorkbook() {
@ -671,7 +664,6 @@ public abstract class BaseTestWorkbook {
sh3.createRow(4).createCell(0).setCellValue(5); sh3.createRow(4).createCell(0).setCellValue(5);
sh3.createRow(5).createCell(0).setCellFormula("sale_3"); sh3.createRow(5).createCell(0).setCellFormula("sale_3");
sh3.createRow(6).createCell(0).setCellFormula("'Testing 47100'!C1"); sh3.createRow(6).createCell(0).setCellFormula("'Testing 47100'!C1");
return wb; return wb;
} }
@ -682,9 +674,7 @@ public abstract class BaseTestWorkbook {
*/ */
@Test @Test
public void setSheetName() throws IOException { public void setSheetName() throws IOException {
try (Workbook wb1 = newSetSheetNameTestingWorkbook()) {
Workbook wb1 = newSetSheetNameTestingWorkbook();
Sheet sh1 = wb1.getSheetAt(0); Sheet sh1 = wb1.getSheetAt(0);
Name sale_2 = wb1.getName("sale_2"); Name sale_2 = wb1.getName("sale_2");
@ -731,9 +721,7 @@ public abstract class BaseTestWorkbook {
assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0);
assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0);
Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
wb1.close();
sh1 = wb2.getSheetAt(0); sh1 = wb2.getSheetAt(0);
sale_2 = wb2.getName("sale_2"); sale_2 = wb2.getName("sale_2");
@ -759,11 +747,12 @@ public abstract class BaseTestWorkbook {
assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0); assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0);
assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0);
assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0);
wb2.close(); }
}
} }
protected void changeSheetNameWithSharedFormulas(String sampleFile) throws IOException { 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();
@ -785,7 +774,7 @@ public abstract class BaseTestWorkbook {
assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue()); assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue());
} }
wb.close(); }
} }
protected void assertSheetOrder(Workbook wb, String... sheets) { protected void assertSheetOrder(Workbook wb, String... sheets) {
@ -803,7 +792,8 @@ public abstract class BaseTestWorkbook {
@Test @Test
public void test58499() throws IOException { public void test58499() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); try (Workbook workbook = _testDataProvider.createWorkbook();
OutputStream os = new NullOutputStream()) {
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
for (int i = 0; i < 900; i++) { for (int i = 0; i < 900; i++) {
Row r = sheet.createRow(i); Row r = sheet.createRow(i);
@ -812,32 +802,25 @@ public abstract class BaseTestWorkbook {
c.setCellStyle(cs); c.setCellStyle(cs);
c.setCellValue("AAA"); c.setCellValue("AAA");
} }
try (OutputStream os = new NullOutputStream()) {
workbook.write(os); workbook.write(os);
} }
//workbook.dispose();
workbook.close();
} }
@Test @Test
public void windowOneDefaults() throws IOException { public void windowOneDefaults() throws IOException {
Workbook b = _testDataProvider.createWorkbook(); try (Workbook b = _testDataProvider.createWorkbook()) {
try {
assertEquals(b.getActiveSheetIndex(), 0); assertEquals(b.getActiveSheetIndex(), 0);
assertEquals(b.getFirstVisibleTab(), 0); assertEquals(b.getFirstVisibleTab(), 0);
} catch (NullPointerException npe) { // throws NullPointerException when WindowOneRecord in Workbook is not probably initialized
fail("WindowOneRecord in Workbook is probably not initialized");
} }
b.close();
} }
@Test @Test
public void getSpreadsheetVersion() throws IOException { public void getSpreadsheetVersion() throws IOException {
final Workbook wb = _testDataProvider.createWorkbook(); try (Workbook wb = _testDataProvider.createWorkbook()) {
assertEquals(_testDataProvider.getSpreadsheetVersion(), wb.getSpreadsheetVersion()); assertEquals(_testDataProvider.getSpreadsheetVersion(), wb.getSpreadsheetVersion());
wb.close(); }
} }
/* FIXME copied from {@link org.apache.poi.ss.TestWorkbookFactory} */ /* FIXME copied from {@link org.apache.poi.ss.TestWorkbookFactory} */
@ -852,7 +835,8 @@ public abstract class BaseTestWorkbook {
@Test @Test
public void sheetClone() throws IOException { public void sheetClone() throws IOException {
// First up, try a simple file // First up, try a simple file
final Workbook b = _testDataProvider.createWorkbook(); try (Workbook b = _testDataProvider.createWorkbook();
Workbook bBack = HSSFTestDataSamples.openSampleWorkbook("SheetWithDrawing.xls")) {
assertEquals(0, b.getNumberOfSheets()); assertEquals(0, b.getNumberOfSheets());
b.createSheet("Sheet One"); b.createSheet("Sheet One");
b.createSheet("Sheet Two"); b.createSheet("Sheet Two");
@ -862,13 +846,10 @@ public abstract class BaseTestWorkbook {
assertEquals(3, b.getNumberOfSheets()); assertEquals(3, b.getNumberOfSheets());
// Now try a problem one with drawing records in it // Now try a problem one with drawing records in it
Workbook bBack = HSSFTestDataSamples.openSampleWorkbook("SheetWithDrawing.xls");
assertEquals(1, bBack.getNumberOfSheets()); assertEquals(1, bBack.getNumberOfSheets());
bBack.cloneSheet(0); bBack.cloneSheet(0);
assertEquals(2, bBack.getNumberOfSheets()); assertEquals(2, bBack.getNumberOfSheets());
}
bBack.close();
b.close();
} }
@Test @Test
@ -899,23 +880,20 @@ public abstract class BaseTestWorkbook {
@Test @Test
public void addSheetTwice() throws IOException { public void addSheetTwice() throws IOException {
final Workbook wb = _testDataProvider.createWorkbook(); try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet1 = wb.createSheet("Sheet1"); Sheet sheet1 = wb.createSheet("Sheet1");
assertNotNull(sheet1); assertNotNull(sheet1);
try {
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(); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("already contains a sheet named 'Sheet1'");
wb.createSheet("Sheet1");
}
} }
// bug 51233 and 55075: correctly size image if added to a row with a custom height // bug 51233 and 55075: correctly size image if added to a row with a custom height
@Test @Test
public void createDrawing() throws Exception { public void createDrawing() throws Exception {
Workbook wb = _testDataProvider.createWorkbook(); try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet("Main Sheet"); Sheet sheet = wb.createSheet("Main Sheet");
Row row0 = sheet.createRow(0); Row row0 = sheet.createRow(0);
Row row1 = sheet.createRow(1); Row row1 = sheet.createRow(1);
@ -953,17 +931,6 @@ public abstract class BaseTestWorkbook {
assertEquals(0, anchor.getCol2()); assertEquals(0, anchor.getCol2());
assertEquals(0, anchor.getDx1()); assertEquals(0, anchor.getDx1());
assertEquals(1114425, anchor.getDx2()); //HSSF: 171 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();
} }
wb.close();
} }
} }

View File

@ -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) {}
}