From 9f2f9dc7937f66397f5fd157df4092ed40998f95 Mon Sep 17 00:00:00 2001 From: Andreas Beeker Date: Thu, 5 Dec 2019 00:18:36 +0000 Subject: [PATCH] Sonar Fixes git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1870856 13f79535-47bb-0310-9956-ffa450edef68 --- .../examples/AddDimensionedImage.java | 121 ++++--------- .../usermodel/examples/HSSFReadWrite.java | 165 ++++++++---------- .../src/org/apache/poi/hssf/view/SViewer.java | 1 + .../apache/poi/hssf/view/SViewerPanel.java | 40 ++++- .../poi/ss/examples/AddDimensionedImage.java | 43 ++--- .../formula/CheckFunctionsSupported.java | 32 ++-- .../usermodel/examples/ChartFromScratch.java | 11 +- src/java/org/apache/poi/util/XMLHelper.java | 53 ++++-- .../hwpf/converter/WordToTextConverter.java | 12 +- .../converter/TestExcelConverterSuite.java | 6 +- .../converter/TestWordToConverterSuite.java | 10 +- 11 files changed, 222 insertions(+), 272 deletions(-) diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/AddDimensionedImage.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/AddDimensionedImage.java index 480662554d..7a3fa8b3e6 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/AddDimensionedImage.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/AddDimensionedImage.java @@ -20,18 +20,18 @@ package org.apache.poi.hssf.usermodel.examples; import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; +import java.io.FileOutputStream; import java.io.IOException; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFPatriarch; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.util.IOUtils; /** @@ -126,8 +126,8 @@ import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; * A note concerning Excels' image resizing behaviour. The HSSFClientAnchor * class contains a method called setAnchorType(int) which can be used to * determine how Excel will resize an image in reponse to the user increasing - * or decreasing the dimensions of the cell containing the image. There are - * three values that can be passed to this method; 0 = To move and size the + * or decreasing the dimensions of the cell containing the image. There are + * three values that can be passed to this method; 0 = To move and size the * image with the cell, 2 = To move but don't size the image with the cell, * 3 = To prevent the image from moving or being resized along with the cell. If * an image is inserted using this class and placed into a single cell then if @@ -298,7 +298,7 @@ public class AddDimensionedImage { // become another parameter passed to the method. //anchor.setAnchorType(HSSFClientAnchor.DONT_MOVE_AND_RESIZE); anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE); - + // Now, add the picture to the workbook. Note that the type is assumed // to be a JPEG/JPG, this could easily (and should) be parameterised // however. @@ -538,7 +538,7 @@ public class AddDimensionedImage { // total number of co-ordinate positions to the third paramater // of the ClientAnchorDetail constructor. For no sepcific reason, // the latter option is used below. - anchorDetail = new ClientAnchorDetail(startingColumn, + anchorDetail = new ClientAnchorDetail(startingColumn, toColumn, ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS); } // In this case, the image will overlap part of another column and it is @@ -675,29 +675,9 @@ public class AddDimensionedImage { * interrupted. */ private byte[] imageToBytes(String imageFilename) throws IOException { - File imageFile; - FileInputStream fis = null; - ByteArrayOutputStream bos; - int read; - try { - imageFile = new File(imageFilename); - fis = new FileInputStream(imageFile); - bos = new ByteArrayOutputStream(); - while((read = fis.read()) != -1) { - bos.write(read); - } - return(bos.toByteArray()); - } - finally { - if(fis != null) { - try { - fis.close(); - fis = null; - } - catch(IOException ioEx) { - // Nothing to do here - } - } + File imageFile = new File(imageFilename); + try (FileInputStream fis = new FileInputStream(imageFile)) { + return IOUtils.toByteArray(fis); } } @@ -720,41 +700,21 @@ public class AddDimensionedImage { * * @param args the command line arguments */ - public static void main(String[] args) { - String imageFile; - String outputFile; - FileOutputStream fos = null; - HSSFSheet sheet; - try { - if(args.length < 2){ - System.err.println("Usage: AddDimensionedImage imageFile outputFile"); - return; - } - imageFile = args[0]; - outputFile = args[1]; - - try (HSSFWorkbook workbook = new HSSFWorkbook()) { - sheet = workbook.createSheet("Picture Test"); - new AddDimensionedImage().addImageToSheet("A1", sheet, - imageFile, 125, 125, - AddDimensionedImage.EXPAND_ROW_AND_COLUMN); - fos = new FileOutputStream(outputFile); - workbook.write(fos); - } - } catch(IOException ioEx) { - System.out.println("Caught an: " + ioEx.getClass().getName()); - System.out.println("Message: " + ioEx.getMessage()); - System.out.println("Stacktrace follows..........."); - ioEx.printStackTrace(System.out); + public static void main(String[] args) throws IOException { + if(args.length < 2){ + System.err.println("Usage: AddDimensionedImage imageFile outputFile"); + return; } - finally { - try { - if(fos != null) { - fos.close(); - fos = null; - } - } catch(IOException ioEx) { - // I G N O R E + String imageFile = args[0]; + String outputFile = args[1]; + + try (HSSFWorkbook workbook = new HSSFWorkbook()) { + HSSFSheet sheet = workbook.createSheet("Picture Test"); + new AddDimensionedImage().addImageToSheet("A1", sheet, + imageFile, 125, 125, + AddDimensionedImage.EXPAND_ROW_AND_COLUMN); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + workbook.write(fos); } } } @@ -775,21 +735,21 @@ public class AddDimensionedImage { * * Together, parameter seven and eight determine the column and row * co-ordinates of the cell whose top left hand corner will be aligned * with the images bottom right hand corner. - * + * * An instance of the ClientAnchorDetail class provides three of the eight * parameters, one of the co-ordinates for the images top left hand corner, - * one of the co-ordinates for the images bottom right hand corner and + * one of the co-ordinates for the images bottom right hand corner and * either how far the image should be inset from the top or the left hand * edge of the cell. - * + * * @author Mark Beardsley [mas at apache.org] * @version 1.00 5th August 2009. */ - public class ClientAnchorDetail { + public static class ClientAnchorDetail { - public int fromIndex; - public int toIndex; - public int inset; + private int fromIndex; + private int toIndex; + private int inset; /** * Create a new instance of the ClientAnchorDetail class using the @@ -857,17 +817,13 @@ public class AddDimensionedImage { * Additional constants. * widthUnits2Millimetres() and millimetres2Units() methods. */ - public static class ConvertImageUnits { + private static final class ConvertImageUnits { // Each cell conatins a fixed number of co-ordinate points; this number // does not vary with row height or column width or with font. These two // constants are defined below. public static final int TOTAL_COLUMN_COORDINATE_POSITIONS = 1023; // MB public static final int TOTAL_ROW_COORDINATE_POSITIONS = 255; // MB - // The resoultion of an image can be expressed as a specific number - // of pixels per inch. Displays and printers differ but 96 pixels per - // inch is an acceptable standard to beging with. - public static final int PIXELS_PER_INCH = 96; // MB // Cnstants that defines how many pixels and points there are in a // millimetre. These values are required for the conversion algorithm. public static final double PIXELS_PER_MILLIMETRES = 3.78; // MB @@ -880,13 +836,11 @@ public class AddDimensionedImage { public static final double CELL_BORDER_WIDTH_MILLIMETRES = 2.0D; // MB public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256; public static final int UNIT_OFFSET_LENGTH = 7; - public static final int[] UNIT_OFFSET_MAP = new int[] + private static final int[] UNIT_OFFSET_MAP = new int[] { 0, 36, 73, 109, 146, 182, 219 }; /** * pixel units to excel width units(units of 1/256th of a character width) - * @param pxs - * @return */ public static short pixel2WidthUnits(int pxs) { short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * @@ -898,9 +852,6 @@ public class AddDimensionedImage { /** * excel width units(units of 1/256th of a character width) to pixel * units. - * - * @param widthUnits - * @return */ public static int widthUnits2Pixel(short widthUnits) { int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java index 0484d6feef..5ed9d905cf 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java @@ -20,7 +20,6 @@ package org.apache.poi.hssf.usermodel.examples; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; -import java.util.Locale; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; @@ -57,7 +56,8 @@ public final class HSSFReadWrite { * rows/cells. */ private static void testCreateSampleSheet(String outputFilename) throws IOException { - try (HSSFWorkbook wb = new HSSFWorkbook()) { + try (HSSFWorkbook wb = new HSSFWorkbook(); + FileOutputStream out = new FileOutputStream(outputFilename)) { HSSFSheet s = wb.createSheet(); HSSFCellStyle cs = wb.createCellStyle(); HSSFCellStyle cs2 = wb.createCellStyle(); @@ -121,9 +121,7 @@ public final class HSSFReadWrite { wb.removeSheetAt(1); // end deleted sheet - try (FileOutputStream out = new FileOutputStream(outputFilename)) { - wb.write(out); - } + wb.write(out); } } @@ -147,115 +145,104 @@ public final class HSSFReadWrite { * "MODIFIED CELL" then writes it out. Hence this is "modify test 1". If you * take the output from the write test, you'll have a valid scenario. */ - public static void main(String[] args) { + public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("At least one argument expected"); return; } String fileName = args[0]; - try { - if (args.length < 2) { - - try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) { - System.out.println("Data dump:\n"); - - for (int k = 0; k < wb.getNumberOfSheets(); k++) { - HSSFSheet sheet = wb.getSheetAt(k); - int rows = sheet.getPhysicalNumberOfRows(); - System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows - + " row(s)."); - for (int r = 0; r < rows; r++) { - HSSFRow row = sheet.getRow(r); - if (row == null) { - continue; - } + if (args.length < 2) { + + try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) { + System.out.println("Data dump:\n"); + + for (int k = 0; k < wb.getNumberOfSheets(); k++) { + HSSFSheet sheet = wb.getSheetAt(k); + int rows = sheet.getPhysicalNumberOfRows(); + System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows + " row(s)."); + for (int r = 0; r < rows; r++) { + HSSFRow row = sheet.getRow(r); + if (row == null) { + continue; + } - System.out.println("\nROW " + row.getRowNum() + " has " + row.getPhysicalNumberOfCells() + " cell(s)."); - for (int c = 0; c < row.getLastCellNum(); c++) { - HSSFCell cell = row.getCell(c); - String value; + System.out.println("\nROW " + row.getRowNum() + " has " + row.getPhysicalNumberOfCells() + " cell(s)."); + for (int c = 0; c < row.getLastCellNum(); c++) { + HSSFCell cell = row.getCell(c); + String value; - if (cell != null) { - switch (cell.getCellType()) { + if (cell != null) { + switch (cell.getCellType()) { - case FORMULA: - value = "FORMULA value=" + cell.getCellFormula(); - break; + case FORMULA: + value = "FORMULA value=" + cell.getCellFormula(); + break; - case NUMERIC: - value = "NUMERIC value=" + cell.getNumericCellValue(); - break; + case NUMERIC: + value = "NUMERIC value=" + cell.getNumericCellValue(); + break; - case STRING: - value = "STRING value=" + cell.getStringCellValue(); - break; + case STRING: + value = "STRING value=" + cell.getStringCellValue(); + break; - case BLANK: - value = ""; - break; + case BLANK: + value = ""; + break; - case BOOLEAN: - value = "BOOLEAN value-" + cell.getBooleanCellValue(); - break; + case BOOLEAN: + value = "BOOLEAN value-" + cell.getBooleanCellValue(); + break; - case ERROR: - value = "ERROR value=" + cell.getErrorCellValue(); - break; + case ERROR: + value = "ERROR value=" + cell.getErrorCellValue(); + break; - default: - value = "UNKNOWN value of type " + cell.getCellType(); - } - System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" - + value); + default: + value = "UNKNOWN value of type " + cell.getCellType(); } + System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" + value); } } } } - } else if (args.length == 2) { - if (args[1].toLowerCase(Locale.ROOT).equals("write")) { - System.out.println("Write mode"); - long time = System.currentTimeMillis(); - HSSFReadWrite.testCreateSampleSheet(fileName); - - System.out.println("" + (System.currentTimeMillis() - time) - + " ms generation time"); - } else { - System.out.println("readwrite test"); - try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) { - try (FileOutputStream stream = new FileOutputStream(args[1])) { - wb.write(stream); - } - } + } + } else if (args.length == 2) { + if ("write".equalsIgnoreCase(args[1])) { + System.out.println("Write mode"); + long time = System.currentTimeMillis(); + HSSFReadWrite.testCreateSampleSheet(fileName); + + System.out.println("" + (System.currentTimeMillis() - time) + " ms generation time"); + } else { + System.out.println("readwrite test"); + try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName); + FileOutputStream stream = new FileOutputStream(args[1])) { + wb.write(stream); } - } else if (args.length == 3 && args[2].equalsIgnoreCase("modify1")) { - // delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!" - - try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName)) { - HSSFSheet sheet = wb.getSheetAt(0); + } + } else if (args.length == 3 && "modify1".equalsIgnoreCase(args[2])) { + // delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!" - for (int k = 0; k < 25; k++) { - HSSFRow row = sheet.getRow(k); + try (HSSFWorkbook wb = HSSFReadWrite.readFile(fileName); + FileOutputStream stream = new FileOutputStream(args[1])) { + HSSFSheet sheet = wb.getSheetAt(0); - sheet.removeRow(row); - } - for (int k = 74; k < 100; k++) { - HSSFRow row = sheet.getRow(k); - - sheet.removeRow(row); - } - HSSFRow row = sheet.getRow(39); - HSSFCell cell = row.getCell(3); - cell.setCellValue("MODIFIED CELL!!!!!"); - - try (FileOutputStream stream = new FileOutputStream(args[1])) { - wb.write(stream); - } + for (int k = 0; k < 25; k++) { + HSSFRow row = sheet.getRow(k); + sheet.removeRow(row); } + for (int k = 74; k < 100; k++) { + HSSFRow row = sheet.getRow(k); + sheet.removeRow(row); + } + HSSFRow row = sheet.getRow(39); + HSSFCell cell = row.getCell(3); + cell.setCellValue("MODIFIED CELL!!!!!"); + + wb.write(stream); } - } catch (Exception e) { - e.printStackTrace(); } } } diff --git a/src/examples/src/org/apache/poi/hssf/view/SViewer.java b/src/examples/src/org/apache/poi/hssf/view/SViewer.java index 3e9daf34ff..d3c4cbecaa 100644 --- a/src/examples/src/org/apache/poi/hssf/view/SViewer.java +++ b/src/examples/src/org/apache/poi/hssf/view/SViewer.java @@ -70,6 +70,7 @@ public class SViewer extends JApplet { * Initialize the applet */ @Override + @SuppressWarnings("squid:S1148") public void init() { try { jbInit(); diff --git a/src/examples/src/org/apache/poi/hssf/view/SViewerPanel.java b/src/examples/src/org/apache/poi/hssf/view/SViewerPanel.java index dfc4dde9f4..1bd8223c1b 100644 --- a/src/examples/src/org/apache/poi/hssf/view/SViewerPanel.java +++ b/src/examples/src/org/apache/poi/hssf/view/SViewerPanel.java @@ -17,13 +17,37 @@ package org.apache.poi.hssf.view; -import java.awt.*; -import java.awt.event.*; -import java.io.*; -import javax.swing.*; -import javax.swing.table.*; - -import org.apache.poi.hssf.usermodel.*; +import java.awt.AWTEvent; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Insets; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.WindowEvent; +import java.io.FileInputStream; +import java.io.IOException; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTable; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableColumn; +import javax.swing.table.TableColumnModel; + +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; /** * This class presents the sheets to the user. @@ -144,7 +168,7 @@ public void paint(Graphics g) { * The default is to popup a menu when the event occurs over a tab */ private class TabListener implements MouseListener { - public JPopupMenu popup; + private final JPopupMenu popup; public TabListener() { popup = new JPopupMenu("Sheet"); popup.add(createInsertSheetAction()); diff --git a/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java b/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java index fa5e233cf9..82a2db46ee 100644 --- a/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java +++ b/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java @@ -100,7 +100,7 @@ import org.apache.poi.util.IOUtils; * in which those corners should be located. The setCol1() and setRow1() methods * together identify the cell that should contain the top left hand corner of * the image while setCol2() and setRow2() do the same for the images bottom - * right hand corner. + * right hand corner. * * Knowing that, it is possible to look again at the example above and to see * that the top left hand corner of the image will be located in cell A1 (0, 0) @@ -108,7 +108,7 @@ import org.apache.poi.util.IOUtils; * the bottom right hand corner of the image will be located in cell B2 (1, 1) and * it will again be aligned with the top left hand corner of the cell. This has the * effect of making the image seem to occupy the whole of cell A1. Interestingly, it - * also has an effect on the images resizing behaviour because testing has + * also has an effect on the images resizing behaviour because testing has * demonstrated that if the image is wholly contained within one cell and is not * 'attached' for want of a better word, to a neighbouring cell, then that image * will not increase in size in response to the user dragging the column wider @@ -170,8 +170,8 @@ import org.apache.poi.util.IOUtils; * A note concerning Excels image resizing behaviour. The ClientAnchor * class contains a method called setAnchorType(int) which can be used to * determine how Excel will resize an image in response to the user increasing - * or decreasing the dimensions of the cell containing the image. There are - * three values that can be passed to this method; 0 = To move and size the + * or decreasing the dimensions of the cell containing the image. There are + * three values that can be passed to this method; 0 = To move and size the * image with the cell, 2 = To move but don't size the image with the cell, * 3 = To prevent the image from moving or being resized along with the cell. If * an image is inserted using this class and placed into a single cell then if @@ -221,12 +221,12 @@ public class AddDimensionedImage { public static final int EXPAND_COLUMN = 2; public static final int EXPAND_ROW_AND_COLUMN = 3; public static final int OVERLAY_ROW_AND_COLUMN = 7; - + // Modified to support EMU - English Metric Units - used within the OOXML // workbooks, this multoplier is used to convert between measurements in // millimetres and in EMUs private static final int EMU_PER_MM = 36000; - + /** * Add an image to a worksheet. * @@ -551,7 +551,7 @@ public class AddDimensionedImage { (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { row.setHeightInPoints((float)(reqImageHeightMM * ConvertImageUnits.POINTS_PER_MILLIMETRE)); - if(sheet instanceof HSSFSheet) { + if(sheet instanceof HSSFSheet) { rowHeightMM = reqImageHeightMM; rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / rowHeightMM; @@ -863,9 +863,9 @@ public class AddDimensionedImage { */ public class ClientAnchorDetail { - public int fromIndex; - public int toIndex; - public int inset; + private int fromIndex; + private int toIndex; + private int inset; /** * Create a new instance of the ClientAnchorDetail class using the @@ -938,26 +938,25 @@ public class AddDimensionedImage { // Each cell conatins a fixed number of co-ordinate points; this number // does not vary with row height or column width or with font. These two // constants are defined below. - public static final int TOTAL_COLUMN_COORDINATE_POSITIONS = 1023; // MB - public static final int TOTAL_ROW_COORDINATE_POSITIONS = 255; // MB + public static final int TOTAL_COLUMN_COORDINATE_POSITIONS = 1023; + public static final int TOTAL_ROW_COORDINATE_POSITIONS = 255; // The resoultion of an image can be expressed as a specific number // of pixels per inch. Displays and printers differ but 96 pixels per // inch is an acceptable standard to beging with. - public static final int PIXELS_PER_INCH = 96; // MB + public static final int PIXELS_PER_INCH = 96; // Cnstants that defines how many pixels and points there are in a // millimetre. These values are required for the conversion algorithm. - public static final double PIXELS_PER_MILLIMETRES = 3.78; // MB - public static final double POINTS_PER_MILLIMETRE = 2.83; // MB + public static final double PIXELS_PER_MILLIMETRES = 3.78; + public static final double POINTS_PER_MILLIMETRE = 2.83; // The column width returned by HSSF and the width of a picture when // positioned to exactly cover one cell are different by almost exactly // 2mm - give or take rounding errors. This constant allows that // additional amount to be accounted for when calculating how many // celles the image ought to overlie. - public static final double CELL_BORDER_WIDTH_MILLIMETRES = 2.0D; // MB + public static final double CELL_BORDER_WIDTH_MILLIMETRES = 2.0D; public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256; public static final int UNIT_OFFSET_LENGTH = 7; - public static final int[] UNIT_OFFSET_MAP = new int[] - { 0, 36, 73, 109, 146, 182, 219 }; + private static final int[] UNIT_OFFSET_MAP = { 0, 36, 73, 109, 146, 182, 219 }; /** * pixel units to excel width units(units of 1/256th of a character width) @@ -1007,13 +1006,5 @@ public class AddDimensionedImage { return(ConvertImageUnits.pixel2WidthUnits((int)(millimetres * ConvertImageUnits.PIXELS_PER_MILLIMETRES))); } - - public static int pointsToPixels(double points) { - return (int) Math.round(points / 72D * PIXELS_PER_INCH); - } - - public static double pointsToMillimeters(double points) { - return points / 72D * 25.4; - } } } diff --git a/src/examples/src/org/apache/poi/ss/examples/formula/CheckFunctionsSupported.java b/src/examples/src/org/apache/poi/ss/examples/formula/CheckFunctionsSupported.java index adb24eb676..0e32c29116 100644 --- a/src/examples/src/org/apache/poi/ss/examples/formula/CheckFunctionsSupported.java +++ b/src/examples/src/org/apache/poi/ss/examples/formula/CheckFunctionsSupported.java @@ -52,16 +52,16 @@ public class CheckFunctionsSupported { System.err.println(" CheckFunctionsSupported "); return; } - + Workbook wb = WorkbookFactory.create(new File(args[0])); CheckFunctionsSupported check = new CheckFunctionsSupported(wb); - + // Fetch all the problems List problems = new ArrayList<>(); for (int sn=0; sn unsupportedFunctions = new TreeSet<>(); for (FormulaEvaluationProblems p : problems) { @@ -76,15 +76,15 @@ public class CheckFunctionsSupported { } System.out.println("Total unsupported functions = " + unsupportedFunctions.size()); } - + // Report sheet by sheet for (int sn=0; sn getUnsupportedFunctions(String sheetName) { return getUnsupportedFunctions(workbook.getSheet(sheetName)); } @@ -113,7 +113,7 @@ public class CheckFunctionsSupported { FormulaEvaluationProblems problems = getEvaluationProblems(sheet); return problems.unsupportedFunctions; } - + public FormulaEvaluationProblems getEvaluationProblems(String sheetName) { return getEvaluationProblems(workbook.getSheet(sheetName)); } @@ -123,7 +123,7 @@ public class CheckFunctionsSupported { public FormulaEvaluationProblems getEvaluationProblems(Sheet sheet) { Set unsupportedFunctions = new HashSet<>(); Map unevaluatableCells = new HashMap<>(); - + for (Row r : sheet) { for (Cell c : r) { try { @@ -133,7 +133,7 @@ public class CheckFunctionsSupported { // Has been wrapped with cell details, but we know those e = (Exception)e.getCause(); } - + if (e instanceof NotImplementedFunctionException) { NotImplementedFunctionException nie = (NotImplementedFunctionException)e; unsupportedFunctions.add(nie.getFunctionName()); @@ -142,16 +142,16 @@ public class CheckFunctionsSupported { } } } - + return new FormulaEvaluationProblems(unsupportedFunctions, unevaluatableCells); } - + public static class FormulaEvaluationProblems { /** Which used functions are unsupported by POI at this time */ - public Set unsupportedFunctions; + private final Set unsupportedFunctions; /** Which cells had unevaluatable formulas, and why? */ - public Map unevaluatableCells; - + private final Map unevaluatableCells; + protected FormulaEvaluationProblems(Set unsupportedFunctions, Map unevaluatableCells) { this.unsupportedFunctions = Collections.unmodifiableSet(unsupportedFunctions); diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/ChartFromScratch.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/ChartFromScratch.java index b1ebbdc01e..3859a737aa 100644 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/ChartFromScratch.java +++ b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/ChartFromScratch.java @@ -87,17 +87,12 @@ public class ChartFromScratch { Double[] values1 = listCountries.toArray(new Double[0]); Double[] values2 = listSpeakers.toArray(new Double[0]); - try (XWPFDocument doc = new XWPFDocument()) { + try (XWPFDocument doc = new XWPFDocument(); + OutputStream out = new FileOutputStream("chart-from-scratch.docx")) { XWPFChart chart = doc.createChart(XDDFChart.DEFAULT_WIDTH * 10, XDDFChart.DEFAULT_HEIGHT * 15); setBarData(chart, chartTitle, series, categories, values1, values2); // save the result - try (OutputStream out = new FileOutputStream("chart-from-scratch.docx")) { - doc.write(out); - } - } - catch(Exception e) - { - e.printStackTrace(); + doc.write(out); } } System.out.println("Done"); diff --git a/src/java/org/apache/poi/util/XMLHelper.java b/src/java/org/apache/poi/util/XMLHelper.java index fd02caca2f..ab408c4444 100644 --- a/src/java/org/apache/poi/util/XMLHelper.java +++ b/src/java/org/apache/poi/util/XMLHelper.java @@ -17,11 +17,21 @@ package org.apache.poi.util; +import static javax.xml.XMLConstants.ACCESS_EXTERNAL_DTD; +import static javax.xml.XMLConstants.ACCESS_EXTERNAL_SCHEMA; +import static javax.xml.XMLConstants.ACCESS_EXTERNAL_STYLESHEET; +import static javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING; +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; +import static javax.xml.stream.XMLInputFactory.IS_NAMESPACE_AWARE; +import static javax.xml.stream.XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES; +import static javax.xml.stream.XMLInputFactory.IS_VALIDATING; +import static javax.xml.stream.XMLInputFactory.SUPPORT_DTD; +import static javax.xml.stream.XMLOutputFactory.IS_REPAIRING_NAMESPACES; + import java.io.StringReader; import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; -import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -44,6 +54,8 @@ import org.xml.sax.XMLReader; /** * Helper methods for working with javax.xml classes. + * + * @see OWASP XXE */ @Internal public final class XMLHelper { @@ -86,20 +98,18 @@ public final class XMLHelper { /** * Creates a new DocumentBuilderFactory, with sensible defaults - * - * @see OWASP XXE */ @SuppressWarnings({"squid:S2755"}) public static DocumentBuilderFactory getDocumentBuilderFactory() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // this doesn't appear to work, and we still need to limit - // entity expansions to 1 in trySetXercesSecurityManager + // entity expansions to 1 in trySet(XercesSecurityManager) factory.setExpandEntityReferences(false); factory.setValidating(false); - trySet(factory::setFeature, XMLConstants.FEATURE_SECURE_PROCESSING, true); - trySet(factory::setAttribute, XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); - trySet(factory::setAttribute, XMLConstants.ACCESS_EXTERNAL_DTD, ""); + trySet(factory::setFeature, FEATURE_SECURE_PROCESSING, true); + trySet(factory::setAttribute, ACCESS_EXTERNAL_SCHEMA, ""); + trySet(factory::setAttribute, ACCESS_EXTERNAL_DTD, ""); trySet(factory::setFeature, FEATURE_EXTERNAL_ENTITIES, false); trySet(factory::setFeature, FEATURE_PARAMETER_ENTITIES, false); trySet(factory::setFeature, FEATURE_LOAD_EXTERNAL_DTD, false); @@ -134,14 +144,16 @@ public final class XMLHelper { } } + @SuppressWarnings("squid:S2755") public static SAXParserFactory getSaxParserFactory() { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); - trySet(factory::setFeature, XMLConstants.FEATURE_SECURE_PROCESSING, true); + trySet(factory::setFeature, FEATURE_SECURE_PROCESSING, true); trySet(factory::setFeature, FEATURE_LOAD_DTD_GRAMMAR, false); trySet(factory::setFeature, FEATURE_LOAD_EXTERNAL_DTD, false); + trySet(factory::setFeature, FEATURE_EXTERNAL_ENTITIES, false); return factory; } catch (RuntimeException | Error re) { // NOSONAR // this also catches NoClassDefFoundError, which may be due to a local class path issue @@ -161,7 +173,8 @@ public final class XMLHelper { public static XMLReader newXMLReader() throws SAXException, ParserConfigurationException { XMLReader xmlReader = saxFactory.newSAXParser().getXMLReader(); xmlReader.setEntityResolver(XMLHelper::ignoreEntity); - trySet(xmlReader::setFeature, XMLConstants.FEATURE_SECURE_PROCESSING, true); + trySet(xmlReader::setFeature, FEATURE_SECURE_PROCESSING, true); + trySet(xmlReader::setFeature, FEATURE_EXTERNAL_ENTITIES, false); Object manager = getXercesSecurityManager(); if (manager == null || !trySet(xmlReader::setProperty, PROPERTY_SECURITY_MANAGER, manager)) { // separate old version of Xerces not found => use the builtin way of setting the property @@ -176,10 +189,10 @@ public final class XMLHelper { @SuppressWarnings({"squid:S2755"}) public static XMLInputFactory newXMLInputFactory() { XMLInputFactory factory = XMLInputFactory.newInstance(); - trySet(factory::setProperty, XMLInputFactory.IS_NAMESPACE_AWARE, true); - trySet(factory::setProperty, XMLInputFactory.IS_VALIDATING, false); - trySet(factory::setProperty, XMLInputFactory.SUPPORT_DTD, false); - trySet(factory::setProperty, XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); + trySet(factory::setProperty, IS_NAMESPACE_AWARE, true); + trySet(factory::setProperty, IS_VALIDATING, false); + trySet(factory::setProperty, SUPPORT_DTD, false); + trySet(factory::setProperty, IS_SUPPORTING_EXTERNAL_ENTITIES, false); return factory; } @@ -188,7 +201,7 @@ public final class XMLHelper { */ public static XMLOutputFactory newXMLOutputFactory() { XMLOutputFactory factory = XMLOutputFactory.newInstance(); - trySet(factory::setProperty, XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); + trySet(factory::setProperty, IS_REPAIRING_NAMESPACES, true); return factory; } @@ -202,7 +215,9 @@ public final class XMLHelper { public static TransformerFactory getTransformerFactory() { TransformerFactory factory = TransformerFactory.newInstance(); - trySet(factory::setFeature, XMLConstants.FEATURE_SECURE_PROCESSING, true); + trySet(factory::setFeature, FEATURE_SECURE_PROCESSING, true); + trySet(factory::setAttribute, ACCESS_EXTERNAL_DTD, ""); + trySet(factory::setAttribute, ACCESS_EXTERNAL_STYLESHEET, ""); return factory; } @@ -216,10 +231,10 @@ public final class XMLHelper { } public static SchemaFactory getSchemaFactory() { - SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - trySet(factory::setFeature, XMLConstants.FEATURE_SECURE_PROCESSING, true); - trySet(factory::setProperty, XMLConstants.ACCESS_EXTERNAL_DTD, ""); - trySet(factory::setProperty, XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); + trySet(factory::setFeature, FEATURE_SECURE_PROCESSING, true); + trySet(factory::setProperty, ACCESS_EXTERNAL_DTD, ""); + trySet(factory::setProperty, ACCESS_EXTERNAL_SCHEMA, ""); return factory; } diff --git a/src/scratchpad/src/org/apache/poi/hwpf/converter/WordToTextConverter.java b/src/scratchpad/src/org/apache/poi/hwpf/converter/WordToTextConverter.java index 3103c81869..b297ed4f1d 100644 --- a/src/scratchpad/src/org/apache/poi/hwpf/converter/WordToTextConverter.java +++ b/src/scratchpad/src/org/apache/poi/hwpf/converter/WordToTextConverter.java @@ -27,7 +27,6 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; @@ -83,7 +82,7 @@ public class WordToTextConverter extends AbstractWordConverter /** * Java main() interface to interact with {@link WordToTextConverter} - * + * *

* Usage: WordToTextConverter infile outfile *

@@ -131,7 +130,7 @@ public class WordToTextConverter extends AbstractWordConverter /** * Creates new instance of {@link WordToTextConverter}. Can be used for * output several {@link HWPFDocument}s into single text document. - * + * * @throws ParserConfigurationException * if an internal {@link DocumentBuilder} cannot be created */ @@ -144,7 +143,7 @@ public class WordToTextConverter extends AbstractWordConverter /** * Creates new instance of {@link WordToTextConverter}. Can be used for * output several {@link HWPFDocument}s into single text document. - * + * * @param document * XML DOM Document used as storage for text pieces */ @@ -178,11 +177,8 @@ public class WordToTextConverter extends AbstractWordConverter DOMSource domSource = new DOMSource( getDocument() ); StreamResult streamResult = new StreamResult( stringWriter ); - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer serializer = tf.newTransformer(); + Transformer serializer = XMLHelper.newTransformer(); // TODO set encoding from a command argument - serializer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" ); - serializer.setOutputProperty( OutputKeys.INDENT, "no" ); serializer.setOutputProperty( OutputKeys.METHOD, "text" ); serializer.transform( domSource, streamResult ); diff --git a/src/scratchpad/testcases/org/apache/poi/hssf/converter/TestExcelConverterSuite.java b/src/scratchpad/testcases/org/apache/poi/hssf/converter/TestExcelConverterSuite.java index cdf362acc9..8b8d05cf57 100644 --- a/src/scratchpad/testcases/org/apache/poi/hssf/converter/TestExcelConverterSuite.java +++ b/src/scratchpad/testcases/org/apache/poi/hssf/converter/TestExcelConverterSuite.java @@ -26,7 +26,6 @@ import java.util.List; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; @@ -106,10 +105,7 @@ public class TestExcelConverterSuite StringWriter stringWriter = new StringWriter(); - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" ); - transformer.setOutputProperty( OutputKeys.INDENT, "no" ); + Transformer transformer = XMLHelper.newTransformer(); transformer.setOutputProperty( OutputKeys.METHOD, "html" ); transformer.transform( new DOMSource( excelToHtmlConverter.getDocument() ), diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java index 1a8d5b8b80..ac0f30006b 100644 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java +++ b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToConverterSuite.java @@ -26,7 +26,6 @@ import java.util.List; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; @@ -105,10 +104,7 @@ public class TestWordToConverterSuite StringWriter stringWriter = new StringWriter(); - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" ); - transformer.setOutputProperty( OutputKeys.INDENT, "false" ); + Transformer transformer = XMLHelper.newTransformer(); transformer.setOutputProperty( OutputKeys.METHOD, "html" ); transformer.transform( new DOMSource( wordToHtmlConverter.getDocument() ), @@ -134,9 +130,7 @@ public class TestWordToConverterSuite StringWriter stringWriter = new StringWriter(); - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" ); + Transformer transformer = XMLHelper.newTransformer(); transformer.setOutputProperty( OutputKeys.INDENT, "yes" ); transformer.setOutputProperty( OutputKeys.METHOD, "text" ); transformer.transform( -- 2.39.5