More IntelliJ warnings fixes

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1809370 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Dominik Stadler 2017-09-23 07:38:01 +00:00
parent 996010a3ca
commit 5ed15ac7c2
17 changed files with 232 additions and 356 deletions

View File

@ -169,7 +169,6 @@ public class CopyCompare
* @exception NoPropertySetStreamException if the application tries to
* create a property set from a POI document stream that is not a property
* set stream.
* @throws UnsupportedEncodingException
* @exception IOException if any I/O exception occurs.
*/
private static boolean equal(final DirectoryEntry d1,
@ -233,7 +232,6 @@ public class CopyCompare
* @exception NoPropertySetStreamException if the application tries to
* create a property set from a POI document stream that is not a property
* set stream.
* @throws UnsupportedEncodingException
* @exception IOException if any I/O exception occurs.
*/
private static boolean equal(final DocumentEntry d1, final DocumentEntry d2,
@ -355,8 +353,6 @@ public class CopyCompare
* @param path The file's path in the POI filesystem.
* @param name The file's name in the POI filesystem.
* @param ps The property set to write.
* @throws WritingNotSupportedException
* @throws IOException
*/
public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path,
@ -378,7 +374,6 @@ public class CopyCompare
* @param path The source document's path.
* @param name The source document's name.
* @param stream The stream containing the source document.
* @throws IOException
*/
public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path,
@ -407,9 +402,6 @@ public class CopyCompare
/**
* <p>Writes the POI file system to a disk file.</p>
*
* @throws FileNotFoundException
* @throws IOException
*/
public void close() throws FileNotFoundException, IOException {
out = new FileOutputStream(dstName);

View File

@ -19,17 +19,12 @@ package org.apache.poi.hpsf.examples;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import org.apache.poi.hpsf.CustomProperties;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.MarkUnsupportedException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.UnexpectedPropertySetTypeException;
import org.apache.poi.hpsf.WritingNotSupportedException;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
@ -76,16 +71,8 @@ public class ModifyDocumentSummaryInformation {
* <p>Main method - see class description.</p>
*
* @param args The command-line parameters.
* @throws IOException
* @throws MarkUnsupportedException
* @throws NoPropertySetStreamException
* @throws UnexpectedPropertySetTypeException
* @throws WritingNotSupportedException
*/
public static void main(final String[] args) throws IOException,
NoPropertySetStreamException, MarkUnsupportedException,
UnexpectedPropertySetTypeException, WritingNotSupportedException
{
public static void main(final String[] args) throws Exception {
/* Read the name of the POI filesystem to modify from the command line.
* For brevity to boundary check is performed on the command-line
* arguments. */

View File

@ -19,7 +19,6 @@ package org.apache.poi.hpsf.examples;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hpsf.NoPropertySetStreamException;
@ -64,7 +63,7 @@ public class ReadCustomPropertySets
@Override
public void processPOIFSReaderEvent(final POIFSReaderEvent event)
{
PropertySet ps = null;
PropertySet ps;
try
{
ps = PropertySetFactory.create(event.getStream());
@ -93,10 +92,8 @@ public class ReadCustomPropertySets
/* Print the list of sections: */
List<Section> sections = ps.getSections();
int nr = 0;
for (Iterator<Section> i = sections.iterator(); i.hasNext();)
{
for (Section sec : sections) {
/* Print a single section: */
Section sec = i.next();
out(" Section " + nr++ + ":");
String s = hex(sec.getFormatID().getBytes());
s = s.substring(0, s.length() - 1);
@ -108,15 +105,13 @@ public class ReadCustomPropertySets
/* Print the properties: */
Property[] properties = sec.getProperties();
for (int i2 = 0; i2 < properties.length; i2++)
{
for (Property p : properties) {
/* Print a single property: */
Property p = properties[i2];
long id = p.getID();
long type = p.getType();
Object value = p.getValue();
out(" Property ID: " + id + ", type: " + type +
", value: " + value);
", value: " + value);
}
}
}

View File

@ -193,7 +193,7 @@ public class WriteAuthorAndTitle
/* According to the definition of the processPOIFSReaderEvent method
* we cannot pass checked exceptions to the caller. The following
* lines check whether a checked exception occured and throws an
* lines check whether a checked exception occurred and throws an
* unchecked exception. The message of that exception is that of
* the underlying checked exception. */
if (t != null) {
@ -212,8 +212,6 @@ public class WriteAuthorAndTitle
* @param name The original (and destination) stream's name.
* @param si The property set. It should be a summary information
* property set.
* @throws IOException
* @throws WritingNotSupportedException
*/
public void editSI(final POIFSFileSystem poiFs,
final POIFSDocumentPath path,
@ -257,8 +255,6 @@ public class WriteAuthorAndTitle
* @param path The file's path in the POI filesystem.
* @param name The file's name in the POI filesystem.
* @param ps The property set to write.
* @throws WritingNotSupportedException
* @throws IOException
*/
public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path,
@ -281,7 +277,6 @@ public class WriteAuthorAndTitle
* @param path The source document's path.
* @param name The source document's name.
* @param stream The stream containing the source document.
* @throws IOException
*/
public void copy(final POIFSFileSystem poiFs,
final POIFSDocumentPath path,
@ -303,9 +298,6 @@ public class WriteAuthorAndTitle
/**
* <p>Writes the POI file system to a disk file.</p>
*
* @throws FileNotFoundException
* @throws IOException
*/
public void close() throws FileNotFoundException, IOException
{

View File

@ -99,8 +99,6 @@ public class XLS2CSVmra implements HSSFListener {
* Creates a new XLS -> CSV converter
* @param filename The file to process
* @param minColumns The minimum number of columns to output, or -1 for no minimum
* @throws IOException
* @throws FileNotFoundException
*/
public XLS2CSVmra(String filename, int minColumns) throws IOException, FileNotFoundException {
this(

View File

@ -43,9 +43,9 @@ public class BigExample {
// create a new sheet
HSSFSheet s = wb.createSheet();
// declare a row object reference
HSSFRow r = null;
HSSFRow r;
// declare a cell object reference
HSSFCell c = null;
HSSFCell c;
// create 3 cell styles
HSSFCellStyle cs = wb.createCellStyle();
HSSFCellStyle cs2 = wb.createCellStyle();
@ -69,9 +69,9 @@ public class BigExample {
//make it bold
f2.setBold(true);
//set cell stlye
//set cell style
cs.setFont(f);
//set the cell format see HSSFDataFromat for a full list
//set the cell format see HSSFDataFormat for a full list
cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
//set a thin border

View File

@ -20,7 +20,6 @@ package org.apache.poi.hssf.usermodel.examples;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

View File

@ -498,13 +498,13 @@ public void paintBorder(Component c, Graphics g, int x, int y, int width,
* @param y the y origin of the line
* @param thickness the thickness of the line
* @param horizontal or vertical (true for horizontal)
* @param right/bottom or left/top thickness (true for right or top),
* @param rightBottom or left/top thickness (true for right or top),
* if true then the x or y origin will be incremented to provide
* thickness, if false, they'll be decremented. For vertical
* borders, x is incremented or decremented, for horizontal its y.
* Just set to true for north and west, and false for east and
* south.
* @returns length - returns the length of the line.
* @return length - returns the length of the line.
*/
private int drawDashDotDot(Graphics g,int x, int y, int thickness,
boolean horizontal,
@ -529,7 +529,7 @@ public void paintBorder(Component c, Graphics g, int x, int y, int width,
}
/**
* @returns the line thickness for a border based on border type
* @return the line thickness for a border based on border type
*/
private int getThickness(BorderStyle thickness) {
switch (thickness) {

View File

@ -57,23 +57,16 @@ public class DocumentDescriptorRenderer extends DefaultTreeCellRenderer
/**
* <p>Renders {@link DocumentDescriptor} as a string.</p>
*/
protected String renderAsString(final DocumentDescriptor d)
{
final StringBuilder b = new StringBuilder();
b.append("Name: ");
b.append(d.name);
b.append(" ");
b.append(HexDump.toHex(d.name));
b.append("\n");
b.append("Size: ");
b.append(d.size);
b.append(" bytes\n");
b.append("First bytes: ");
b.append(HexDump.toHex(d.bytes));
return b.toString();
protected String renderAsString(final DocumentDescriptor d) {
return "Name: " +
d.name +
" " +
HexDump.toHex(d.name) +
"\n" +
"Size: " +
d.size +
" bytes\n" +
"First bytes: " +
HexDump.toHex(d.bytes);
}
}

View File

@ -84,9 +84,7 @@ public class POIBrowser extends JFrame
/* Add the POI filesystems to the tree. */
int displayedFiles = 0;
for (int i = 0; i < args.length; i++)
{
final String filename = args[i];
for (final String filename : args) {
try {
FileInputStream fis = new FileInputStream(filename);
POIFSReader r = new POIFSReader();
@ -98,7 +96,7 @@ public class POIBrowser extends JFrame
System.err.println(filename + ": " + ex);
} catch (Exception t) {
System.err.println("Unexpected exception while reading \"" +
filename + "\":");
filename + "\":");
t.printStackTrace(System.err);
}
}

View File

@ -333,10 +333,10 @@ public class AddDimensionedImage {
URL imageFile, double reqImageWidthMM, double reqImageHeightMM,
int resizeBehaviour) throws IOException,
IllegalArgumentException {
ClientAnchor anchor = null;
ClientAnchorDetail rowClientAnchorDetail = null;
ClientAnchorDetail colClientAnchorDetail = null;
int imageType = 0;
ClientAnchor anchor;
ClientAnchorDetail rowClientAnchorDetail;
ClientAnchorDetail colClientAnchorDetail;
int imageType;
// Validate the resizeBehaviour parameter.
if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) &&
@ -427,9 +427,9 @@ public class AddDimensionedImage {
private ClientAnchorDetail fitImageToColumns(Sheet sheet, int colNumber,
double reqImageWidthMM, int resizeBehaviour) {
double colWidthMM = 0.0D;
double colCoordinatesPerMM = 0.0D;
int pictureWidthCoordinates = 0;
double colWidthMM;
double colCoordinatesPerMM;
int pictureWidthCoordinates;
ClientAnchorDetail colClientAnchorDetail = null;
// Get the colum's width in millimetres
@ -522,10 +522,10 @@ public class AddDimensionedImage {
*/
private ClientAnchorDetail fitImageToRows(Sheet sheet, int rowNumber,
double reqImageHeightMM, int resizeBehaviour) {
Row row = null;
double rowHeightMM = 0.0D;
double rowCoordinatesPerMM = 0.0D;
int pictureHeightCoordinates = 0;
Row row;
double rowHeightMM;
double rowCoordinatesPerMM;
int pictureHeightCoordinates;
ClientAnchorDetail rowClientAnchorDetail = null;
// Get the row and it's height
@ -612,13 +612,13 @@ public class AddDimensionedImage {
private ClientAnchorDetail calculateColumnLocation(Sheet sheet,
int startingColumn,
double reqImageWidthMM) {
ClientAnchorDetail anchorDetail = null;
ClientAnchorDetail anchorDetail;
double totalWidthMM = 0.0D;
double colWidthMM = 0.0D;
double overlapMM = 0.0D;
double coordinatePositionsPerMM = 0.0D;
double overlapMM;
double coordinatePositionsPerMM;
int toColumn = startingColumn;
int inset = 0;
int inset;
// Calculate how many columns the image will have to
// span in order to be presented at the required size.
@ -722,14 +722,14 @@ public class AddDimensionedImage {
*/
private ClientAnchorDetail calculateRowLocation(Sheet sheet,
int startingRow, double reqImageHeightMM) {
ClientAnchorDetail clientAnchorDetail = null;
Row row = null;
ClientAnchorDetail clientAnchorDetail;
Row row;
double rowHeightMM = 0.0D;
double totalRowHeightMM = 0.0D;
double overlapMM = 0.0D;
double rowCoordinatesPerMM = 0.0D;
double overlapMM;
double rowCoordinatesPerMM;
int toRow = startingRow;
int inset = 0;
int inset;
// Step through the rows in the sheet and accumulate a total of their
// heights.
@ -813,11 +813,11 @@ public class AddDimensionedImage {
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String imageFile = null;
String outputFile = null;
FileOutputStream fos = null;
Workbook workbook = null;
Sheet sheet = null;
String imageFile;
String outputFile;
FileOutputStream fos;
Workbook workbook;
Sheet sheet;
if(args.length < 2){
System.err.println("Usage: AddDimensionedImage imageFile outputFile");
@ -962,8 +962,6 @@ public class AddDimensionedImage {
/**
* pixel units to excel width units(units of 1/256th of a character width)
* @param pxs
* @return
*/
public static short pixel2WidthUnits(int pxs) {
short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR *
@ -975,9 +973,6 @@ public class AddDimensionedImage {
/**
* excel width units(units of 1/256th of a character width) to pixel
* units.
*
* @param widthUnits
* @return
*/
public static int widthUnits2Pixel(short widthUnits) {
int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR)

View File

@ -63,7 +63,6 @@ public class ConditionalFormats {
* generates a sample workbook with conditional formatting,
* and prints out a summary of applied formats for one sheet
* @param args pass "-xls" to generate an HSSF workbook, default is XSSF
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Workbook wb;
@ -656,8 +655,6 @@ public class ConditionalFormats {
/**
* Print out a summary of the conditional formatting rules applied to cells on the given sheet.
* Only cells with a matching rule are printed, and for those, all matching rules are sumarized.
* @param wb
* @param sheetName
*/
static void evaluateRules(Workbook wb, String sheetName) {
final WorkbookEvaluatorProvider wbEvalProv = (WorkbookEvaluatorProvider) wb.getCreationHelper().createFormulaEvaluator();

View File

@ -285,8 +285,8 @@ public class ToCSV {
IllegalArgumentException, InvalidFormatException {
File source = new File(strSource);
File destination = new File(strDestination);
File[] filesList = null;
String destinationFilename = null;
File[] filesList;
String destinationFilename;
// Check that the source file/folder exists.
if(!source.exists()) {
@ -406,9 +406,9 @@ public class ToCSV {
* a CSV file.
*/
private void convertToCSV() {
Sheet sheet = null;
Row row = null;
int lastRowNum = 0;
Sheet sheet;
Row row;
int lastRowNum;
this.csvData = new ArrayList<>();
System.out.println("Converting files contents to CSV format.");
@ -451,11 +451,11 @@ public class ToCSV {
*/
private void saveCSVFile(File file)
throws FileNotFoundException, IOException {
FileWriter fw = null;
FileWriter fw;
BufferedWriter bw = null;
ArrayList<String> line = null;
StringBuffer buffer = null;
String csvLineElement = null;
ArrayList<String> line;
StringBuffer buffer;
String csvLineElement;
try {
System.out.println("Saving the CSV file [" + file.getName() + "]");
@ -524,8 +524,8 @@ public class ToCSV {
* an Excel workbook.
*/
private void rowToCSV(Row row) {
Cell cell = null;
int lastCellNum = 0;
Cell cell;
int lastCellNum;
ArrayList<String> csvLine = new ArrayList<>();
// Check to ensure that a row was recovered from the sheet as it is
@ -603,7 +603,7 @@ public class ToCSV {
* speech mark characters correctly escaped.
*/
private String escapeEmbeddedCharacters(String field) {
StringBuffer buffer = null;
StringBuffer buffer;
// If the fields contents should be formatted to confrom with Excel's
// convention....
@ -671,7 +671,7 @@ public class ToCSV {
// with matching names but different extensions - Test.xls and Test.xlsx
// for example - then the CSV file generated from one will overwrite
// that generated from the other.
ToCSV converter = null;
ToCSV converter;
boolean converted = true;
long startTime = System.currentTimeMillis();
try {

View File

@ -328,12 +328,9 @@ public class ToHtml {
style = wb.getCellStyleAt((short) 0);
}
StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb);
try {
try (Formatter fmt = new Formatter(sb)) {
fmt.format("style_%02x", style.getIndex());
return fmt.toString();
} finally {
fmt.close();
}
}
@ -371,14 +368,14 @@ public class ToHtml {
/**
* computes the column widths, defined by the sheet.
*
* @param sheet
* @param sheet The sheet for which to compute widths
* @return Map with key: column index; value: column width in pixels
* <br>special keys:
* <br>{@link #IDX_HEADER_COL_WIDTH} - width of the header column
* <br>{@link #IDX_TABLE_WIDTH} - width of the entire table
*/
private Map<Integer, Integer> computeWidths(Sheet sheet) {
Map<Integer, Integer> ret = new TreeMap<Integer, Integer>();
Map<Integer, Integer> ret = new TreeMap<>();
int tableWidth = 0;
ensureColumnBounds(sheet);

View File

@ -20,7 +20,6 @@
package org.apache.poi.xssf.eventusermodel.examples;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.crypt.examples.EncryptionUtils;

View File

@ -44,170 +44,148 @@ public class TestXSSFImportFromXML {
@Test
public void testImportFromXML() throws IOException, XPathExpressionException, SAXException{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx");
try {
String name = "name";
String teacher = "teacher";
String tutor = "tutor";
String cdl = "cdl";
String duration = "duration";
String topic = "topic";
String project = "project";
String credits = "credits";
String testXML = "<CORSO>"+
"<NOME>"+name+"</NOME>"+
"<DOCENTE>"+teacher+"</DOCENTE>"+
"<TUTOR>"+tutor+"</TUTOR>"+
"<CDL>"+cdl+"</CDL>"+
"<DURATA>"+duration+"</DURATA>"+
"<ARGOMENTO>"+topic+"</ARGOMENTO>"+
"<PROGETTO>"+project+"</PROGETTO>"+
"<CREDITI>"+credits+"</CREDITI>"+
"</CORSO>\u0000";
XSSFMap map = wb.getMapInfo().getXSSFMapByName("CORSO_mapping");
assertNotNull(map);
XSSFImportFromXML importer = new XSSFImportFromXML(map);
importer.importFromXML(testXML);
XSSFSheet sheet=wb.getSheetAt(0);
XSSFRow row = sheet.getRow(0);
assertTrue(row.getCell(0).getStringCellValue().equals(name));
assertTrue(row.getCell(1).getStringCellValue().equals(teacher));
assertTrue(row.getCell(2).getStringCellValue().equals(tutor));
assertTrue(row.getCell(3).getStringCellValue().equals(cdl));
assertTrue(row.getCell(4).getStringCellValue().equals(duration));
assertTrue(row.getCell(5).getStringCellValue().equals(topic));
assertTrue(row.getCell(6).getStringCellValue().equals(project));
assertTrue(row.getCell(7).getStringCellValue().equals(credits));
} finally {
wb.close();
}
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx")) {
String name = "name";
String teacher = "teacher";
String tutor = "tutor";
String cdl = "cdl";
String duration = "duration";
String topic = "topic";
String project = "project";
String credits = "credits";
String testXML = "<CORSO>" +
"<NOME>" + name + "</NOME>" +
"<DOCENTE>" + teacher + "</DOCENTE>" +
"<TUTOR>" + tutor + "</TUTOR>" +
"<CDL>" + cdl + "</CDL>" +
"<DURATA>" + duration + "</DURATA>" +
"<ARGOMENTO>" + topic + "</ARGOMENTO>" +
"<PROGETTO>" + project + "</PROGETTO>" +
"<CREDITI>" + credits + "</CREDITI>" +
"</CORSO>\u0000";
XSSFMap map = wb.getMapInfo().getXSSFMapByName("CORSO_mapping");
assertNotNull(map);
XSSFImportFromXML importer = new XSSFImportFromXML(map);
importer.importFromXML(testXML);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row = sheet.getRow(0);
assertTrue(row.getCell(0).getStringCellValue().equals(name));
assertTrue(row.getCell(1).getStringCellValue().equals(teacher));
assertTrue(row.getCell(2).getStringCellValue().equals(tutor));
assertTrue(row.getCell(3).getStringCellValue().equals(cdl));
assertTrue(row.getCell(4).getStringCellValue().equals(duration));
assertTrue(row.getCell(5).getStringCellValue().equals(topic));
assertTrue(row.getCell(6).getStringCellValue().equals(project));
assertTrue(row.getCell(7).getStringCellValue().equals(credits));
}
}
@Test(timeout=60000)
public void testMultiTable() throws IOException, XPathExpressionException, SAXException{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx");
try {
String cellC6 = "c6";
String cellC7 = "c7";
String cellC8 = "c8";
String cellC9 = "c9";
String testXML = "<ns1:MapInfo xmlns:ns1=\""+NS_SPREADSHEETML+"\" SelectionNamespaces=\"\">" +
"<ns1:Schema ID=\""+cellC6+"\" SchemaRef=\"a\" />"+
"<ns1:Schema ID=\""+cellC7+"\" SchemaRef=\"b\" />"+
"<ns1:Schema ID=\""+cellC8+"\" SchemaRef=\"c\" />"+
"<ns1:Schema ID=\""+cellC9+"\" SchemaRef=\"d\" />";
for(int i = 10; i< 10010; i++){
testXML += "<ns1:Schema ID=\"c"+i+"\" SchemaRef=\"d\" />";
}
testXML += "<ns1:Map ID=\"1\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">"+
"<ns1:DataBinding DataBindingLoadMode=\"\" />"+
"</ns1:Map>"+
"<ns1:Map ID=\"2\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">"+
"<ns1:DataBinding DataBindingLoadMode=\"\" />"+
"</ns1:Map>"+
"<ns1:Map ID=\"3\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">"+
"<ns1:DataBinding DataBindingLoadMode=\"\" />"+
"</ns1:Map>"+
"</ns1:MapInfo>\u0000";
XSSFMap map = wb.getMapInfo().getXSSFMapByName("MapInfo_mapping");
assertNotNull(map);
XSSFImportFromXML importer = new XSSFImportFromXML(map);
importer.importFromXML(testXML);
//Check for Schema element
XSSFSheet sheet=wb.getSheetAt(1);
assertEquals(cellC6,sheet.getRow(5).getCell(2).getStringCellValue());
assertEquals(cellC7,sheet.getRow(6).getCell(2).getStringCellValue());
assertEquals(cellC8,sheet.getRow(7).getCell(2).getStringCellValue());
assertEquals(cellC9,sheet.getRow(8).getCell(2).getStringCellValue());
assertEquals("c5001",sheet.getRow(5000).getCell(2).getStringCellValue());
} finally {
wb.close();
}
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx")) {
String cellC6 = "c6";
String cellC7 = "c7";
String cellC8 = "c8";
String cellC9 = "c9";
StringBuilder testXML = new StringBuilder("<ns1:MapInfo xmlns:ns1=\"" + NS_SPREADSHEETML + "\" SelectionNamespaces=\"\">" +
"<ns1:Schema ID=\"" + cellC6 + "\" SchemaRef=\"a\" />" +
"<ns1:Schema ID=\"" + cellC7 + "\" SchemaRef=\"b\" />" +
"<ns1:Schema ID=\"" + cellC8 + "\" SchemaRef=\"c\" />" +
"<ns1:Schema ID=\"" + cellC9 + "\" SchemaRef=\"d\" />");
for (int i = 10; i < 10010; i++) {
testXML.append("<ns1:Schema ID=\"c").append(i).append("\" SchemaRef=\"d\" />");
}
testXML.append("<ns1:Map ID=\"1\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">" + "<ns1:DataBinding DataBindingLoadMode=\"\" />" + "</ns1:Map>" + "<ns1:Map ID=\"2\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">" + "<ns1:DataBinding DataBindingLoadMode=\"\" />" + "</ns1:Map>" + "<ns1:Map ID=\"3\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">" + "<ns1:DataBinding DataBindingLoadMode=\"\" />" + "</ns1:Map>" + "</ns1:MapInfo>\u0000");
XSSFMap map = wb.getMapInfo().getXSSFMapByName("MapInfo_mapping");
assertNotNull(map);
XSSFImportFromXML importer = new XSSFImportFromXML(map);
importer.importFromXML(testXML.toString());
//Check for Schema element
XSSFSheet sheet = wb.getSheetAt(1);
assertEquals(cellC6, sheet.getRow(5).getCell(2).getStringCellValue());
assertEquals(cellC7, sheet.getRow(6).getCell(2).getStringCellValue());
assertEquals(cellC8, sheet.getRow(7).getCell(2).getStringCellValue());
assertEquals(cellC9, sheet.getRow(8).getCell(2).getStringCellValue());
assertEquals("c5001", sheet.getRow(5000).getCell(2).getStringCellValue());
}
}
@Test
public void testSingleAttributeCellWithNamespace() throws IOException, XPathExpressionException, SAXException{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx");
try {
int id = 1;
String displayName = "dispName";
String ref="19";
int count = 21;
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>"+
"<ns1:table xmlns:ns1=\""+NS_SPREADSHEETML+"\" id=\""+id+"\" displayName=\""+displayName+"\" ref=\""+ref+"\">"+
"<ns1:tableColumns count=\""+count+"\" />"+
"</ns1:table>\u0000";
XSSFMap map = wb.getMapInfo().getXSSFMapByName("table_mapping");
assertNotNull(map);
XSSFImportFromXML importer = new XSSFImportFromXML(map);
importer.importFromXML(testXML);
//Check for Schema element
XSSFSheet sheet=wb.getSheetAt(0);
assertEquals(new Double(id), sheet.getRow(28).getCell(1).getNumericCellValue(), 0);
assertEquals(displayName, sheet.getRow(11).getCell(5).getStringCellValue());
assertEquals(ref, sheet.getRow(14).getCell(7).getStringCellValue());
assertEquals(new Double(count), sheet.getRow(18).getCell(3).getNumericCellValue(), 0);
} finally {
wb.close();
}
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx")) {
int id = 1;
String displayName = "dispName";
String ref = "19";
int count = 21;
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>" +
"<ns1:table xmlns:ns1=\"" + NS_SPREADSHEETML + "\" id=\"" + id + "\" displayName=\"" + displayName + "\" ref=\"" + ref + "\">" +
"<ns1:tableColumns count=\"" + count + "\" />" +
"</ns1:table>\u0000";
XSSFMap map = wb.getMapInfo().getXSSFMapByName("table_mapping");
assertNotNull(map);
XSSFImportFromXML importer = new XSSFImportFromXML(map);
importer.importFromXML(testXML);
//Check for Schema element
XSSFSheet sheet = wb.getSheetAt(0);
assertEquals(new Double(id), sheet.getRow(28).getCell(1).getNumericCellValue(), 0);
assertEquals(displayName, sheet.getRow(11).getCell(5).getStringCellValue());
assertEquals(ref, sheet.getRow(14).getCell(7).getStringCellValue());
assertEquals(new Double(count), sheet.getRow(18).getCell(3).getNumericCellValue(), 0);
}
}
@Test
public void testOptionalFields_Bugzilla_55864() throws IOException, XPathExpressionException, SAXException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55864.xlsx");
try {
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
"<PersonInfoRoot>" +
"<PersonData>" +
"<FirstName>Albert</FirstName>" +
"<LastName>Einstein</LastName>" +
"<BirthDate>1879-03-14</BirthDate>" +
"</PersonData>" +
"</PersonInfoRoot>";
XSSFMap map = wb.getMapInfo().getXSSFMapByName("PersonInfoRoot_Map");
assertNotNull(map);
XSSFImportFromXML importer = new XSSFImportFromXML(map);
importer.importFromXML(testXML);
XSSFSheet sheet=wb.getSheetAt(0);
XSSFRow rowHeadings = sheet.getRow(0);
XSSFRow rowData = sheet.getRow(1);
assertEquals("FirstName", rowHeadings.getCell(0).getStringCellValue());
assertEquals("Albert", rowData.getCell(0).getStringCellValue());
assertEquals("LastName", rowHeadings.getCell(1).getStringCellValue());
assertEquals("Einstein", rowData.getCell(1).getStringCellValue());
assertEquals("BirthDate", rowHeadings.getCell(2).getStringCellValue());
assertEquals("1879-03-14", rowData.getCell(2).getStringCellValue());
// Value for OptionalRating is declared optional (minOccurs=0) in 55864.xlsx
assertEquals("OptionalRating", rowHeadings.getCell(3).getStringCellValue());
assertNull("", rowData.getCell(3));
} finally {
wb.close();
}
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55864.xlsx")) {
String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
"<PersonInfoRoot>" +
"<PersonData>" +
"<FirstName>Albert</FirstName>" +
"<LastName>Einstein</LastName>" +
"<BirthDate>1879-03-14</BirthDate>" +
"</PersonData>" +
"</PersonInfoRoot>";
XSSFMap map = wb.getMapInfo().getXSSFMapByName("PersonInfoRoot_Map");
assertNotNull(map);
XSSFImportFromXML importer = new XSSFImportFromXML(map);
importer.importFromXML(testXML);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow rowHeadings = sheet.getRow(0);
XSSFRow rowData = sheet.getRow(1);
assertEquals("FirstName", rowHeadings.getCell(0).getStringCellValue());
assertEquals("Albert", rowData.getCell(0).getStringCellValue());
assertEquals("LastName", rowHeadings.getCell(1).getStringCellValue());
assertEquals("Einstein", rowData.getCell(1).getStringCellValue());
assertEquals("BirthDate", rowHeadings.getCell(2).getStringCellValue());
assertEquals("1879-03-14", rowData.getCell(2).getStringCellValue());
// Value for OptionalRating is declared optional (minOccurs=0) in 55864.xlsx
assertEquals("OptionalRating", rowHeadings.getCell(3).getStringCellValue());
assertNull("", rowData.getCell(3));
}
}
@Test

View File

@ -180,8 +180,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test
public void getCellStyleAt() throws IOException{
XSSFWorkbook workbook = new XSSFWorkbook();
try {
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
short i = 0;
//get default style
CellStyle cellStyleAt = workbook.getCellStyleAt(i);
@ -194,17 +193,14 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
font.setFontName("Verdana");
customStyle.setFont(font);
int x = styleSource.putStyle(customStyle);
cellStyleAt = workbook.getCellStyleAt((short)x);
cellStyleAt = workbook.getCellStyleAt((short) x);
assertNotNull(cellStyleAt);
} finally {
workbook.close();
}
}
}
@Test
public void getFontAt() throws IOException{
XSSFWorkbook workbook = new XSSFWorkbook();
try {
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
StylesTable styleSource = workbook.getStylesSource();
short i = 0;
//get default font
@ -215,22 +211,17 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
XSSFFont customFont = new XSSFFont();
customFont.setItalic(true);
int x = styleSource.putFont(customFont);
fontAt = workbook.getFontAt((short)x);
fontAt = workbook.getFontAt((short) x);
assertNotNull(fontAt);
} finally {
workbook.close();
}
}
}
@Test
public void getNumCellStyles() throws IOException{
XSSFWorkbook workbook = new XSSFWorkbook();
try {
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
//get default cellStyles
assertEquals(1, workbook.getNumCellStyles());
} finally {
workbook.close();
}
}
}
@Test
@ -303,35 +294,27 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test
public void incrementSheetId() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
try {
int sheetId = (int)wb.createSheet().sheet.getSheetId();
try (XSSFWorkbook wb = new XSSFWorkbook()) {
int sheetId = (int) wb.createSheet().sheet.getSheetId();
assertEquals(1, sheetId);
sheetId = (int)wb.createSheet().sheet.getSheetId();
sheetId = (int) wb.createSheet().sheet.getSheetId();
assertEquals(2, sheetId);
//test file with gaps in the sheetId sequence
XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm");
try {
int lastSheetId = (int)wbBack.getSheetAt(wbBack.getNumberOfSheets() - 1).sheet.getSheetId();
sheetId = (int)wbBack.createSheet().sheet.getSheetId();
assertEquals(lastSheetId+1, sheetId);
} finally {
wbBack.close();
try (XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm")) {
int lastSheetId = (int) wbBack.getSheetAt(wbBack.getNumberOfSheets() - 1).sheet.getSheetId();
sheetId = (int) wbBack.createSheet().sheet.getSheetId();
assertEquals(lastSheetId + 1, sheetId);
}
} finally {
wb.close();
}
}
/**
* Test setting of core properties such as Title and Author
* @throws IOException
*/
@Test
public void workbookProperties() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
try {
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
POIXMLProperties props = workbook.getProperties();
assertNotNull(props);
//the Application property must be set for new workbooks, see Bugzilla #47559
@ -350,8 +333,6 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().getValue());
assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().getValue());
wbBack.close();
} finally {
workbook.close();
}
}
@ -396,6 +377,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
/**
* When deleting a sheet make sure that we adjust sheet indices of named ranges
*/
@SuppressWarnings("deprecation")
@Test
public void bug47737() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx");
@ -500,8 +482,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test
public void recalcId() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
try {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
assertFalse(wb.getForceFormulaRecalculation());
CTWorkbook ctWorkbook = wb.getCTWorkbook();
assertFalse(ctWorkbook.isSetCalcPr());
@ -523,8 +504,6 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
calcPr.setCalcMode(STCalcMode.MANUAL);
wb.setForceFormulaRecalculation(true);
assertEquals(STCalcMode.AUTO, calcPr.getCalcMode());
} finally {
wb.close();
}
}
@ -549,11 +528,8 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
accessWorkbook(workbook);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
workbook.write(stream);
} finally {
stream.close();
}
accessWorkbook(workbook);
@ -703,8 +679,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test
public void bug51158a() throws IOException {
// create a workbook
final XSSFWorkbook workbook = new XSSFWorkbook();
try {
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
workbook.createSheet("Test Sheet");
XSSFSheet sheetBack = workbook.getSheetAt(0);
@ -713,7 +688,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
sheetBack.commit();
// ensure that a memory based package part does not have lingering data from previous commit() calls
if(sheetBack.getPackagePart() instanceof MemoryPackagePart) {
if (sheetBack.getPackagePart() instanceof MemoryPackagePart) {
sheetBack.getPackagePart().clear();
}
@ -722,8 +697,6 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream()), "UTF-8");
assertEquals(1, countMatches(str, "<worksheet"));
} finally {
workbook.close();
}
}
@ -752,16 +725,13 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test
public void testAddPivotCache() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
try {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
CTWorkbook ctWb = wb.getCTWorkbook();
CTPivotCache pivotCache = wb.addPivotCache("0");
//Ensures that pivotCaches is initiated
assertTrue(ctWb.isSetPivotCaches());
assertSame(pivotCache, ctWb.getPivotCaches().getPivotCacheArray(0));
assertEquals("0", pivotCache.getId());
} finally {
wb.close();
}
}
@ -801,22 +771,16 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
public void testLoadWorkbookWithPivotTable() throws Exception {
File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx");
XSSFWorkbook wb = new XSSFWorkbook();
try {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
setPivotData(wb);
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
} finally {
wb.close();
}
XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file);
try {
try (XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file)) {
assertTrue(wb2.getPivotTables().size() == 1);
} finally {
wb2.close();
}
assertTrue(file.delete());
@ -826,26 +790,17 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
public void testAddPivotTableToWorkbookWithLoadedPivotTable() throws Exception {
File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx");
XSSFWorkbook wb = new XSSFWorkbook();
try {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
setPivotData(wb);
FileOutputStream fileOut = new FileOutputStream(file);
try {
try (FileOutputStream fileOut = new FileOutputStream(file)) {
wb.write(fileOut);
} finally {
fileOut.close();
}
} finally {
wb.close();
}
XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file);
try {
try (XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file)) {
setPivotData(wb2);
assertTrue(wb2.getPivotTables().size() == 2);
} finally {
wb2.close();
}
assertTrue(file.delete());
@ -853,17 +808,17 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test
public void testSetFirstVisibleTab_57373() throws IOException {
Workbook wb = new XSSFWorkbook();
try {
/*Sheet sheet1 =*/ wb.createSheet();
try (Workbook wb = new XSSFWorkbook()) {
/*Sheet sheet1 =*/
wb.createSheet();
Sheet sheet2 = wb.createSheet();
int idx2 = wb.getSheetIndex(sheet2);
Sheet sheet3 = wb.createSheet();
int idx3 = wb.getSheetIndex(sheet3);
// add many sheets so "first visible" is relevant
for(int i = 0; i < 30;i++) {
for (int i = 0; i < 30; i++) {
wb.createSheet();
}
@ -878,12 +833,12 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
sheet2 = wbBack.getSheetAt(idx2);
assertNotNull(sheet2);
sheet3 = wbBack.getSheetAt(idx3);
assertNotNull(sheet3);
assertEquals(idx2, wb.getFirstVisibleTab());
assertEquals(idx3, wb.getActiveSheetIndex());
wbBack.close();
} finally {
wb.close();
}
}
@ -947,8 +902,8 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
* In order to make code for looping over sheets in workbooks standard, regardless
* of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously
* available Iterator<XSSFSheet> iterator and Iterator<XSSFSheet> sheetIterator
* have been replaced with Iterator<Sheet> {@link #iterator} and
* Iterator<Sheet> {@link #sheetIterator}. This makes iterating over sheets in a workbook
* have been replaced with Iterator<Sheet> {@link Sheet#iterator} and
* Iterator<Sheet> {@link Workbook#sheetIterator}. This makes iterating over sheets in a workbook
* similar to iterating over rows in a sheet and cells in a row.
*
* Note: this breaks backwards compatibility! Existing codebases will need to
@ -1124,6 +1079,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
wb.close();
}
@SuppressWarnings("deprecation")
@Test
public void testRemoveSheet() throws IOException {
// Test removing a sheet maintains the named ranges correctly