SonarQube fixes

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1777855 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2017-01-08 00:38:41 +00:00
parent 24c0b83841
commit bf311b8e6e
30 changed files with 562 additions and 434 deletions

View File

@ -84,24 +84,22 @@ public class SavePasswordProtectedXlsx {
public static void save(final InputStream inputStream, final String filename, final String pwd) public static void save(final InputStream inputStream, final String filename, final String pwd)
throws InvalidFormatException, IOException, GeneralSecurityException { throws InvalidFormatException, IOException, GeneralSecurityException {
POIFSFileSystem fs = null;
FileOutputStream fos = null;
OPCPackage opc = null;
try { try {
POIFSFileSystem fs = new POIFSFileSystem(); fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = Encryptor.getInstance(info); Encryptor enc = Encryptor.getInstance(info);
enc.confirmPassword(pwd); enc.confirmPassword(pwd);
OPCPackage opc = OPCPackage.open(inputStream); opc = OPCPackage.open(inputStream);
try { fos = new FileOutputStream(filename);
FileOutputStream fos = new FileOutputStream(filename);
try {
opc.save(enc.getDataStream(fs)); opc.save(enc.getDataStream(fs));
fs.writeFilesystem(fos); fs.writeFilesystem(fos);
} finally { } finally {
IOUtils.closeQuietly(fos); IOUtils.closeQuietly(fos);
}
} finally {
IOUtils.closeQuietly(opc); IOUtils.closeQuietly(opc);
} IOUtils.closeQuietly(fs);
} finally {
IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(inputStream);
} }
} }

View File

@ -18,9 +18,17 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date; import java.util.Date;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
@ -29,7 +37,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreateCell { public class CreateCell {
public static void main(String[]args) throws Exception { public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
CreationHelper creationHelper = wb.getCreationHelper(); CreationHelper creationHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet"); Sheet sheet = wb.createSheet("new sheet");
@ -76,5 +84,6 @@ public class CreateCell {
FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx"); FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -16,9 +16,9 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
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;
@ -37,8 +37,7 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo;
*/ */
public class CreateTable { public class CreateTable {
public static void main(String[] args) throws FileNotFoundException, public static void main(String[] args) throws IOException {
IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) wb.createSheet(); XSSFSheet sheet = (XSSFSheet) wb.createSheet();
@ -88,5 +87,6 @@ public class CreateTable {
FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx"); FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -17,9 +17,15 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@ -27,7 +33,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
* Fills and Colors * Fills and Colors
*/ */
public class FillsAndColors { public class FillsAndColors {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet"); Sheet sheet = wb.createSheet("new sheet");
@ -37,7 +43,7 @@ public class FillsAndColors {
// Aqua background // Aqua background
CellStyle style = wb.createCellStyle(); CellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex()); style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
style.setFillPattern(CellStyle.BIG_SPOTS); style.setFillPattern(FillPatternType.BIG_SPOTS);
Cell cell = row.createCell(1); Cell cell = row.createCell(1);
cell.setCellValue(new XSSFRichTextString("X")); cell.setCellValue(new XSSFRichTextString("X"));
cell.setCellStyle(style); cell.setCellStyle(style);
@ -45,7 +51,7 @@ public class FillsAndColors {
// Orange "foreground", foreground being the fill foreground not the font color. // Orange "foreground", foreground being the fill foreground not the font color.
style = wb.createCellStyle(); style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.ORANGE.getIndex()); style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell = row.createCell(2); cell = row.createCell(2);
cell.setCellValue(new XSSFRichTextString("X")); cell.setCellValue(new XSSFRichTextString("X"));
cell.setCellStyle(style); cell.setCellStyle(style);
@ -54,6 +60,6 @@ public class FillsAndColors {
FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx"); FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -17,6 +17,7 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.PrintSetup; import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
@ -25,8 +26,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FitSheetToOnePage { public class FitSheetToOnePage {
public static void main(String[]args) throws IOException {
public static void main(String[]args) throws Exception {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("format sheet"); Sheet sheet = wb.createSheet("format sheet");
PrintSetup ps = sheet.getPrintSetup(); PrintSetup ps = sheet.getPrintSetup();
@ -41,6 +41,6 @@ public class FitSheetToOnePage {
FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx"); FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -17,6 +17,7 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Footer; import org.apache.poi.ss.usermodel.Footer;
import org.apache.poi.ss.usermodel.Header; import org.apache.poi.ss.usermodel.Header;
@ -28,7 +29,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class HeadersAndFooters { public class HeadersAndFooters {
public static void main(String[]args) throws Exception { public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("first-header - format sheet"); Sheet sheet = wb.createSheet("first-header - format sheet");
sheet.createRow(0).createCell(0).setCellValue(123); sheet.createRow(0).createCell(0).setCellValue(123);
@ -79,6 +80,6 @@ public class HeadersAndFooters {
FileOutputStream fileOut = new FileOutputStream("headerFooter.xlsx"); FileOutputStream fileOut = new FileOutputStream("headerFooter.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -17,20 +17,21 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.Workbook; import java.io.IOException;
import org.apache.poi.ss.usermodel.Sheet;
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 java.io.FileInputStream; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
* Iterate over rows and cells * Iterate over rows and cells
*/ */
public class IterateCells { public class IterateCells {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(new FileInputStream(args[0])); Workbook wb = new XSSFWorkbook(new FileInputStream(args[0]));
for (int i = 0; i < wb.getNumberOfSheets(); i++) { for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i); Sheet sheet = wb.getSheetAt(i);
@ -42,5 +43,6 @@ public class IterateCells {
} }
} }
} }
wb.close();
} }
} }

View File

@ -17,6 +17,7 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Chart; import org.apache.poi.ss.usermodel.Chart;
@ -42,7 +43,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/ */
public class LineChart { public class LineChart {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("linechart"); Sheet sheet = wb.createSheet("linechart");
final int NUM_OF_ROWS = 3; final int NUM_OF_ROWS = 3;
@ -59,7 +60,7 @@ public class LineChart {
} }
} }
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
Chart chart = drawing.createChart(anchor); Chart chart = drawing.createChart(anchor);
@ -87,5 +88,6 @@ public class LineChart {
FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx"); FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -17,21 +17,22 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
* An example of how to merge regions of cells. * An example of how to merge regions of cells.
*/ */
public class MergingCells { public class MergingCells {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet"); Sheet sheet = wb.createSheet("new sheet");
@ -45,5 +46,6 @@ public class MergingCells {
FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx"); FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -17,6 +17,7 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellStyle;
@ -30,7 +31,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/ */
public class NewLinesInCells { public class NewLinesInCells {
public static void main(String[]args) throws Exception { public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
@ -52,6 +53,7 @@ public class NewLinesInCells {
FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx"); FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -18,6 +18,7 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
@ -26,14 +27,14 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Outlining { public class Outlining {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws IOException {
Outlining o=new Outlining(); Outlining o=new Outlining();
o.groupRowColumn(); o.groupRowColumn();
o.collapseExpandRowColumn(); o.collapseExpandRowColumn();
} }
private void groupRowColumn() throws Exception { private void groupRowColumn() throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet"); Sheet sheet1 = wb.createSheet("new sheet");
@ -50,10 +51,11 @@ public class Outlining {
wb.write(fileOut); wb.write(fileOut);
} finally { } finally {
fileOut.close(); fileOut.close();
wb.close();
} }
} }
private void collapseExpandRowColumn() throws Exception { private void collapseExpandRowColumn() throws IOException {
Workbook wb2 = new XSSFWorkbook(); Workbook wb2 = new XSSFWorkbook();
Sheet sheet2 = wb2.createSheet("new sheet"); Sheet sheet2 = wb2.createSheet("new sheet");
sheet2.groupRow( 5, 14 ); sheet2.groupRow( 5, 14 );
@ -76,6 +78,7 @@ public class Outlining {
wb2.write(fileOut); wb2.write(fileOut);
} finally { } finally {
fileOut.close(); fileOut.close();
wb2.close();
} }
} }
} }

View File

@ -20,19 +20,32 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*; import java.io.IOException;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.usermodel.charts.*; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Chart;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.charts.AxisCrosses;
import org.apache.poi.ss.usermodel.charts.AxisPosition;
import org.apache.poi.ss.usermodel.charts.ChartDataSource;
import org.apache.poi.ss.usermodel.charts.ChartLegend;
import org.apache.poi.ss.usermodel.charts.DataSources;
import org.apache.poi.ss.usermodel.charts.LegendPosition;
import org.apache.poi.ss.usermodel.charts.ScatterChartData;
import org.apache.poi.ss.usermodel.charts.ValueAxis;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
* Illustrates how to create a simple scatter chart. * Illustrates how to create a simple scatter chart.
*
* @author Roman Kashitsyn
*/ */
public class ScatterChart { public class ScatterChart {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet 1"); Sheet sheet = wb.createSheet("Sheet 1");
final int NUM_OF_ROWS = 3; final int NUM_OF_ROWS = 3;
@ -49,7 +62,7 @@ public class ScatterChart {
} }
} }
Drawing drawing = sheet.createDrawingPatriarch(); Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
Chart chart = drawing.createChart(anchor); Chart chart = drawing.createChart(anchor);
@ -76,5 +89,6 @@ public class ScatterChart {
FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx"); FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -18,6 +18,7 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
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;
@ -29,7 +30,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
*/ */
public class ShiftRows { public class ShiftRows {
public static void main(String[]args) throws Exception { public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1"); Sheet sheet = wb.createSheet("Sheet1");
@ -54,7 +55,7 @@ public class ShiftRows {
FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx"); FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }

View File

@ -17,17 +17,18 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import org.apache.poi.ss.usermodel.Workbook; import java.io.FileOutputStream;
import java.io.IOException;
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.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
/** /**
* How to set spklit and freeze panes * How to set split and freeze panes
*/ */
public class SplitAndFreezePanes { public class SplitAndFreezePanes {
public static void main(String[]args) throws Exception { public static void main(String[]args) throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet"); Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet"); Sheet sheet2 = wb.createSheet("second sheet");
@ -46,5 +47,6 @@ public class SplitAndFreezePanes {
FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx"); FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -18,18 +18,17 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.POIXMLProperties; import org.apache.poi.POIXMLProperties;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
* How to set extended and custom properties * How to set extended and custom properties
*
* @author Yegor Kozlov
*/ */
public class WorkbookProperties { public class WorkbookProperties {
public static void main(String[]args) throws Exception { public static void main(String[]args) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
workbook.createSheet("Workbook Properties"); workbook.createSheet("Workbook Properties");
@ -59,7 +58,7 @@ public class WorkbookProperties {
FileOutputStream out = new FileOutputStream("workbook.xlsx"); FileOutputStream out = new FileOutputStream("workbook.xlsx");
workbook.write(out); workbook.write(out);
out.close(); out.close();
workbook.close();
} }

View File

@ -17,17 +17,23 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
* Working with borders * Working with borders
*/ */
public class WorkingWithBorders { public class WorkingWithBorders {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("borders"); Sheet sheet = wb.createSheet("borders");
@ -40,13 +46,13 @@ public class WorkingWithBorders {
// Style the cell with borders all around. // Style the cell with borders all around.
CellStyle style = wb.createCellStyle(); CellStyle style = wb.createCellStyle();
style.setBorderBottom(CellStyle.BORDER_THIN); style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN); style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREEN.getIndex()); style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
style.setBorderRight(CellStyle.BORDER_THIN); style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLUE.getIndex()); style.setRightBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED); style.setBorderTop(BorderStyle.MEDIUM_DASHED);
style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setTopBorderColor(IndexedColors.BLACK.getIndex());
cell.setCellStyle(style); cell.setCellStyle(style);
@ -54,5 +60,6 @@ public class WorkingWithBorders {
FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx"); FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -17,17 +17,22 @@
package org.apache.poi.xssf.usermodel.examples; package org.apache.poi.xssf.usermodel.examples;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.IndexedColors;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
* Working with Fonts * Working with Fonts
*/ */
public class WorkingWithFonts { public class WorkingWithFonts {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet("Fonts"); Sheet sheet = wb.createSheet("Fonts");
@ -97,5 +102,6 @@ public class WorkingWithFonts {
FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx"); FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx");
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
wb.close();
} }
} }

View File

@ -30,7 +30,7 @@ import org.apache.poi.xwpf.usermodel.XWPFRun;
public class BetterHeaderFooterExample { public class BetterHeaderFooterExample {
public static void main(String[] args) { public static void main(String[] args) throws IOException {
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
XWPFParagraph p = doc.createParagraph(); XWPFParagraph p = doc.createParagraph();
@ -48,13 +48,9 @@ public class BetterHeaderFooterExample {
XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT); XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT);
foot.createParagraph().createRun().setText("footer"); foot.createParagraph().createRun().setText("footer");
try {
OutputStream os = new FileOutputStream(new File("header2.docx")); OutputStream os = new FileOutputStream(new File("header2.docx"));
doc.write(os); doc.write(os);
os.close();
doc.close(); doc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
} }

View File

@ -23,33 +23,31 @@ import static org.junit.Assert.assertEquals;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List; import java.util.List;
import java.util.Iterator;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
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.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
/** /**
* Tests whether it is possible to successfully update an Excel workbook that is * Tests whether it is possible to successfully update an Excel workbook that is
* embedded into a WordprocessingML document. Note that the test has currently * embedded into a WordprocessingML document. Note that the test has currently
* only been conducted with a binary Excel workbook and NOT yet with a * only been conducted with a binary Excel workbook and NOT yet with a
* SpreadsheetML workbook embedded into the document. * SpreadsheetML workbook embedded into the document.<p>
* *
* <p>
* This code was successfully tested with the following file from the POI test collection: * This code was successfully tested with the following file from the POI test collection:
* http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx * http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx
* </p>
*
* @author Mark B
*/ */
public class UpdateEmbeddedDoc { public class UpdateEmbeddedDoc {
@ -79,27 +77,15 @@ public class UpdateEmbeddedDoc {
this.docFile = new File(filename); this.docFile = new File(filename);
FileInputStream fis = null; FileInputStream fis = null;
if (!this.docFile.exists()) { if (!this.docFile.exists()) {
throw new FileNotFoundException("The Word dcoument " + throw new FileNotFoundException("The Word dcoument " + filename + " does not exist.");
filename +
" does not exist.");
} }
try { try {
// Open the Word document file and instantiate the XWPFDocument // Open the Word document file and instantiate the XWPFDocument
// class. // class.
fis = new FileInputStream(this.docFile); fis = new FileInputStream(this.docFile);
this.doc = new XWPFDocument(fis); this.doc = new XWPFDocument(fis);
} finally { } finally {
if (fis != null) { IOUtils.closeQuietly(fis);
try {
fis.close();
fis = null;
} catch (IOException ioEx) {
System.out.println("IOException caught trying to close " +
"FileInputStream in the constructor of " +
"UpdateEmbeddedDoc.");
}
}
} }
} }
@ -121,35 +107,38 @@ public class UpdateEmbeddedDoc {
* file system. * file system.
*/ */
public void updateEmbeddedDoc() throws OpenXML4JException, IOException { public void updateEmbeddedDoc() throws OpenXML4JException, IOException {
Workbook workbook = null;
Sheet sheet = null;
Row row = null;
Cell cell = null;
PackagePart pPart = null;
Iterator<PackagePart> pIter = null;
List<PackagePart> embeddedDocs = this.doc.getAllEmbedds(); List<PackagePart> embeddedDocs = this.doc.getAllEmbedds();
if (embeddedDocs != null && !embeddedDocs.isEmpty()) { for (PackagePart pPart : embeddedDocs) {
pIter = embeddedDocs.iterator(); String ext = pPart.getPartName().getExtension();
while (pIter.hasNext()) { if (BINARY_EXTENSION.equals(ext) || OPENXML_EXTENSION.equals(ext)) {
pPart = pIter.next(); // Get an InputStream from the package part and pass that
if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) ||
pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) {
// Get an InputStream from the pacage part and pass that
// to the create method of the WorkbookFactory class. Update // to the create method of the WorkbookFactory class. Update
// the resulting Workbook and then stream that out again // the resulting Workbook and then stream that out again
// using an OutputStream obtained from the same PackagePart. // using an OutputStream obtained from the same PackagePart.
workbook = WorkbookFactory.create(pPart.getInputStream()); InputStream is = pPart.getInputStream();
sheet = workbook.getSheetAt(SHEET_NUM); Workbook workbook = null;
row = sheet.getRow(ROW_NUM); OutputStream os = null;
cell = row.getCell(CELL_NUM); try {
workbook = WorkbookFactory.create(is);
Sheet sheet = workbook.getSheetAt(SHEET_NUM);
Row row = sheet.getRow(ROW_NUM);
Cell cell = row.getCell(CELL_NUM);
cell.setCellValue(NEW_VALUE); cell.setCellValue(NEW_VALUE);
workbook.write(pPart.getOutputStream()); os = pPart.getOutputStream();
workbook.write(os);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(workbook);
IOUtils.closeQuietly(is);
}
} }
} }
if (!embeddedDocs.isEmpty()) {
// Finally, write the newly modified Word document out to file. // Finally, write the newly modified Word document out to file.
this.doc.write(new FileOutputStream(this.docFile)); FileOutputStream fos = new FileOutputStream(this.docFile);
this.doc.write(fos);
fos.close();
} }
} }
@ -179,24 +168,20 @@ public class UpdateEmbeddedDoc {
* file system. * file system.
*/ */
public void checkUpdatedDoc() throws OpenXML4JException, IOException { public void checkUpdatedDoc() throws OpenXML4JException, IOException {
for (PackagePart pPart : this.doc.getAllEmbedds()) {
String ext = pPart.getPartName().getExtension();
if (BINARY_EXTENSION.equals(ext) || OPENXML_EXTENSION.equals(ext)) {
InputStream is = pPart.getInputStream();
Workbook workbook = null; Workbook workbook = null;
Sheet sheet = null; try {
Row row = null; workbook = WorkbookFactory.create(is);
Cell cell = null; Sheet sheet = workbook.getSheetAt(SHEET_NUM);
PackagePart pPart = null; Row row = sheet.getRow(ROW_NUM);
Iterator<PackagePart> pIter = null; Cell cell = row.getCell(CELL_NUM);
List<PackagePart> embeddedDocs = this.doc.getAllEmbedds();
if (embeddedDocs != null && !embeddedDocs.isEmpty()) {
pIter = embeddedDocs.iterator();
while (pIter.hasNext()) {
pPart = pIter.next();
if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) ||
pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) {
workbook = WorkbookFactory.create(pPart.getInputStream());
sheet = workbook.getSheetAt(SHEET_NUM);
row = sheet.getRow(ROW_NUM);
cell = row.getCell(CELL_NUM);
assertEquals(cell.getNumericCellValue(), NEW_VALUE, 0.0001); assertEquals(cell.getNumericCellValue(), NEW_VALUE, 0.0001);
} finally {
IOUtils.closeQuietly(workbook);
IOUtils.closeQuietly(is);
} }
} }
} }
@ -206,16 +191,11 @@ public class UpdateEmbeddedDoc {
* Code to test updating of the embedded Excel workbook. * Code to test updating of the embedded Excel workbook.
* *
* @param args * @param args
* @throws OpenXML4JException
*/ */
public static void main(String[] args) { public static void main(String[] args) throws IOException, OpenXML4JException {
try {
UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]); UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]);
ued.updateEmbeddedDoc(); ued.updateEmbeddedDoc();
ued.checkUpdatedDoc(); ued.checkUpdatedDoc();
} catch (Exception ex) {
System.out.println(ex.getClass().getName());
System.out.println(ex.getMessage());
ex.printStackTrace(System.out);
}
} }
} }

View File

@ -56,9 +56,8 @@ public final class LittleEndianByteArrayInputStream extends ByteArrayInputStream
final int size = LittleEndianConsts.INT_SIZE; final int size = LittleEndianConsts.INT_SIZE;
checkPosition(size); checkPosition(size);
int le = LittleEndian.getInt(buf, pos); int le = LittleEndian.getInt(buf, pos);
if (super.skip(size) < size) { long skipped = super.skip(size);
throw new RuntimeException("Buffer overrun"); assert skipped == size : "Buffer overrun";
}
return le; return le;
} }
@ -67,9 +66,8 @@ public final class LittleEndianByteArrayInputStream extends ByteArrayInputStream
final int size = LittleEndianConsts.LONG_SIZE; final int size = LittleEndianConsts.LONG_SIZE;
checkPosition(size); checkPosition(size);
long le = LittleEndian.getLong(buf, pos); long le = LittleEndian.getLong(buf, pos);
if (super.skip(size) < size) { long skipped = super.skip(size);
throw new RuntimeException("Buffer overrun"); assert skipped == size : "Buffer overrun";
}
return le; return le;
} }
@ -88,9 +86,8 @@ public final class LittleEndianByteArrayInputStream extends ByteArrayInputStream
final int size = LittleEndianConsts.SHORT_SIZE; final int size = LittleEndianConsts.SHORT_SIZE;
checkPosition(size); checkPosition(size);
int le = LittleEndian.getUShort(buf, pos); int le = LittleEndian.getUShort(buf, pos);
if (super.skip(size) < size) { long skipped = super.skip(size);
throw new RuntimeException("Buffer overrun"); assert skipped == size : "Buffer overrun";
}
return le; return le;
} }

View File

@ -261,7 +261,7 @@ public class WorkbookFactory {
} }
} catch(OfficeXmlFileException e) { } catch(OfficeXmlFileException e) {
// opening as .xls failed => try opening as .xlsx // opening as .xls failed => try opening as .xlsx
OPCPackage pkg = OPCPackage.open(file, readOnly ? PackageAccess.READ : PackageAccess.READ_WRITE); OPCPackage pkg = OPCPackage.open(file, readOnly ? PackageAccess.READ : PackageAccess.READ_WRITE); // NOSONAR
try { try {
return new XSSFWorkbook(pkg); return new XSSFWorkbook(pkg);
} catch (Exception ioe) { } catch (Exception ioe) {

View File

@ -48,10 +48,12 @@ import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
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.IOUtils;
import org.apache.poi.util.Internal; import org.apache.poi.util.Internal;
import org.apache.poi.util.NotImplemented; import org.apache.poi.util.NotImplemented;
import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger; import org.apache.poi.util.POILogger;
import org.apache.poi.util.Removal;
import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFile;
import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFSheet;
@ -233,20 +235,14 @@ public class SXSSFWorkbook implements Workbook {
public SXSSFWorkbook(XSSFWorkbook workbook, int rowAccessWindowSize, boolean compressTmpFiles, boolean useSharedStringsTable){ public SXSSFWorkbook(XSSFWorkbook workbook, int rowAccessWindowSize, boolean compressTmpFiles, boolean useSharedStringsTable){
setRandomAccessWindowSize(rowAccessWindowSize); setRandomAccessWindowSize(rowAccessWindowSize);
setCompressTempFiles(compressTmpFiles); setCompressTempFiles(compressTmpFiles);
if (workbook == null) if (workbook == null) {
{
_wb=new XSSFWorkbook(); _wb=new XSSFWorkbook();
_sharedStringSource = useSharedStringsTable ? _wb.getSharedStringSource() : null; _sharedStringSource = useSharedStringsTable ? _wb.getSharedStringSource() : null;
} } else {
else
{
_wb=workbook; _wb=workbook;
_sharedStringSource = useSharedStringsTable ? _wb.getSharedStringSource() : null; _sharedStringSource = useSharedStringsTable ? _wb.getSharedStringSource() : null;
final int numberOfSheets = _wb.getNumberOfSheets(); for ( Sheet sheet : _wb ) {
for ( int i = 0; i < numberOfSheets; i++ ) createAndRegisterSXSSFSheet( (XSSFSheet)sheet );
{
XSSFSheet sheet = _wb.getSheetAt( i );
createAndRegisterSXSSFSheet( sheet );
} }
} }
} }
@ -364,62 +360,44 @@ public class SXSSFWorkbook implements Workbook {
{ {
for(XSSFSheet sheet : _sxFromXHash.values()) for(XSSFSheet sheet : _sxFromXHash.values())
{ {
if(sheetRef.equals(sheet.getPackagePart().getPartName().getName().substring(1))) return sheet; if(sheetRef.equals(sheet.getPackagePart().getPartName().getName().substring(1))) {
return sheet;
}
} }
return null; return null;
} }
protected void injectData(ZipEntrySource zipEntrySource, OutputStream out) throws IOException protected void injectData(ZipEntrySource zipEntrySource, OutputStream out) throws IOException {
{ try {
try
{
ZipOutputStream zos = new ZipOutputStream(out); ZipOutputStream zos = new ZipOutputStream(out);
try try {
{
Enumeration<? extends ZipEntry> en = zipEntrySource.getEntries(); Enumeration<? extends ZipEntry> en = zipEntrySource.getEntries();
while (en.hasMoreElements()) while (en.hasMoreElements()) {
{
ZipEntry ze = en.nextElement(); ZipEntry ze = en.nextElement();
zos.putNextEntry(new ZipEntry(ze.getName())); zos.putNextEntry(new ZipEntry(ze.getName()));
InputStream is = zipEntrySource.getInputStream(ze); InputStream is = zipEntrySource.getInputStream(ze);
XSSFSheet xSheet=getSheetFromZipEntryName(ze.getName()); XSSFSheet xSheet=getSheetFromZipEntryName(ze.getName());
if(xSheet!=null) if(xSheet!=null) {
{
SXSSFSheet sxSheet=getSXSSFSheet(xSheet); SXSSFSheet sxSheet=getSXSSFSheet(xSheet);
InputStream xis = sxSheet.getWorksheetXMLInputStream(); InputStream xis = sxSheet.getWorksheetXMLInputStream();
try try {
{
copyStreamAndInjectWorksheet(is,zos,xis); copyStreamAndInjectWorksheet(is,zos,xis);
} } finally {
finally
{
xis.close(); xis.close();
} }
} } else {
else IOUtils.copy(is, zos);
{
copyStream(is, zos);
} }
is.close(); is.close();
} }
} } finally {
finally
{
zos.close(); zos.close();
} }
} } finally {
finally
{
zipEntrySource.close(); zipEntrySource.close();
} }
} }
private static void copyStream(InputStream in, OutputStream out) throws IOException {
byte[] chunk = new byte[1024];
int count;
while ((count = in.read(chunk)) >=0 ) {
out.write(chunk,0,count);
}
}
private static void copyStreamAndInjectWorksheet(InputStream in, OutputStream out, InputStream worksheetData) throws IOException { private static void copyStreamAndInjectWorksheet(InputStream in, OutputStream out, InputStream worksheetData) throws IOException {
InputStreamReader inReader=new InputStreamReader(in,"UTF-8"); //TODO: Is it always UTF-8 or do we need to read the xml encoding declaration in the file? If not, we should perhaps use a SAX reader instead. InputStreamReader inReader=new InputStreamReader(in,"UTF-8"); //TODO: Is it always UTF-8 or do we need to read the xml encoding declaration in the file? If not, we should perhaps use a SAX reader instead.
OutputStreamWriter outWriter=new OutputStreamWriter(out,"UTF-8"); OutputStreamWriter outWriter=new OutputStreamWriter(out,"UTF-8");
@ -492,7 +470,9 @@ public class SXSSFWorkbook implements Workbook {
} }
else else
{ {
if(pos>0) outWriter.write(s,0,pos); if(pos>0) {
outWriter.write(s,0,pos);
}
if(c==s.charAt(0)) if(c==s.charAt(0))
{ {
pos=1; pos=1;
@ -511,12 +491,13 @@ public class SXSSFWorkbook implements Workbook {
outWriter.flush(); outWriter.flush();
} }
//Copy the worksheet data to "out". //Copy the worksheet data to "out".
copyStream(worksheetData,out); IOUtils.copy(worksheetData,out);
outWriter.write("</sheetData>"); outWriter.write("</sheetData>");
outWriter.flush(); outWriter.flush();
//Copy the rest of "in" to "out". //Copy the rest of "in" to "out".
while(((c=inReader.read())!=-1)) while(((c=inReader.read())!=-1)) {
outWriter.write(c); outWriter.write(c);
}
outWriter.flush(); outWriter.flush();
} }
@ -830,7 +811,9 @@ public class SXSSFWorkbook implements Workbook {
* @return the font with the matched attributes or <code>null</code> * @return the font with the matched attributes or <code>null</code>
* @deprecated POI 3.15 beta 2. Use {@link #findFont(boolean, short, short, String, boolean, boolean, short, byte)} instead. * @deprecated POI 3.15 beta 2. Use {@link #findFont(boolean, short, short, String, boolean, boolean, short, byte)} instead.
*/ */
@Deprecated
@Override @Override
@Removal(version="3.17")
public Font findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) public Font findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline)
{ {
return _wb.findFont(boldWeight, color, fontHeight, name, italic, strikeout, typeOffset, underline); return _wb.findFont(boldWeight, color, fontHeight, name, italic, strikeout, typeOffset, underline);
@ -934,7 +917,7 @@ public class SXSSFWorkbook implements Workbook {
} }
/** /**
* Write out this workbook to an Outputstream. * Write out this workbook to an OutputStream.
* *
* @param stream - the java OutputStream you wish to write to * @param stream - the java OutputStream you wish to write to
* @exception IOException if anything can't be written. * @exception IOException if anything can't be written.
@ -946,29 +929,25 @@ public class SXSSFWorkbook implements Workbook {
//Save the template //Save the template
File tmplFile = TempFile.createTempFile("poi-sxssf-template", ".xlsx"); File tmplFile = TempFile.createTempFile("poi-sxssf-template", ".xlsx");
try boolean deleted;
{ try {
FileOutputStream os = new FileOutputStream(tmplFile); FileOutputStream os = new FileOutputStream(tmplFile);
try try {
{
_wb.write(os); _wb.write(os);
} } finally {
finally
{
os.close(); os.close();
} }
//Substitute the template entries with the generated sheet data files //Substitute the template entries with the generated sheet data files
final ZipEntrySource source = new ZipFileZipEntrySource(new ZipFile(tmplFile)); final ZipEntrySource source = new ZipFileZipEntrySource(new ZipFile(tmplFile));
injectData(source, stream); injectData(source, stream);
} finally {
deleted = tmplFile.delete();
} }
finally if(!deleted) {
{
if(!tmplFile.delete()) {
throw new IOException("Could not delete temporary file after processing: " + tmplFile); throw new IOException("Could not delete temporary file after processing: " + tmplFile);
} }
} }
}
protected void flushSheets() throws IOException { protected void flushSheets() throws IOException {
for (SXSSFSheet sheet : _xFromSxHash.values()) for (SXSSFSheet sheet : _xFromSxHash.values())
@ -1046,6 +1025,7 @@ public class SXSSFWorkbook implements Workbook {
*/ */
@Override @Override
@Deprecated @Deprecated
@Removal(version="3.18")
public Name getNameAt(int nameIndex) public Name getNameAt(int nameIndex)
{ {
return _wb.getNameAt(nameIndex); return _wb.getNameAt(nameIndex);
@ -1076,6 +1056,7 @@ public class SXSSFWorkbook implements Workbook {
*/ */
@Override @Override
@Deprecated @Deprecated
@Removal(version="3.18")
public int getNameIndex(String name) public int getNameIndex(String name)
{ {
return _wb.getNameIndex(name); return _wb.getNameIndex(name);
@ -1090,6 +1071,7 @@ public class SXSSFWorkbook implements Workbook {
*/ */
@Override @Override
@Deprecated @Deprecated
@Removal(version="3.18")
public void removeName(int index) public void removeName(int index)
{ {
_wb.removeName(index); _wb.removeName(index);
@ -1104,6 +1086,7 @@ public class SXSSFWorkbook implements Workbook {
*/ */
@Override @Override
@Deprecated @Deprecated
@Removal(version="3.18")
public void removeName(String name) public void removeName(String name)
{ {
_wb.removeName(name); _wb.removeName(name);

View File

@ -46,6 +46,7 @@ import org.apache.poi.ss.util.CellReference;
import org.apache.poi.util.Beta; import org.apache.poi.util.Beta;
import org.apache.poi.util.Internal; import org.apache.poi.util.Internal;
import org.apache.poi.util.LocaleUtil; import org.apache.poi.util.LocaleUtil;
import org.apache.poi.util.Removal;
import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.model.StylesTable;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
@ -180,32 +181,20 @@ public final class XSSFCell implements Cell {
// Copy CellStyle // Copy CellStyle
if (policy.isCopyCellStyle()) { if (policy.isCopyCellStyle()) {
if (srcCell != null) { setCellStyle(srcCell == null ? null : srcCell.getCellStyle());
setCellStyle(srcCell.getCellStyle());
}
else {
// clear cell style
setCellStyle(null);
}
} }
final Hyperlink srcHyperlink = (srcCell == null) ? null : srcCell.getHyperlink();
if (policy.isMergeHyperlink()) { if (policy.isMergeHyperlink()) {
// if srcCell doesn't have a hyperlink and destCell has a hyperlink, don't clear destCell's hyperlink // if srcCell doesn't have a hyperlink and destCell has a hyperlink, don't clear destCell's hyperlink
final Hyperlink srcHyperlink = srcCell.getHyperlink();
if (srcHyperlink != null) { if (srcHyperlink != null) {
setHyperlink(new XSSFHyperlink(srcHyperlink)); setHyperlink(new XSSFHyperlink(srcHyperlink));
} }
} } else if (policy.isCopyHyperlink()) {
else if (policy.isCopyHyperlink()) {
// overwrite the hyperlink at dest cell with srcCell's hyperlink // overwrite the hyperlink at dest cell with srcCell's hyperlink
// if srcCell doesn't have a hyperlink, clear the hyperlink (if one exists) at destCell // if srcCell doesn't have a hyperlink, clear the hyperlink (if one exists) at destCell
final Hyperlink srcHyperlink = srcCell.getHyperlink(); setHyperlink(srcHyperlink == null ? null : new XSSFHyperlink(srcHyperlink));
if (srcHyperlink == null) {
setHyperlink(null);
}
else {
setHyperlink(new XSSFHyperlink(srcHyperlink));
}
} }
} }
@ -303,7 +292,9 @@ public final class XSSFCell implements Cell {
case NUMERIC: case NUMERIC:
if(_cell.isSetV()) { if(_cell.isSetV()) {
String v = _cell.getV(); String v = _cell.getV();
if (v.isEmpty()) return 0.0; if (v.isEmpty()) {
return 0.0;
}
try { try {
return Double.parseDouble(v); return Double.parseDouble(v);
} catch(NumberFormatException e) { } catch(NumberFormatException e) {
@ -487,7 +478,9 @@ public final class XSSFCell implements Cell {
*/ */
protected String getCellFormula(XSSFEvaluationWorkbook fpb) { protected String getCellFormula(XSSFEvaluationWorkbook fpb) {
CellType cellType = getCellTypeEnum(); CellType cellType = getCellTypeEnum();
if(cellType != CellType.FORMULA) throw typeMismatch(CellType.FORMULA, cellType, false); if(cellType != CellType.FORMULA) {
throw typeMismatch(CellType.FORMULA, cellType, false);
}
CTCellFormula f = _cell.getF(); CTCellFormula f = _cell.getF();
if (isPartOfArrayFormulaGroup() && f == null) { if (isPartOfArrayFormulaGroup() && f == null) {
@ -510,8 +503,10 @@ public final class XSSFCell implements Cell {
XSSFSheet sheet = getSheet(); XSSFSheet sheet = getSheet();
CTCellFormula f = sheet.getSharedFormula(si); CTCellFormula f = sheet.getSharedFormula(si);
if(f == null) throw new IllegalStateException( if(f == null) {
throw new IllegalStateException(
"Master cell of a shared formula with sid="+si+" was not found"); "Master cell of a shared formula with sid="+si+" was not found");
}
String sharedFormula = f.getStringValue(); String sharedFormula = f.getStringValue();
//Range of cells which the shared formula applies to //Range of cells which the shared formula applies to
@ -560,7 +555,9 @@ public final class XSSFCell implements Cell {
XSSFWorkbook wb = _row.getSheet().getWorkbook(); XSSFWorkbook wb = _row.getSheet().getWorkbook();
if (formula == null) { if (formula == null) {
wb.onDeleteFormula(this); wb.onDeleteFormula(this);
if(_cell.isSetF()) _cell.unsetF(); if(_cell.isSetF()) {
_cell.unsetF();
}
return; return;
} }
@ -571,7 +568,9 @@ public final class XSSFCell implements Cell {
CTCellFormula f = CTCellFormula.Factory.newInstance(); CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue(formula); f.setStringValue(formula);
_cell.setF(f); _cell.setF(f);
if(_cell.isSetV()) _cell.unsetV(); if(_cell.isSetV()) {
_cell.unsetV();
}
} }
/** /**
@ -644,7 +643,9 @@ public final class XSSFCell implements Cell {
@Override @Override
public void setCellStyle(CellStyle style) { public void setCellStyle(CellStyle style) {
if(style == null) { if(style == null) {
if(_cell.isSetS()) _cell.unsetS(); if(_cell.isSetS()) {
_cell.unsetS();
}
} else { } else {
XSSFCellStyle xStyle = (XSSFCellStyle)style; XSSFCellStyle xStyle = (XSSFCellStyle)style;
xStyle.verifyBelongsToStylesSource(_stylesSource); xStyle.verifyBelongsToStylesSource(_stylesSource);
@ -670,7 +671,9 @@ public final class XSSFCell implements Cell {
* @return the cell type * @return the cell type
* @deprecated 3.15. Will return a {@link CellType} enum in the future. * @deprecated 3.15. Will return a {@link CellType} enum in the future.
*/ */
@Deprecated
@Override @Override
@Removal(version="3.17")
public int getCellType() { public int getCellType() {
return getCellTypeEnum().getCode(); return getCellTypeEnum().getCode();
} }
@ -684,7 +687,9 @@ public final class XSSFCell implements Cell {
*/ */
@Override @Override
public CellType getCellTypeEnum() { public CellType getCellTypeEnum() {
if (isFormulaCell()) return CellType.FORMULA; if (isFormulaCell()) {
return CellType.FORMULA;
}
return getBaseCellType(true); return getBaseCellType(true);
} }
@ -700,7 +705,9 @@ public final class XSSFCell implements Cell {
* on the cached value of the formula * on the cached value of the formula
* @deprecated 3.15. Will return a {@link CellType} enum in the future. * @deprecated 3.15. Will return a {@link CellType} enum in the future.
*/ */
@Deprecated
@Override @Override
@Removal(version="3.17")
public int getCachedFormulaResultType() { public int getCachedFormulaResultType() {
return getCachedFormulaResultTypeEnum().getCode(); return getCachedFormulaResultTypeEnum().getCode();
} }
@ -826,7 +833,9 @@ public final class XSSFCell implements Cell {
*/ */
public String getErrorCellString() throws IllegalStateException { public String getErrorCellString() throws IllegalStateException {
CellType cellType = getBaseCellType(true); CellType cellType = getBaseCellType(true);
if(cellType != CellType.ERROR) throw typeMismatch(CellType.ERROR, cellType, false); if(cellType != CellType.ERROR) {
throw typeMismatch(CellType.ERROR, cellType, false);
}
return _cell.getV(); return _cell.getV();
} }
@ -897,7 +906,9 @@ public final class XSSFCell implements Cell {
private void setBlank(){ private void setBlank(){
CTCell blank = CTCell.Factory.newInstance(); CTCell blank = CTCell.Factory.newInstance();
blank.setR(_cell.getR()); blank.setR(_cell.getR());
if(_cell.isSetS()) blank.setS(_cell.getS()); if(_cell.isSetS()) {
blank.setS(_cell.getS());
}
_cell.set(blank); _cell.set(blank);
} }
@ -925,7 +936,9 @@ public final class XSSFCell implements Cell {
* @see CellType#ERROR * @see CellType#ERROR
* @deprecated POI 3.15 beta 3. Use {@link #setCellType(CellType)} instead. * @deprecated POI 3.15 beta 3. Use {@link #setCellType(CellType)} instead.
*/ */
@Deprecated
@Override @Override
@Removal(version="3.17")
public void setCellType(int cellType) { public void setCellType(int cellType) {
setCellType(CellType.forInt(cellType)); setCellType(CellType.forInt(cellType));
} }
@ -964,7 +977,9 @@ public final class XSSFCell implements Cell {
CTCellFormula f = CTCellFormula.Factory.newInstance(); CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue("0"); f.setStringValue("0");
_cell.setF(f); _cell.setF(f);
if(_cell.isSetT()) _cell.unsetT(); if(_cell.isSetT()) {
_cell.unsetT();
}
} }
break; break;
case BLANK: case BLANK:

View File

@ -78,7 +78,7 @@ public class XSSFPivotCacheDefinition extends POIXMLDocumentPart{
options.setLoadReplaceDocumentElement(null); options.setLoadReplaceDocumentElement(null);
ctPivotCacheDefinition = CTPivotCacheDefinition.Factory.parse(is, options); ctPivotCacheDefinition = CTPivotCacheDefinition.Factory.parse(is, options);
} catch (XmlException e) { } catch (XmlException e) {
throw new IOException(e.getLocalizedMessage()); throw new IOException(e.getLocalizedMessage(), e);
} }
} }
@ -123,24 +123,32 @@ public class XSSFPivotCacheDefinition extends POIXMLDocumentPart{
final String ref = wsSource.getRef(); final String ref = wsSource.getRef();
final String name = wsSource.getName(); final String name = wsSource.getName();
if (ref == null && name == null) throw new IllegalArgumentException("Pivot cache must reference an area, named range, or table."); if (ref == null && name == null) {
throw new IllegalArgumentException("Pivot cache must reference an area, named range, or table.");
}
// this is the XML format, so tell the reference that. // this is the XML format, so tell the reference that.
if (ref != null) return new AreaReference(ref, SpreadsheetVersion.EXCEL2007); if (ref != null) {
return new AreaReference(ref, SpreadsheetVersion.EXCEL2007);
}
assert (name != null);
if (name != null) {
// named range or table? // named range or table?
final Name range = wb.getName(name); final Name range = wb.getName(name);
if (range != null) return new AreaReference(range.getRefersToFormula(), SpreadsheetVersion.EXCEL2007); if (range != null) {
return new AreaReference(range.getRefersToFormula(), SpreadsheetVersion.EXCEL2007);
}
// not a named range, check for a table. // not a named range, check for a table.
// do this second, as tables are sheet-specific, but named ranges are not, and may not have a sheet name given. // do this second, as tables are sheet-specific, but named ranges are not, and may not have a sheet name given.
final XSSFSheet sheet = (XSSFSheet) wb.getSheet(wsSource.getSheet()); final XSSFSheet sheet = (XSSFSheet) wb.getSheet(wsSource.getSheet());
for (XSSFTable table : sheet.getTables()) { for (XSSFTable table : sheet.getTables()) {
if (table.getName().equals(name)) { //case-sensitive? // TODO: case-sensitive?
if (name.equals(table.getName())) {
return new AreaReference(table.getStartCellReference(), table.getEndCellReference()); return new AreaReference(table.getStartCellReference(), table.getEndCellReference());
} }
} }
}
throw new IllegalArgumentException("Name '" + name + "' was not found."); throw new IllegalArgumentException("Name '" + name + "' was not found.");
} }

View File

@ -236,7 +236,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
private void initHyperlinks() { private void initHyperlinks() {
hyperlinks = new ArrayList<XSSFHyperlink>(); hyperlinks = new ArrayList<XSSFHyperlink>();
if(!worksheet.isSetHyperlinks()) return; if(!worksheet.isSetHyperlinks()) {
return;
}
try { try {
PackageRelationshipCollection hyperRels = PackageRelationshipCollection hyperRels =
@ -390,11 +392,15 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
// for each cell in sheet, if cell belongs to an array formula, check if merged region intersects array formula cells // for each cell in sheet, if cell belongs to an array formula, check if merged region intersects array formula cells
for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) { for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) {
XSSFRow row = getRow(rowIn); XSSFRow row = getRow(rowIn);
if (row == null) continue; if (row == null) {
continue;
}
for (int colIn = firstColumn; colIn <= lastColumn; colIn++) { for (int colIn = firstColumn; colIn <= lastColumn; colIn++) {
XSSFCell cell = row.getCell(colIn); XSSFCell cell = row.getCell(colIn);
if (cell == null) continue; if (cell == null) {
continue;
}
if (cell.isPartOfArrayFormulaGroup()) { if (cell.isPartOfArrayFormulaGroup()) {
CellRangeAddress arrayRange = cell.getArrayFormulaRange(); CellRangeAddress arrayRange = cell.getArrayFormulaRange();
@ -646,7 +652,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
// If both colSplit and rowSplit are zero then the existing freeze pane is removed // If both colSplit and rowSplit are zero then the existing freeze pane is removed
if(colSplit == 0 && rowSplit == 0){ if(colSplit == 0 && rowSplit == 0){
if(ctView.isSetPane()) ctView.unsetPane(); if(ctView.isSetPane()) {
ctView.unsetPane();
}
ctView.setSelectionArray(null); ctView.setSelectionArray(null);
return; return;
} }
@ -659,12 +667,16 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
if (colSplit > 0) { if (colSplit > 0) {
pane.setXSplit(colSplit); pane.setXSplit(colSplit);
} else { } else {
if(pane.isSetXSplit()) pane.unsetXSplit(); if(pane.isSetXSplit()) {
pane.unsetXSplit();
}
} }
if (rowSplit > 0) { if (rowSplit > 0) {
pane.setYSplit(rowSplit); pane.setYSplit(rowSplit);
} else { } else {
if(pane.isSetYSplit()) pane.unsetYSplit(); if(pane.isSetYSplit()) {
pane.unsetYSplit();
}
} }
pane.setState(STPaneState.FROZEN); pane.setState(STPaneState.FROZEN);
@ -756,7 +768,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @return the cell comment, if one exists. Otherwise return null. * @return the cell comment, if one exists. Otherwise return null.
* @deprecated as of 2015-11-23 (circa POI 3.14beta1). Use {@link #getCellComment(CellAddress)} instead. * @deprecated as of 2015-11-23 (circa POI 3.14beta1). Use {@link #getCellComment(CellAddress)} instead.
*/ */
@Deprecated
@Override @Override
@Removal(version="3.16")
public XSSFComment getCellComment(int row, int column) { public XSSFComment getCellComment(int row, int column) {
return getCellComment(new CellAddress(row, column)); return getCellComment(new CellAddress(row, column));
} }
@ -778,7 +792,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
CellAddress ref = new CellAddress(row, column); CellAddress ref = new CellAddress(row, column);
CTComment ctComment = sheetComments.getCTComment(ref); CTComment ctComment = sheetComments.getCTComment(ref);
if(ctComment == null) return null; if(ctComment == null) {
return null;
}
XSSFVMLDrawing vml = getVMLDrawing(false); XSSFVMLDrawing vml = getVMLDrawing(false);
return new XSSFComment(sheetComments, ctComment, return new XSSFComment(sheetComments, ctComment,
@ -1181,7 +1197,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/ */
@Override @Override
public double getMargin(short margin) { public double getMargin(short margin) {
if (!worksheet.isSetPageMargins()) return 0; if (!worksheet.isSetPageMargins()) {
return 0;
}
CTPageMargins pageMargins = worksheet.getPageMargins(); CTPageMargins pageMargins = worksheet.getPageMargins();
switch (margin) { switch (margin) {
@ -1252,7 +1270,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
@Override @Override
public CellRangeAddress getMergedRegion(int index) { public CellRangeAddress getMergedRegion(int index) {
CTMergeCells ctMergeCells = worksheet.getMergeCells(); CTMergeCells ctMergeCells = worksheet.getMergeCells();
if(ctMergeCells == null) throw new IllegalStateException("This worksheet does not contain merged regions"); if(ctMergeCells == null) {
throw new IllegalStateException("This worksheet does not contain merged regions");
}
CTMergeCell ctMergeCell = ctMergeCells.getMergeCellArray(index); CTMergeCell ctMergeCell = ctMergeCells.getMergeCellArray(index);
String ref = ctMergeCell.getRef(); String ref = ctMergeCell.getRef();
@ -1269,7 +1289,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
public List<CellRangeAddress> getMergedRegions() { public List<CellRangeAddress> getMergedRegions() {
List<CellRangeAddress> addresses = new ArrayList<CellRangeAddress>(); List<CellRangeAddress> addresses = new ArrayList<CellRangeAddress>();
CTMergeCells ctMergeCells = worksheet.getMergeCells(); CTMergeCells ctMergeCells = worksheet.getMergeCells();
if(ctMergeCells == null) return addresses; if(ctMergeCells == null) {
return addresses;
}
for(CTMergeCell ctMergeCell : ctMergeCells.getMergeCellArray()) { for(CTMergeCell ctMergeCell : ctMergeCells.getMergeCellArray()) {
String ref = ctMergeCell.getRef(); String ref = ctMergeCell.getRef();
@ -1302,7 +1324,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
public PaneInformation getPaneInformation() { public PaneInformation getPaneInformation() {
CTPane pane = getDefaultSheetView().getPane(); CTPane pane = getDefaultSheetView().getPane();
// no pane configured // no pane configured
if(pane == null) return null; if(pane == null) {
return null;
}
CellReference cellRef = pane.isSetTopLeftCell() ? new CellReference(pane.getTopLeftCell()) : null; CellReference cellRef = pane.isSetTopLeftCell() ? new CellReference(pane.getTopLeftCell()) : null;
return new PaneInformation((short)pane.getXSplit(), (short)pane.getYSplit(), return new PaneInformation((short)pane.getXSplit(), (short)pane.getYSplit(),
@ -1861,7 +1885,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/ */
@Override @Override
public void removeMergedRegion(int index) { public void removeMergedRegion(int index) {
if (!worksheet.isSetMergeCells()) return; if (!worksheet.isSetMergeCells()) {
return;
}
CTMergeCells ctMergeCells = worksheet.getMergeCells(); CTMergeCells ctMergeCells = worksheet.getMergeCells();
int size = ctMergeCells.sizeOfMergeCellArray(); int size = ctMergeCells.sizeOfMergeCellArray();
@ -1884,7 +1910,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/ */
@Override @Override
public void removeMergedRegions(Collection<Integer> indices) { public void removeMergedRegions(Collection<Integer> indices) {
if (!worksheet.isSetMergeCells()) return; if (!worksheet.isSetMergeCells()) {
return;
}
CTMergeCells ctMergeCells = worksheet.getMergeCells(); CTMergeCells ctMergeCells = worksheet.getMergeCells();
List<CTMergeCell> newMergeCells = new ArrayList<CTMergeCell>(ctMergeCells.sizeOfMergeCellArray()); List<CTMergeCell> newMergeCells = new ArrayList<CTMergeCell>(ctMergeCells.sizeOfMergeCellArray());
@ -2466,7 +2494,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/ */
@Override @Override
public void setColumnWidth(int columnIndex, int width) { public void setColumnWidth(int columnIndex, int width) {
if(width > 255*256) throw new IllegalArgumentException("The maximum column width for an individual cell is 255 characters."); if(width > 255*256) {
throw new IllegalArgumentException("The maximum column width for an individual cell is 255 characters.");
}
columnHelper.setColWidth(columnIndex, (double)width/256); columnHelper.setColWidth(columnIndex, (double)width/256);
columnHelper.setCustomWidth(columnIndex, true); columnHelper.setCustomWidth(columnIndex, true);
@ -2611,8 +2641,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
short level = getRow(rowIndex).getCTRow().getOutlineLevel(); short level = getRow(rowIndex).getCTRow().getOutlineLevel();
int currentRow = rowIndex; int currentRow = rowIndex;
while (getRow(currentRow) != null) { while (getRow(currentRow) != null) {
if (getRow(currentRow).getCTRow().getOutlineLevel() < level) if (getRow(currentRow).getCTRow().getOutlineLevel() < level) {
return currentRow + 1; return currentRow + 1;
}
currentRow--; currentRow--;
} }
return currentRow; return currentRow;
@ -2641,8 +2672,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @param rowNumber the zero based row index to expand * @param rowNumber the zero based row index to expand
*/ */
private void expandRow(int rowNumber) { private void expandRow(int rowNumber) {
if (rowNumber == -1) if (rowNumber == -1) {
return; return;
}
XSSFRow row = getRow(rowNumber); XSSFRow row = getRow(rowNumber);
// If it is already expanded do nothing. // If it is already expanded do nothing.
if (!row.getCTRow().isSetHidden()) { if (!row.getCTRow().isSetHidden()) {
@ -2756,6 +2788,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @param denominator The denominator for the zoom magnification. * @param denominator The denominator for the zoom magnification.
* @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #setZoom(int)} instead. * @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #setZoom(int)} instead.
*/ */
@Deprecated
@Removal(version="3.16") @Removal(version="3.16")
@Override @Override
public void setZoom(int numerator, int denominator) { public void setZoom(int numerator, int denominator) {
@ -2989,6 +3022,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
// we need to sort it in a way so the shifting does not mess up the structures, // we need to sort it in a way so the shifting does not mess up the structures,
// i.e. when shifting down, start from down and go up, when shifting up, vice-versa // i.e. when shifting down, start from down and go up, when shifting up, vice-versa
SortedMap<XSSFComment, Integer> commentsToShift = new TreeMap<XSSFComment, Integer>(new Comparator<XSSFComment>() { SortedMap<XSSFComment, Integer> commentsToShift = new TreeMap<XSSFComment, Integer>(new Comparator<XSSFComment>() {
@Override
public int compare(XSSFComment o1, XSSFComment o2) { public int compare(XSSFComment o1, XSSFComment o2) {
int row1 = o1.getRow(); int row1 = o1.getRow();
int row2 = o2.getRow(); int row2 = o2.getRow();
@ -3038,7 +3072,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
} }
} }
if(rownum < startRow || rownum > endRow) continue; if(rownum < startRow || rownum > endRow) {
continue;
}
if (!copyRowHeight) { if (!copyRowHeight) {
row.setHeight((short)-1); row.setHeight((short)-1);
@ -3266,6 +3302,8 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @param cellRef the location of the active cell, e.g. <code>A1</code>.. * @param cellRef the location of the active cell, e.g. <code>A1</code>..
* @deprecated 3.14beta2 (circa 2015-12-05). Use {@link #setActiveCell(CellAddress)} instead. * @deprecated 3.14beta2 (circa 2015-12-05). Use {@link #setActiveCell(CellAddress)} instead.
*/ */
@Deprecated
@Removal(version="3.16")
public void setActiveCell(String cellRef) { public void setActiveCell(String cellRef) {
CTSelection ctsel = getSheetTypeSelection(); CTSelection ctsel = getSheetTypeSelection();
ctsel.setActiveCell(cellRef); ctsel.setActiveCell(cellRef);
@ -3313,11 +3351,11 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/ */
private CTSheetView getDefaultSheetView() { private CTSheetView getDefaultSheetView() {
CTSheetViews views = getSheetTypeSheetViews(); CTSheetViews views = getSheetTypeSheetViews();
int sz = views == null ? 0 : views.sizeOfSheetViewArray(); if (views == null) {
if (sz == 0) {
return null; return null;
} }
return views.getSheetViewArray(sz - 1); int sz = views.sizeOfSheetViewArray();
return (sz == 0) ? null : views.getSheetViewArray(sz - 1);
} }
/** /**
@ -3835,6 +3873,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
return dataValidationHelper; return dataValidationHelper;
} }
@Override
public List<XSSFDataValidation> getDataValidations() { public List<XSSFDataValidation> getDataValidations() {
List<XSSFDataValidation> xssfValidations = new ArrayList<XSSFDataValidation>(); List<XSSFDataValidation> xssfValidations = new ArrayList<XSSFDataValidation>();
CTDataValidations dataValidations = this.worksheet.getDataValidations(); CTDataValidations dataValidations = this.worksheet.getDataValidations();
@ -3879,7 +3918,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
@Override @Override
public XSSFAutoFilter setAutoFilter(CellRangeAddress range) { public XSSFAutoFilter setAutoFilter(CellRangeAddress range) {
CTAutoFilter af = worksheet.getAutoFilter(); CTAutoFilter af = worksheet.getAutoFilter();
if(af == null) af = worksheet.addNewAutoFilter(); if(af == null) {
af = worksheet.addNewAutoFilter();
}
CellRangeAddress norm = new CellRangeAddress(range.getFirstRow(), range.getLastRow(), CellRangeAddress norm = new CellRangeAddress(range.getFirstRow(), range.getLastRow(),
range.getFirstColumn(), range.getLastColumn()); range.getFirstColumn(), range.getLastColumn());
@ -3945,7 +3986,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/ */
public XSSFColor getTabColor() { public XSSFColor getTabColor() {
CTSheetPr pr = worksheet.getSheetPr(); CTSheetPr pr = worksheet.getSheetPr();
if(pr == null) pr = worksheet.addNewSheetPr(); if(pr == null) {
pr = worksheet.addNewSheetPr();
}
if (!pr.isSetTabColor()) { if (!pr.isSetTabColor()) {
return null; return null;
} }
@ -3958,6 +4001,8 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @param colorIndex the indexed color to set, must be a constant from {@link org.apache.poi.ss.usermodel.IndexedColors} * @param colorIndex the indexed color to set, must be a constant from {@link org.apache.poi.ss.usermodel.IndexedColors}
* @deprecated 3.15-beta2. Removed in 3.17. Use {@link #setTabColor(XSSFColor)}. * @deprecated 3.15-beta2. Removed in 3.17. Use {@link #setTabColor(XSSFColor)}.
*/ */
@Deprecated
@Removal(version="3.17")
public void setTabColor(int colorIndex) { public void setTabColor(int colorIndex) {
IndexedColors indexedColor = IndexedColors.fromInt(colorIndex); IndexedColors indexedColor = IndexedColors.fromInt(colorIndex);
XSSFColor color = new XSSFColor(indexedColor); XSSFColor color = new XSSFColor(indexedColor);
@ -3971,7 +4016,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/ */
public void setTabColor(XSSFColor color) { public void setTabColor(XSSFColor color) {
CTSheetPr pr = worksheet.getSheetPr(); CTSheetPr pr = worksheet.getSheetPr();
if(pr == null) pr = worksheet.addNewSheetPr(); if(pr == null) {
pr = worksheet.addNewSheetPr();
}
pr.setTabColor(color.getCTColor()); pr.setTabColor(color.getCTColor());
} }
@ -4197,6 +4244,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
} }
return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() { return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() {
@Override
public void configureReference(CTWorksheetSource wsSource) { public void configureReference(CTWorksheetSource wsSource) {
final String[] firstCell = source.getFirstCell().getCellRefParts(); final String[] firstCell = source.getFirstCell().getCellRefParts();
final String firstRow = firstCell[1]; final String firstRow = firstCell[1];
@ -4269,6 +4317,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
} }
return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() { return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() {
@Override
public void configureReference(CTWorksheetSource wsSource) { public void configureReference(CTWorksheetSource wsSource) {
wsSource.setName(source.getNameName()); wsSource.setName(source.getNameName());
} }
@ -4297,6 +4346,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
@Beta @Beta
public XSSFPivotTable createPivotTable(final Table source, CellReference position) { public XSSFPivotTable createPivotTable(final Table source, CellReference position) {
return createPivotTable(position, getWorkbook().getSheet(source.getSheetName()), new PivotTableReferenceConfigurator() { return createPivotTable(position, getWorkbook().getSheet(source.getSheetName()), new PivotTableReferenceConfigurator() {
@Override
public void configureReference(CTWorksheetSource wsSource) { public void configureReference(CTWorksheetSource wsSource) {
wsSource.setName(source.getName()); wsSource.setName(source.getName());
} }
@ -4317,6 +4367,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
return tables; return tables;
} }
@Override
public int getColumnOutlineLevel(int columnIndex) { public int getColumnOutlineLevel(int columnIndex) {
CTCol col = columnHelper.getColumn(columnIndex, false); CTCol col = columnHelper.getColumn(columnIndex, false);
if (col == null) { if (col == null) {

View File

@ -352,15 +352,19 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
Map<String, ExternalLinksTable> elIdMap = new HashMap<String, ExternalLinksTable>(); Map<String, ExternalLinksTable> elIdMap = new HashMap<String, ExternalLinksTable>();
for(RelationPart rp : getRelationParts()){ for(RelationPart rp : getRelationParts()){
POIXMLDocumentPart p = rp.getDocumentPart(); POIXMLDocumentPart p = rp.getDocumentPart();
if(p instanceof SharedStringsTable) sharedStringSource = (SharedStringsTable)p; if(p instanceof SharedStringsTable) {
else if(p instanceof StylesTable) stylesSource = (StylesTable)p; sharedStringSource = (SharedStringsTable)p;
else if(p instanceof ThemesTable) theme = (ThemesTable)p; } else if(p instanceof StylesTable) {
else if(p instanceof CalculationChain) calcChain = (CalculationChain)p; stylesSource = (StylesTable)p;
else if(p instanceof MapInfo) mapInfo = (MapInfo)p; } else if(p instanceof ThemesTable) {
else if (p instanceof XSSFSheet) { theme = (ThemesTable)p;
} else if(p instanceof CalculationChain) {
calcChain = (CalculationChain)p;
} else if(p instanceof MapInfo) {
mapInfo = (MapInfo)p;
} else if (p instanceof XSSFSheet) {
shIdMap.put(rp.getRelationship().getId(), (XSSFSheet)p); shIdMap.put(rp.getRelationship().getId(), (XSSFSheet)p);
} } else if (p instanceof ExternalLinksTable) {
else if (p instanceof ExternalLinksTable) {
elIdMap.put(rp.getRelationship().getId(), (ExternalLinksTable)p); elIdMap.put(rp.getRelationship().getId(), (ExternalLinksTable)p);
} }
} }
@ -723,8 +727,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
*/ */
@Override @Override
public XSSFDataFormat createDataFormat() { public XSSFDataFormat createDataFormat() {
if (formatter == null) if (formatter == null) {
formatter = new XSSFDataFormat(stylesSource); formatter = new XSSFDataFormat(stylesSource);
}
return formatter; return formatter;
} }
@ -827,7 +832,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
validateSheetName(sheetname); validateSheetName(sheetname);
// YK: Mimic Excel and silently truncate sheet names longer than 31 characters // YK: Mimic Excel and silently truncate sheet names longer than 31 characters
if(sheetname.length() > 31) sheetname = sheetname.substring(0, 31); if(sheetname.length() > 31) {
sheetname = sheetname.substring(0, 31);
}
WorkbookUtil.validateSheetName(sheetname); WorkbookUtil.validateSheetName(sheetname);
CTSheet sheet = addSheet(sheetname); CTSheet sheet = addSheet(sheetname);
@ -860,7 +867,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
wrapper.sheet = sheet; wrapper.sheet = sheet;
sheet.setId(rp.getRelationship().getId()); sheet.setId(rp.getRelationship().getId());
sheet.setSheetId(sheetNumber); sheet.setSheetId(sheetNumber);
if (sheets.isEmpty()) wrapper.setSelected(true); if (sheets.isEmpty()) {
wrapper.setSelected(true);
}
sheets.add(wrapper); sheets.add(wrapper);
return wrapper; return wrapper;
} }
@ -1082,7 +1091,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
@Override @Override
public String getPrintArea(int sheetIndex) { public String getPrintArea(int sheetIndex) {
XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex); XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
if (name == null) return null; if (name == null) {
return null;
}
//adding one here because 0 indicates a global named region; doesnt make sense for print areas //adding one here because 0 indicates a global named region; doesnt make sense for print areas
return name.getRefersToFormula(); return name.getRefersToFormula();
@ -1146,7 +1157,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
public int getSheetIndex(Sheet sheet) { public int getSheetIndex(Sheet sheet) {
int idx = 0; int idx = 0;
for(XSSFSheet sh : sheets){ for(XSSFSheet sh : sheets){
if(sh == sheet) return idx; if(sh == sheet) {
return idx;
}
idx++; idx++;
} }
return -1; return -1;
@ -1439,7 +1452,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
List<XSSFName> toRemove = new ArrayList<XSSFName>(); List<XSSFName> toRemove = new ArrayList<XSSFName>();
for (XSSFName nm : namedRanges) { for (XSSFName nm : namedRanges) {
CTDefinedName ct = nm.getCTName(); CTDefinedName ct = nm.getCTName();
if(!ct.isSetLocalSheetId()) continue; if(!ct.isSetLocalSheetId()) {
continue;
}
if (ct.getLocalSheetId() == index) { if (ct.getLocalSheetId() == index) {
toRemove.add(nm); toRemove.add(nm);
} else if (ct.getLocalSheetId() > index){ } else if (ct.getLocalSheetId() > index){
@ -1639,21 +1654,28 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
*/ */
@Override @Override
public void setSheetName(int sheetIndex, String sheetname) { public void setSheetName(int sheetIndex, String sheetname) {
if (sheetname == null) {
throw new IllegalArgumentException( "sheetName must not be null" );
}
validateSheetIndex(sheetIndex); validateSheetIndex(sheetIndex);
String oldSheetName = getSheetName(sheetIndex); String oldSheetName = getSheetName(sheetIndex);
// YK: Mimic Excel and silently truncate sheet names longer than 31 characters // YK: Mimic Excel and silently truncate sheet names longer than 31 characters
if(sheetname != null && sheetname.length() > 31) sheetname = sheetname.substring(0, 31); if(sheetname.length() > 31) {
sheetname = sheetname.substring(0, 31);
}
WorkbookUtil.validateSheetName(sheetname); WorkbookUtil.validateSheetName(sheetname);
// findbugs fix - validateSheetName has already checked for null value
assert(sheetname != null);
// Do nothing if no change // Do nothing if no change
if (sheetname.equals(oldSheetName)) return; if (sheetname.equals(oldSheetName)) {
return;
}
// Check it isn't already taken // Check it isn't already taken
if (containsSheet(sheetname, sheetIndex )) if (containsSheet(sheetname, sheetIndex )) {
throw new IllegalArgumentException( "The workbook already contains a sheet of this name" ); throw new IllegalArgumentException( "The workbook already contains a sheet of this name" );
}
// Update references to the name // Update references to the name
XSSFFormulaUtils utils = new XSSFFormulaUtils(this); XSSFFormulaUtils utils = new XSSFFormulaUtils(this);
@ -1822,7 +1844,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
* Returns the Theme of current workbook. * Returns the Theme of current workbook.
*/ */
public ThemesTable getTheme() { public ThemesTable getTheme() {
if (stylesSource == null) return null; if (stylesSource == null) {
return null;
}
return stylesSource.getTheme(); return stylesSource.getTheme();
} }
@ -1832,7 +1856,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
*/ */
@Override @Override
public XSSFCreationHelper getCreationHelper() { public XSSFCreationHelper getCreationHelper() {
if(_creationHelper == null) _creationHelper = new XSSFCreationHelper(this); if(_creationHelper == null) {
_creationHelper = new XSSFCreationHelper(this);
}
return _creationHelper; return _creationHelper;
} }
@ -1857,9 +1883,10 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
ctName = ctName.substring(0, MAX_SENSITIVE_SHEET_NAME_LEN); ctName = ctName.substring(0, MAX_SENSITIVE_SHEET_NAME_LEN);
} }
if (excludeSheetIdx != i && name.equalsIgnoreCase(ctName)) if (excludeSheetIdx != i && name.equalsIgnoreCase(ctName)) {
return true; return true;
} }
}
return false; return false;
} }
@ -2149,7 +2176,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
* otherwise the given algorithm is used for calculating the hash password (Excel 2013) * otherwise the given algorithm is used for calculating the hash password (Excel 2013)
*/ */
public void setWorkbookPassword(String password, HashAlgorithm hashAlgo) { public void setWorkbookPassword(String password, HashAlgorithm hashAlgo) {
if (password == null && !workbookProtectionPresent()) return; if (password == null && !workbookProtectionPresent()) {
return;
}
setPassword(safeGetWorkbookProtection(), password, hashAlgo, "workbook"); setPassword(safeGetWorkbookProtection(), password, hashAlgo, "workbook");
} }
@ -2159,7 +2188,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
* @return true, if the hashes match (... though original password may differ ...) * @return true, if the hashes match (... though original password may differ ...)
*/ */
public boolean validateWorkbookPassword(String password) { public boolean validateWorkbookPassword(String password) {
if (!workbookProtectionPresent()) return (password == null); if (!workbookProtectionPresent()) {
return (password == null);
}
return validatePassword(safeGetWorkbookProtection(), password, "workbook"); return validatePassword(safeGetWorkbookProtection(), password, "workbook");
} }
@ -2171,7 +2202,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
* otherwise the given algorithm is used for calculating the hash password (Excel 2013) * otherwise the given algorithm is used for calculating the hash password (Excel 2013)
*/ */
public void setRevisionsPassword(String password, HashAlgorithm hashAlgo) { public void setRevisionsPassword(String password, HashAlgorithm hashAlgo) {
if (password == null && !workbookProtectionPresent()) return; if (password == null && !workbookProtectionPresent()) {
return;
}
setPassword(safeGetWorkbookProtection(), password, hashAlgo, "revisions"); setPassword(safeGetWorkbookProtection(), password, hashAlgo, "revisions");
} }
@ -2181,7 +2214,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook {
* @return true if the hashes match (... though original password may differ ...) * @return true if the hashes match (... though original password may differ ...)
*/ */
public boolean validateRevisionsPassword(String password) { public boolean validateRevisionsPassword(String password) {
if (!workbookProtectionPresent()) return (password == null); if (!workbookProtectionPresent()) {
return (password == null);
}
return validatePassword(safeGetWorkbookProtection(), password, "revisions"); return validatePassword(safeGetWorkbookProtection(), password, "revisions");
} }

View File

@ -26,38 +26,38 @@ public class NumericRanges {
public static final int OVERLAPS_2_WRAPS = 3; public static final int OVERLAPS_2_WRAPS = 3;
public static long[] getOverlappingRange(long[] range1, long[] range2) { public static long[] getOverlappingRange(long[] range1, long[] range2) {
int overlappingType = getOverlappingType(range1, range2); switch(getOverlappingType(range1, range2)) {
if (overlappingType == OVERLAPS_1_MINOR) { case OVERLAPS_1_MINOR:
return new long[]{range2[0], range1[1]}; return new long[]{range2[0], range1[1]};
} case OVERLAPS_2_MINOR:
else if (overlappingType == OVERLAPS_2_MINOR) {
return new long[]{range1[0], range2[1]}; return new long[]{range1[0], range2[1]};
} case OVERLAPS_2_WRAPS:
else if (overlappingType == OVERLAPS_2_WRAPS) {
return range1; return range1;
} case OVERLAPS_1_WRAPS:
else if (overlappingType == OVERLAPS_1_WRAPS) {
return range2; return range2;
} default:
case NO_OVERLAPS:
return new long[]{-1, -1}; return new long[]{-1, -1};
} }
}
public static int getOverlappingType(long[] range1, long[] range2) { public static int getOverlappingType(long[] range1, long[] range2) {
long min1 = range1[0]; long min1 = range1[0];
long max1 = range1[1]; long max1 = range1[1];
long min2 = range2[0]; long min2 = range2[0];
long max2 = range2[1]; long max2 = range2[1];
if (min1 >= min2 && max1 <= max2) { if (min1 >= min2) {
if (max1 <= max2) {
return OVERLAPS_2_WRAPS; return OVERLAPS_2_WRAPS;
} else if (min1 <= max2) {
return OVERLAPS_2_MINOR;
} }
else if (min2 >= min1 && max2 <= max1) { } else {
if (max1 >= max2) {
return OVERLAPS_1_WRAPS; return OVERLAPS_1_WRAPS;
} } else if (max1 >= min2) {
else if ((min2 >= min1 && min2 <= max1) && max2 >= max1) {
return OVERLAPS_1_MINOR; return OVERLAPS_1_MINOR;
} }
else if ((min1 >= min2 && min1 <= max2) && max1 >= max2) {
return OVERLAPS_2_MINOR;
} }
return NO_OVERLAPS; return NO_OVERLAPS;

View File

@ -26,37 +26,7 @@ import org.apache.poi.util.Internal;
import org.apache.poi.wp.usermodel.Paragraph; import org.apache.poi.wp.usermodel.Paragraph;
import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlObject;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDecimalNumber;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdnRef;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTInd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLvl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPBdr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTProofErr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRunTrackChange;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSmartTagRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTextAlignment;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTextAlignment;
/** /**
* <p>A Paragraph within a Document, Table, Header etc.</p> * <p>A Paragraph within a Document, Table, Header etc.</p>
@ -114,8 +84,8 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
for (XWPFParagraph p : footnote.getParagraphs()) { for (XWPFParagraph p : footnote.getParagraphs()) {
if (!first) { if (!first) {
footnoteText.append("\n"); footnoteText.append("\n");
first = false;
} }
first = false;
footnoteText.append(p.getText()); footnoteText.append(p.getText());
} }
@ -204,6 +174,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
return !paragraph.getDomNode().hasChildNodes(); return !paragraph.getDomNode().hasChildNodes();
} }
@Override
public XWPFDocument getDocument() { public XWPFDocument getDocument() {
return document; return document;
} }
@ -240,10 +211,11 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
public String getStyleID() { public String getStyleID() {
if (paragraph.getPPr() != null) { if (paragraph.getPPr() != null) {
if (paragraph.getPPr().getPStyle() != null) { if (paragraph.getPPr().getPStyle() != null) {
if (paragraph.getPPr().getPStyle().getVal() != null) if (paragraph.getPPr().getPStyle().getVal() != null) {
return paragraph.getPPr().getPStyle().getVal(); return paragraph.getPPr().getPStyle().getVal();
} }
} }
}
return null; return null;
} }
@ -257,10 +229,11 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
public BigInteger getNumID() { public BigInteger getNumID() {
if (paragraph.getPPr() != null) { if (paragraph.getPPr() != null) {
if (paragraph.getPPr().getNumPr() != null) { if (paragraph.getPPr().getNumPr() != null) {
if (paragraph.getPPr().getNumPr().getNumId() != null) if (paragraph.getPPr().getNumPr().getNumId() != null) {
return paragraph.getPPr().getNumPr().getNumId().getVal(); return paragraph.getPPr().getNumPr().getNumId().getVal();
} }
} }
}
return null; return null;
} }
@ -270,10 +243,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
* @param numPos * @param numPos
*/ */
public void setNumID(BigInteger numPos) { public void setNumID(BigInteger numPos) {
if (paragraph.getPPr() == null) if (paragraph.getPPr() == null) {
paragraph.addNewPPr(); paragraph.addNewPPr();
if (paragraph.getPPr().getNumPr() == null) }
if (paragraph.getPPr().getNumPr() == null) {
paragraph.getPPr().addNewNumPr(); paragraph.getPPr().addNewNumPr();
}
if (paragraph.getPPr().getNumPr().getNumId() == null) { if (paragraph.getPPr().getNumPr().getNumId() == null) {
paragraph.getPPr().getNumPr().addNewNumId(); paragraph.getPPr().getNumPr().addNewNumId();
} }
@ -289,10 +264,11 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
public BigInteger getNumIlvl() { public BigInteger getNumIlvl() {
if (paragraph.getPPr() != null) { if (paragraph.getPPr() != null) {
if (paragraph.getPPr().getNumPr() != null) { if (paragraph.getPPr().getNumPr() != null) {
if (paragraph.getPPr().getNumPr().getIlvl() != null) if (paragraph.getPPr().getNumPr().getIlvl() != null) {
return paragraph.getPPr().getNumPr().getIlvl().getVal(); return paragraph.getPPr().getNumPr().getIlvl().getVal();
} }
} }
}
return null; return null;
} }
@ -319,10 +295,11 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
} }
} }
if (level != null && level.getNumFmt() != null if (level != null && level.getNumFmt() != null
&& level.getNumFmt().getVal() != null) && level.getNumFmt().getVal() != null) {
return level.getNumFmt().getVal().toString(); return level.getNumFmt().getVal().toString();
} }
} }
}
return null; return null;
} }
@ -339,26 +316,31 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
if (num != null) { if (num != null) {
BigInteger ilvl = getNumIlvl(); BigInteger ilvl = getNumIlvl();
CTNum ctNum = num.getCTNum(); CTNum ctNum = num.getCTNum();
if (ctNum == null) if (ctNum == null) {
return null; return null;
}
CTDecimalNumber ctDecimalNumber = ctNum.getAbstractNumId(); CTDecimalNumber ctDecimalNumber = ctNum.getAbstractNumId();
if (ctDecimalNumber == null) if (ctDecimalNumber == null) {
return null; return null;
}
BigInteger abstractNumId = ctDecimalNumber.getVal(); BigInteger abstractNumId = ctDecimalNumber.getVal();
if (abstractNumId == null) if (abstractNumId == null) {
return null; return null;
}
XWPFAbstractNum xwpfAbstractNum = numbering.getAbstractNum(abstractNumId); XWPFAbstractNum xwpfAbstractNum = numbering.getAbstractNum(abstractNumId);
if (xwpfAbstractNum == null) if (xwpfAbstractNum == null) {
return null; return null;
}
CTAbstractNum anum = xwpfAbstractNum.getCTAbstractNum(); CTAbstractNum anum = xwpfAbstractNum.getCTAbstractNum();
if (anum == null) if (anum == null) {
return null; return null;
}
CTLvl level = null; CTLvl level = null;
for (int i = 0; i < anum.sizeOfLvlArray(); i++) { for (int i = 0; i < anum.sizeOfLvlArray(); i++) {
@ -369,10 +351,11 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
} }
} }
if (level != null && level.getLvlText() != null if (level != null && level.getLvlText() != null
&& level.getLvlText().getVal() != null) && level.getLvlText().getVal() != null) {
return level.getLvlText().getVal().toString(); return level.getLvlText().getVal().toString();
} }
} }
}
return null; return null;
} }
@ -486,10 +469,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
/** /**
* @return The raw alignment value, {@link #getAlignment()} is suggested * @return The raw alignment value, {@link #getAlignment()} is suggested
*/ */
@Override
public int getFontAlignment() { public int getFontAlignment() {
return getAlignment().getValue(); return getAlignment().getValue();
} }
@Override
public void setFontAlignment(int align) { public void setFontAlignment(int align) {
ParagraphAlignment pAlign = ParagraphAlignment.valueOf(align); ParagraphAlignment pAlign = ParagraphAlignment.valueOf(align);
setAlignment(pAlign); setAlignment(pAlign);
@ -600,11 +585,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
} }
CTBorder pr = (ct.isSetTop()) ? ct.getTop() : ct.addNewTop(); CTBorder pr = (ct.isSetTop()) ? ct.getTop() : ct.addNewTop();
if (border.getValue() == Borders.NONE.getValue()) if (border.getValue() == Borders.NONE.getValue()) {
ct.unsetTop(); ct.unsetTop();
else } else {
pr.setVal(STBorder.Enum.forInt(border.getValue())); pr.setVal(STBorder.Enum.forInt(border.getValue()));
} }
}
/** /**
* Specifies the border which shall be displayed below a set of * Specifies the border which shall be displayed below a set of
@ -654,11 +640,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
public void setBorderBottom(Borders border) { public void setBorderBottom(Borders border) {
CTPBdr ct = getCTPBrd(true); CTPBdr ct = getCTPBrd(true);
CTBorder pr = ct.isSetBottom() ? ct.getBottom() : ct.addNewBottom(); CTBorder pr = ct.isSetBottom() ? ct.getBottom() : ct.addNewBottom();
if (border.getValue() == Borders.NONE.getValue()) if (border.getValue() == Borders.NONE.getValue()) {
ct.unsetBottom(); ct.unsetBottom();
else } else {
pr.setVal(STBorder.Enum.forInt(border.getValue())); pr.setVal(STBorder.Enum.forInt(border.getValue()));
} }
}
/** /**
* Specifies the border which shall be displayed on the left side of the * Specifies the border which shall be displayed on the left side of the
@ -703,11 +690,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
public void setBorderLeft(Borders border) { public void setBorderLeft(Borders border) {
CTPBdr ct = getCTPBrd(true); CTPBdr ct = getCTPBrd(true);
CTBorder pr = ct.isSetLeft() ? ct.getLeft() : ct.addNewLeft(); CTBorder pr = ct.isSetLeft() ? ct.getLeft() : ct.addNewLeft();
if (border.getValue() == Borders.NONE.getValue()) if (border.getValue() == Borders.NONE.getValue()) {
ct.unsetLeft(); ct.unsetLeft();
else } else {
pr.setVal(STBorder.Enum.forInt(border.getValue())); pr.setVal(STBorder.Enum.forInt(border.getValue()));
} }
}
/** /**
* Specifies the border which shall be displayed on the right side of the * Specifies the border which shall be displayed on the right side of the
@ -752,11 +740,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
public void setBorderRight(Borders border) { public void setBorderRight(Borders border) {
CTPBdr ct = getCTPBrd(true); CTPBdr ct = getCTPBrd(true);
CTBorder pr = ct.isSetRight() ? ct.getRight() : ct.addNewRight(); CTBorder pr = ct.isSetRight() ? ct.getRight() : ct.addNewRight();
if (border.getValue() == Borders.NONE.getValue()) if (border.getValue() == Borders.NONE.getValue()) {
ct.unsetRight(); ct.unsetRight();
else } else {
pr.setVal(STBorder.Enum.forInt(border.getValue())); pr.setVal(STBorder.Enum.forInt(border.getValue()));
} }
}
/** /**
* Specifies the border which shall be displayed between each paragraph in a * Specifies the border which shall be displayed between each paragraph in a
@ -805,11 +794,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
public void setBorderBetween(Borders border) { public void setBorderBetween(Borders border) {
CTPBdr ct = getCTPBrd(true); CTPBdr ct = getCTPBrd(true);
CTBorder pr = ct.isSetBetween() ? ct.getBetween() : ct.addNewBetween(); CTBorder pr = ct.isSetBetween() ? ct.getBetween() : ct.addNewBetween();
if (border.getValue() == Borders.NONE.getValue()) if (border.getValue() == Borders.NONE.getValue()) {
ct.unsetBetween(); ct.unsetBetween();
else } else {
pr.setVal(STBorder.Enum.forInt(border.getValue())); pr.setVal(STBorder.Enum.forInt(border.getValue()));
} }
}
/** /**
* Specifies that when rendering this document in a paginated * Specifies that when rendering this document in a paginated
@ -857,11 +847,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
CTPPr ppr = getCTPPr(); CTPPr ppr = getCTPPr();
CTOnOff ctPageBreak = ppr.isSetPageBreakBefore() ? ppr CTOnOff ctPageBreak = ppr.isSetPageBreakBefore() ? ppr
.getPageBreakBefore() : ppr.addNewPageBreakBefore(); .getPageBreakBefore() : ppr.addNewPageBreakBefore();
if (pageBreak) if (pageBreak) {
ctPageBreak.setVal(STOnOff.TRUE); ctPageBreak.setVal(STOnOff.TRUE);
else } else {
ctPageBreak.setVal(STOnOff.FALSE); ctPageBreak.setVal(STOnOff.FALSE);
} }
}
/** /**
* Specifies the spacing that should be added after the last line in this * Specifies the spacing that should be added after the last line in this
@ -1228,26 +1219,32 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
indent.setFirstLine(bi); indent.setFirstLine(bi);
} }
@Override
public int getIndentFromLeft() { public int getIndentFromLeft() {
return getIndentationLeft(); return getIndentationLeft();
} }
@Override
public void setIndentFromLeft(int dxaLeft) { public void setIndentFromLeft(int dxaLeft) {
setIndentationLeft(dxaLeft); setIndentationLeft(dxaLeft);
} }
@Override
public int getIndentFromRight() { public int getIndentFromRight() {
return getIndentationRight(); return getIndentationRight();
} }
@Override
public void setIndentFromRight(int dxaRight) { public void setIndentFromRight(int dxaRight) {
setIndentationRight(dxaRight); setIndentationRight(dxaRight);
} }
@Override
public int getFirstLineIndent() { public int getFirstLineIndent() {
return getIndentationFirstLine(); return getIndentationFirstLine();
} }
@Override
public void setFirstLineIndent(int first) { public void setFirstLineIndent(int first) {
setIndentationFirstLine(first); setIndentationFirstLine(first);
} }
@ -1260,6 +1257,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
* *
* @return boolean * @return boolean
*/ */
@Override
public boolean isWordWrapped() { public boolean isWordWrapped() {
CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr() CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr()
.getWordWrap() : null; .getWordWrap() : null;
@ -1279,14 +1277,16 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
* *
* @param wrap - boolean * @param wrap - boolean
*/ */
@Override
public void setWordWrapped(boolean wrap) { public void setWordWrapped(boolean wrap) {
CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr() CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr()
.getWordWrap() : getCTPPr().addNewWordWrap(); .getWordWrap() : getCTPPr().addNewWordWrap();
if (wrap) if (wrap) {
wordWrap.setVal(STOnOff.TRUE); wordWrap.setVal(STOnOff.TRUE);
else } else {
wordWrap.unsetVal(); wordWrap.unsetVal();
} }
}
public boolean isWordWrap() { public boolean isWordWrap() {
return isWordWrapped(); return isWordWrapped();
@ -1325,8 +1325,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
private CTPBdr getCTPBrd(boolean create) { private CTPBdr getCTPBrd(boolean create) {
CTPPr pr = getCTPPr(); CTPPr pr = getCTPPr();
CTPBdr ct = pr.isSetPBdr() ? pr.getPBdr() : null; CTPBdr ct = pr.isSetPBdr() ? pr.getPBdr() : null;
if (create && ct == null) if (create && ct == null) {
ct = pr.addNewPBdr(); ct = pr.addNewPBdr();
}
return ct; return ct;
} }
@ -1337,8 +1338,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
private CTSpacing getCTSpacing(boolean create) { private CTSpacing getCTSpacing(boolean create) {
CTPPr pr = getCTPPr(); CTPPr pr = getCTPPr();
CTSpacing ct = pr.getSpacing() == null ? null : pr.getSpacing(); CTSpacing ct = pr.getSpacing() == null ? null : pr.getSpacing();
if (create && ct == null) if (create && ct == null) {
ct = pr.addNewSpacing(); ct = pr.addNewSpacing();
}
return ct; return ct;
} }
@ -1349,8 +1351,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
private CTInd getCTInd(boolean create) { private CTInd getCTInd(boolean create) {
CTPPr pr = getCTPPr(); CTPPr pr = getCTPPr();
CTInd ct = pr.getInd() == null ? null : pr.getInd(); CTInd ct = pr.getInd() == null ? null : pr.getInd();
if (create && ct == null) if (create && ct == null) {
ct = pr.addNewInd(); ct = pr.addNewInd();
}
return ct; return ct;
} }
@ -1536,8 +1539,9 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
for (int j = startText; j <= endText; j++) { for (int j = startText; j <= endText; j++) {
String tmpText = tArray[j].getStringValue(); String tmpText = tArray[j].getStringValue();
int startChar = 0, endChar = tmpText.length() - 1; int startChar = 0, endChar = tmpText.length() - 1;
if ((j == textBegin) && (i == runBegin)) if ((j == textBegin) && (i == runBegin)) {
startChar = charBegin; startChar = charBegin;
}
if ((j == textEnd) && (i == runEnd)) { if ((j == textEnd) && (i == runEnd)) {
endChar = charEnd; endChar = charEnd;
} }
@ -1585,10 +1589,12 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
* *
* @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType() * @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType()
*/ */
@Override
public BodyElementType getElementType() { public BodyElementType getElementType() {
return BodyElementType.PARAGRAPH; return BodyElementType.PARAGRAPH;
} }
@Override
public IBody getBody() { public IBody getBody() {
return part; return part;
} }
@ -1598,6 +1604,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
* *
* @see org.apache.poi.xwpf.usermodel.IBody#getPart() * @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/ */
@Override
public POIXMLDocumentPart getPart() { public POIXMLDocumentPart getPart() {
if (part != null) { if (part != null) {
return part.getPart(); return part.getPart();
@ -1610,6 +1617,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
* *
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType() * @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/ */
@Override
public BodyType getPartType() { public BodyType getPartType() {
return part.getPartType(); return part.getPartType();
} }

View File

@ -156,11 +156,7 @@ public class XWPFPictureData extends POIXMLDocumentPart {
} catch (IOException e) { } catch (IOException e) {
throw new POIXMLException(e); throw new POIXMLException(e);
} finally { } finally {
try { IOUtils.closeQuietly(is);
if (is != null) is.close();
} catch (IOException e) {
throw new POIXMLException(e);
}
} }
this.checksum = IOUtils.calculateChecksum(data); this.checksum = IOUtils.calculateChecksum(data);
} }

View File

@ -36,7 +36,11 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.*; import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.Key; import java.security.Key;
import java.security.KeyPair; import java.security.KeyPair;
import java.security.KeyStore; import java.security.KeyStore;
@ -389,17 +393,16 @@ public class TestSignatureInfo {
throw e; throw e;
} }
if((e.getCause() instanceof ConnectException) || (e.getCause() instanceof SocketTimeoutException)) { if((e.getCause() instanceof ConnectException) || (e.getCause() instanceof SocketTimeoutException)) {
Assume.assumeTrue("Only allowing ConnectException with 'timed out' as message here, but had: " + e, Assume.assumeFalse("Only allowing ConnectException with 'timed out' as message here, but had: " + e,
e.getCause().getMessage().contains("timed out")); e.getCause().getMessage().contains("timed out"));
} else if (e.getCause() instanceof IOException) { } else if (e.getCause() instanceof IOException) {
Assume.assumeTrue("Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e, Assume.assumeFalse("Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e,
e.getCause().getMessage().contains("Error contacting TSP server")); e.getCause().getMessage().contains("Error contacting TSP server"));
} else if (e.getCause() instanceof RuntimeException) { } else if (e.getCause() instanceof RuntimeException) {
Assume.assumeTrue("Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e, Assume.assumeFalse("Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e,
e.getCause().getMessage().contains("This site is cur")); e.getCause().getMessage().contains("This site is cur"));
} else {
throw e;
} }
throw e;
} }
// verify // verify
@ -557,7 +560,9 @@ public class TestSignatureInfo {
boolean b = si.verifySignature(); boolean b = si.verifySignature();
assertTrue("Signature not correctly calculated for " + ha, b); assertTrue("Signature not correctly calculated for " + ha, b);
} finally { } finally {
if (pkg != null) pkg.close(); if (pkg != null) {
pkg.close();
}
} }
} }
} }