From 60303201dcb715a7738cd5bff3a85ffb424a2a90 Mon Sep 17 00:00:00 2001 From: Andreas Beeker Date: Sat, 15 Aug 2020 00:18:42 +0000 Subject: [PATCH] use the forbidden-apis policies corresponding to the JRE fix the forbidden apis issues git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1880866 13f79535-47bb-0310-9956-ffa450edef68 --- build.xml | 2 +- .../poi/ss/excelant/ExcelAntHandlerTask.java | 20 +- .../excelant/util/ExcelAntWorkbookUtil.java | 5 +- .../poi/poifs/crypt/CryptoFunctions.java | 2 +- .../poi/poifs/crypt/EncryptionInfo.java | 25 +- .../poi/poifs/crypt/EncryptionMode.java | 25 +- .../apache/poi/sl/draw/DrawPictureShape.java | 9 +- .../poi/ss/usermodel/DataFormatter.java | 65 +- src/java/org/apache/poi/util/XMLHelper.java | 2 +- .../poi/poifs/crypt/dsig/SignatureInfo.java | 2 +- .../RelationshipTransformService.java | 59 +- .../poi/xssf/streaming/SheetDataWriter.java | 4 +- .../org/apache/poi/sl/tests/TestFonts.java | 7 +- .../org/apache/poi/sl/tests/TestOleShape.java | 7 +- .../org/apache/poi/sl/tests/TestSlide.java | 33 +- .../org/apache/poi/sl/tests/TestTable.java | 4 +- .../tests/usermodel/TestEmbedOLEPackage.java | 10 +- .../xssf/extractor/TestXSSFImportFromXML.java | 9 +- .../devtools/forbidden-signatures.txt | 6 +- .../org/apache/poi/hslf/model/TestTable.java | 133 +++-- .../poi/hpsf/basic/TestMetaDataIPI.java | 74 +-- .../poi/hssf/usermodel/DummyGraphics2d.java | 10 +- .../hssf/usermodel/TestDataValidation.java | 564 ++++++++---------- .../constant/TestConstantValueParser.java | 14 +- .../ExcelFileFormatDocFunctionExtractor.java | 40 +- .../ss/formula/functions/TestStatsLib.java | 2 +- .../poi/ss/formula/ptg/TestArrayPtg.java | 2 +- 27 files changed, 538 insertions(+), 597 deletions(-) diff --git a/build.xml b/build.xml index 29d097cf01..4debd31e6c 100644 --- a/build.xml +++ b/build.xml @@ -2261,7 +2261,7 @@ under the License. diff --git a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntHandlerTask.java b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntHandlerTask.java index c6baee4f24..75892aa738 100644 --- a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntHandlerTask.java +++ b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntHandlerTask.java @@ -27,43 +27,43 @@ import org.apache.tools.ant.Task; *

* Its purpose is to provide a way to manipulate a workbook in the course * of an ExcelAnt task. The idea being to model a way for test writers to - * simulate the behaviors of the workbook. + * simulate the behaviors of the workbook. *

* Suppose, for example, you have a workbook that has a worksheet that * reacts to values entered or selected by the user. It's possible in * Excel to change other cells based on this but this isn't easily possible * in POI. In ExcelAnt we handle this using the Handler, which is a Java - * class you write to manipulate the workbook. + * class you write to manipulate the workbook. *

- * In order to use this tag you must write a class that implements the + * In order to use this tag you must write a class that implements the * IExcelAntWorkbookHandler interface. After writing the - * class you should package it and it's dependencies into a jar file to + * class you should package it and it's dependencies into a jar file to * add as library in your Ant build file. - * + * * @author Jon Svede ( jon [at] loquatic [dot] com ) * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) * */ public class ExcelAntHandlerTask extends Task { - + private String className ; - + private ExcelAntWorkbookUtil wbUtil ; public void setClassName( String cName ) { className = cName ; } - + protected void setEAWorkbookUtil( ExcelAntWorkbookUtil wkbkUtil ) { wbUtil = wkbkUtil ; } - + @Override public void execute() throws BuildException { log( "handling the workbook with class " + className, Project.MSG_INFO ) ; try { Class clazz = Class.forName( className ) ; - Object handlerObj = clazz.newInstance() ; + Object handlerObj = clazz.getDeclaredConstructor().newInstance() ; if( handlerObj instanceof IExcelAntWorkbookHandler ) { IExcelAntWorkbookHandler iHandler = (IExcelAntWorkbookHandler)handlerObj ; iHandler.setWorkbook( wbUtil.getWorkbook() ) ; diff --git a/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtil.java b/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtil.java index 63cd97e523..ee3f443228 100644 --- a/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtil.java +++ b/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtil.java @@ -18,6 +18,7 @@ package org.apache.poi.ss.excelant.util; import java.io.FileInputStream; +import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; @@ -114,9 +115,9 @@ public class ExcelAntWorkbookUtil extends Typedef { * @throws InstantiationException if the class cannot be constructed * @throws IllegalAccessException if the constructor or the class is not accessible */ - public void addFunction(String name, String clazzName) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + public void addFunction(String name, String clazzName) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { Class clazzInst = Class.forName(clazzName); - Object newInst = clazzInst.newInstance(); + Object newInst = clazzInst.getDeclaredConstructor().newInstance(); if(newInst instanceof FreeRefFunction) { addFunction(name, (FreeRefFunction)newInst); } diff --git a/src/java/org/apache/poi/poifs/crypt/CryptoFunctions.java b/src/java/org/apache/poi/poifs/crypt/CryptoFunctions.java index 46cd58128a..369cbd67e4 100644 --- a/src/java/org/apache/poi/poifs/crypt/CryptoFunctions.java +++ b/src/java/org/apache/poi/poifs/crypt/CryptoFunctions.java @@ -329,7 +329,7 @@ public final class CryptoFunctions { ClassLoader cl = CryptoFunctions.class.getClassLoader(); String bcProviderName = "org.bouncycastle.jce.provider.BouncyCastleProvider"; Class clazz = (Class)cl.loadClass(bcProviderName); - Security.addProvider(clazz.newInstance()); + Security.addProvider(clazz.getDeclaredConstructor().newInstance()); } catch (Exception e) { throw new EncryptedDocumentException("Only the BouncyCastle provider supports your encryption settings - please add it to the classpath.", e); } diff --git a/src/java/org/apache/poi/poifs/crypt/EncryptionInfo.java b/src/java/org/apache/poi/poifs/crypt/EncryptionInfo.java index 17a9136fe4..f02fb16d8c 100644 --- a/src/java/org/apache/poi/poifs/crypt/EncryptionInfo.java +++ b/src/java/org/apache/poi/poifs/crypt/EncryptionInfo.java @@ -38,9 +38,7 @@ import org.apache.poi.util.BitFieldFactory; import org.apache.poi.util.LittleEndianInput; /** - * This class may require {@code poi-ooxml} to be on the classpath to load - * some {@link EncryptionMode}s. - * @see #getBuilder(EncryptionMode) + * Wrapper for the EncryptionInfo node of encrypted documents */ public class EncryptionInfo implements GenericRecord { @@ -214,28 +212,13 @@ public class EncryptionInfo implements GenericRecord { } /** - * This method loads the builder class with reflection, which may generate - * a {@code ClassNotFoundException} if the class is not on the classpath. - * For example, {@link org.apache.poi.poifs.crypt.agile.AgileEncryptionInfoBuilder} - * is contained in the {@code poi-ooxml} package since the class makes use of some OOXML - * classes rather than using the {@code poi} package and plain XML DOM calls. - * As such, you may need to include {@code poi-ooxml} and {@code poi-ooxml-schemas} to load - * some encryption mode builders. See bug #60021 for more information. - * https://bz.apache.org/bugzilla/show_bug.cgi?id=60021 + * Create the builder instance * * @param encryptionMode the encryption mode * @return an encryption info builder - * @throws ClassNotFoundException if the builder class is not on the classpath - * @throws IllegalAccessException if the builder class can't be loaded - * @throws InstantiationException if the builder class can't be loaded */ - @SuppressWarnings({"WeakerAccess", "JavadocReference"}) - protected static EncryptionInfoBuilder getBuilder(EncryptionMode encryptionMode) - throws ClassNotFoundException, IllegalAccessException, InstantiationException { - ClassLoader cl = EncryptionInfo.class.getClassLoader(); - EncryptionInfoBuilder eib; - eib = (EncryptionInfoBuilder)cl.loadClass(encryptionMode.builder).newInstance(); - return eib; + private static EncryptionInfoBuilder getBuilder(EncryptionMode encryptionMode) { + return encryptionMode.builder.get(); } public int getVersionMajor() { diff --git a/src/java/org/apache/poi/poifs/crypt/EncryptionMode.java b/src/java/org/apache/poi/poifs/crypt/EncryptionMode.java index 2f89557996..393247df8d 100644 --- a/src/java/org/apache/poi/poifs/crypt/EncryptionMode.java +++ b/src/java/org/apache/poi/poifs/crypt/EncryptionMode.java @@ -17,7 +17,14 @@ package org.apache.poi.poifs.crypt; +import java.util.function.Supplier; + import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; +import org.apache.poi.poifs.crypt.agile.AgileEncryptionInfoBuilder; +import org.apache.poi.poifs.crypt.binaryrc4.BinaryRC4EncryptionInfoBuilder; +import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionInfoBuilder; +import org.apache.poi.poifs.crypt.standard.StandardEncryptionInfoBuilder; +import org.apache.poi.poifs.crypt.xor.XOREncryptionInfoBuilder; /** * Office supports various encryption modes. @@ -27,23 +34,23 @@ import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; */ public enum EncryptionMode { /* @see 2.3.6 Office Binary Document RC4 Encryption */ - binaryRC4("org.apache.poi.poifs.crypt.binaryrc4.BinaryRC4EncryptionInfoBuilder", 1, 1, 0x0), + binaryRC4(BinaryRC4EncryptionInfoBuilder::new, 1, 1, 0x0), /* @see 2.3.5 Office Binary Document RC4 CryptoAPI Encryption */ - cryptoAPI("org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionInfoBuilder", 4, 2, 0x04), + cryptoAPI(CryptoAPIEncryptionInfoBuilder::new, 4, 2, 0x04), /* @see 2.3.4.5 \EncryptionInfo Stream (Standard Encryption) */ - standard("org.apache.poi.poifs.crypt.standard.StandardEncryptionInfoBuilder", 4, 2, 0x24), + standard(StandardEncryptionInfoBuilder::new, 4, 2, 0x24), /* @see 2.3.4.10 \EncryptionInfo Stream (Agile Encryption) */ - agile("org.apache.poi.poifs.crypt.agile.AgileEncryptionInfoBuilder", 4, 4, 0x40), + agile(AgileEncryptionInfoBuilder::new, 4, 4, 0x40), /* @see XOR Obfuscation */ - xor("org.apache.poi.poifs.crypt.xor.XOREncryptionInfoBuilder", 0, 0, 0) + xor(XOREncryptionInfoBuilder::new, 0, 0, 0) ; - - public final String builder; + + public final Supplier builder; public final int versionMajor; public final int versionMinor; public final int encryptionFlags; - - EncryptionMode(String builder, int versionMajor, int versionMinor, int encryptionFlags) { + + EncryptionMode(Supplier builder, int versionMajor, int versionMinor, int encryptionFlags) { this.builder = builder; this.versionMajor = versionMajor; this.versionMinor = versionMinor; diff --git a/src/java/org/apache/poi/sl/draw/DrawPictureShape.java b/src/java/org/apache/poi/sl/draw/DrawPictureShape.java index 83b50c22db..edf4a4d688 100644 --- a/src/java/org/apache/poi/sl/draw/DrawPictureShape.java +++ b/src/java/org/apache/poi/sl/draw/DrawPictureShape.java @@ -23,6 +23,7 @@ import java.awt.Insets; import java.awt.Paint; import java.awt.geom.Rectangle2D; import java.io.IOException; +import java.lang.reflect.InvocationTargetException; import org.apache.poi.sl.usermodel.PictureData; import org.apache.poi.sl.usermodel.PictureShape; @@ -42,7 +43,7 @@ public class DrawPictureShape extends DrawSimpleShape { public DrawPictureShape(PictureShape shape) { super(shape); } - + @Override public void drawContent(Graphics2D graphics) { PictureShape ps = getShape(); @@ -98,8 +99,8 @@ public class DrawPictureShape extends DrawSimpleShape { for (String kr : KNOWN_RENDERER) { final ImageRenderer ir; try { - ir = ((Class)cl.loadClass(kr)).newInstance(); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { + ir = ((Class)cl.loadClass(kr)).getConstructor().newInstance(); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { // scratchpad was not on the path, ignore and continue LOG.log(POILogger.INFO, "Known image renderer '"+kr+" not found/loaded - include poi-scratchpad jar!", e); continue; @@ -125,7 +126,7 @@ public class DrawPictureShape extends DrawSimpleShape { protected PictureShape getShape() { return (PictureShape)shape; } - + /** * Resize this picture to the default size. * diff --git a/src/java/org/apache/poi/ss/usermodel/DataFormatter.java b/src/java/org/apache/poi/ss/usermodel/DataFormatter.java index b2312841c7..5f383776b7 100644 --- a/src/java/org/apache/poi/ss/usermodel/DataFormatter.java +++ b/src/java/org/apache/poi/ss/usermodel/DataFormatter.java @@ -20,6 +20,7 @@ ==================================================================== */ package org.apache.poi.ss.usermodel; +import java.beans.PropertyChangeSupport; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DateFormat; @@ -36,8 +37,6 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Observable; -import java.util.Observer; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -119,7 +118,7 @@ import org.apache.poi.util.POILogger; * you need it. */ @SuppressWarnings("unused") -public class DataFormatter implements Observer { +public class DataFormatter { private static final String defaultFractionWholePartFormat = "#"; private static final String defaultFractionFractionPartFormat = "#/##"; /** Pattern to find a number format: "0" or "#" */ @@ -213,20 +212,8 @@ public class DataFormatter implements Observer { /** stores if the locale should change according to {@link LocaleUtil#getUserLocale()} */ private boolean localeIsAdapting; - private class LocaleChangeObservable extends Observable { - void checkForLocaleChange() { - checkForLocaleChange(LocaleUtil.getUserLocale()); - } - void checkForLocaleChange(Locale newLocale) { - if (!localeIsAdapting) return; - if (newLocale.equals(locale)) return; - super.setChanged(); - notifyObservers(newLocale); - } - } - - /** the Observable to notify, when the locale has been changed */ - private final LocaleChangeObservable localeChangedObservable = new LocaleChangeObservable(); + // contain a support object instead of extending the support class + private final PropertyChangeSupport pcs; /** For logging any problems we find */ private static POILogger logger = POILogFactory.getLogger(DataFormatter.class); @@ -270,9 +257,9 @@ public class DataFormatter implements Observer { */ public DataFormatter(Locale locale, boolean localeIsAdapting, boolean emulateCSV) { this.localeIsAdapting = true; - localeChangedObservable.addObserver(this); + pcs = new PropertyChangeSupport(this); // localeIsAdapting must be true prior to this first checkForLocaleChange call. - localeChangedObservable.checkForLocaleChange(locale); + checkForLocaleChange(locale); // set localeIsAdapting so subsequent checks perform correctly // (whether a specific locale was provided to this DataFormatter or DataFormatter should // adapt to the current user locale as the locale changes) @@ -319,7 +306,7 @@ public class DataFormatter implements Observer { } private Format getFormat(double cellValue, int formatIndex, String formatStrIn, boolean use1904Windowing) { - localeChangedObservable.checkForLocaleChange(); + checkForLocaleChange(); // Might be better to separate out the n p and z formats, falling back to p when n and z are not set. // That however would require other code to be re factored. @@ -391,7 +378,7 @@ public class DataFormatter implements Observer { } private Format createFormat(double cellValue, int formatIndex, String sFormat) { - localeChangedObservable.checkForLocaleChange(); + checkForLocaleChange(); String formatStr = sFormat; @@ -787,7 +774,7 @@ public class DataFormatter implements Observer { return getDefaultFormat(cell.getNumericCellValue()); } private Format getDefaultFormat(double cellValue) { - localeChangedObservable.checkForLocaleChange(); + checkForLocaleChange(); // for numeric cells try user supplied default if (defaultNumFormat != null) { @@ -891,7 +878,7 @@ public class DataFormatter implements Observer { * @see #formatCellValue(Cell) */ public String formatRawCellContents(double value, int formatIndex, String formatString, boolean use1904Windowing) { - localeChangedObservable.checkForLocaleChange(); + checkForLocaleChange(); // Is it a date? if(DateUtil.isADateFormat(formatIndex,formatString)) { @@ -929,7 +916,7 @@ public class DataFormatter implements Observer { else { result = numberFormat.format(new BigDecimal(textValue)); } - + // If they requested a non-abbreviated Scientific format, // and there's an E## (but not E-##), add the missing '+' for E+## String fslc = formatString.toLowerCase(Locale.ROOT); @@ -1006,7 +993,7 @@ public class DataFormatter implements Observer { * @return a string value of the cell */ public String formatCellValue(Cell cell, FormulaEvaluator evaluator, ConditionalFormattingEvaluator cfEvaluator) { - localeChangedObservable.checkForLocaleChange(); + checkForLocaleChange(); if (cell == null) { return ""; @@ -1117,24 +1104,32 @@ public class DataFormatter implements Observer { * formats need to be refreshed. All formats which aren't originated from DataFormatter * itself, i.e. all Formats added via {@link DataFormatter#addFormat(String, Format)} and * {@link DataFormatter#setDefaultNumberFormat(Format)}, need to be added again. - * To notify callers, the returned {@link Observable} should be used. - * The Object in {@link Observer#update(Observable, Object)} is the new Locale. + * To notify callers, the returned {@link PropertyChangeSupport} should be used. + * The Locale in {@link #updateLocale(Locale)} is the new Locale. * * @return the listener object, where callers can register themselves */ - public Observable getLocaleChangedObservable() { - return localeChangedObservable; + public PropertyChangeSupport getLocaleChangedObservable() { + return pcs; + } + + private void checkForLocaleChange() { + checkForLocaleChange(LocaleUtil.getUserLocale()); + } + + private void checkForLocaleChange(Locale newLocale) { + if (!localeIsAdapting) return; + if (newLocale.equals(locale)) return; + updateLocale(newLocale); + pcs.firePropertyChange("locale", locale, newLocale); } /** * Update formats when locale has been changed * - * @param observable usually this is our own Observable instance - * @param localeObj only reacts on Locale objects + * @param newLocale the new locale */ - public void update(Observable observable, Object localeObj) { - if (!(localeObj instanceof Locale)) return; - Locale newLocale = (Locale)localeObj; + public void updateLocale(Locale newLocale) { if (!localeIsAdapting || newLocale.equals(locale)) return; locale = newLocale; @@ -1166,8 +1161,6 @@ public class DataFormatter implements Observer { addFormat("000-00-0000", ssnFormat); } - - /** * Format class for Excel's SSN format. This class mimics Excel's built-in * SSN formatting. diff --git a/src/java/org/apache/poi/util/XMLHelper.java b/src/java/org/apache/poi/util/XMLHelper.java index e99e7d9ecb..d9e00d9a3c 100644 --- a/src/java/org/apache/poi/util/XMLHelper.java +++ b/src/java/org/apache/poi/util/XMLHelper.java @@ -247,7 +247,7 @@ public final class XMLHelper { // Try built-in JVM one first, standalone if not for (String securityManagerClassName : SECURITY_MANAGERS) { try { - Object mgr = Class.forName(securityManagerClassName).newInstance(); + Object mgr = Class.forName(securityManagerClassName).getDeclaredConstructor().newInstance(); Method setLimit = mgr.getClass().getMethod(METHOD_ENTITY_EXPANSION_XERCES, Integer.TYPE); setLimit.invoke(mgr, 1); // Stop once one can be setup without error diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureInfo.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureInfo.java index d6ce28b759..de73c19c0a 100644 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureInfo.java +++ b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureInfo.java @@ -701,7 +701,7 @@ public class SignatureInfo { private Provider getProvider(String className) { try { - return (Provider)Class.forName(className).newInstance(); + return (Provider)Class.forName(className).getDeclaredConstructor().newInstance(); } catch (Exception e) { LOG.log(POILogger.DEBUG, "XMLDsig-Provider '"+className+"' can't be found - trying next."); return null; diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RelationshipTransformService.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RelationshipTransformService.java index 7cee2a0187..74b0945173 100644 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RelationshipTransformService.java +++ b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RelationshipTransformService.java @@ -18,9 +18,9 @@ /* ==================================================================== This product contains an ASLv2 licensed version of the OOXML signer package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt + http://code.google.com/p/eid-applet/source/browse/trunk/README.txt Copyright (C) 2008-2014 FedICT. - ================================================================= */ + ================================================================= */ package org.apache.poi.poifs.crypt.dsig.services; @@ -52,6 +52,7 @@ import org.apache.jcp.xml.dsig.internal.dom.ApacheNodeSetData; import org.apache.poi.ooxml.util.DocumentHelper; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; +import org.apache.poi.util.SuppressForbidden; import org.apache.xml.security.signature.XMLSignatureInput; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; @@ -65,7 +66,7 @@ import org.w3c.dom.NodeList; /** * JSR105 implementation of the RelationshipTransform transformation. - * + * *

* Specs: http://openiso.org/Ecma/376/Part2/12.2.4#26 *

@@ -77,7 +78,7 @@ public class RelationshipTransformService extends TransformService { private final List sourceIds; private static final POILogger LOG = POILogFactory.getLogger(RelationshipTransformService.class); - + /** * Relationship Transform parameter specification class. */ @@ -90,8 +91,20 @@ public class RelationshipTransformService extends TransformService { return !sourceIds.isEmpty(); } } - - + + @SuppressForbidden("new Provider(String,String,String) is not available in Java 8") + private static final class POIXmlDsigProvider extends Provider { + static final long serialVersionUID = 1L; + private static final String NAME = "POIXmlDsigProvider"; + + private POIXmlDsigProvider() { + super(NAME, 1d, NAME); + put("TransformService." + TRANSFORM_URI, RelationshipTransformService.class.getName()); + put("TransformService." + TRANSFORM_URI + " MechanismType", "DOM"); + } + } + + public RelationshipTransformService() { super(); LOG.log(POILogger.DEBUG, "constructor"); @@ -100,24 +113,18 @@ public class RelationshipTransformService extends TransformService { /** * Register the provider for this TransformService - * + * * @see javax.xml.crypto.dsig.TransformService */ public static synchronized void registerDsigProvider() { // the xml signature classes will try to find a special TransformerService, - // which is ofcourse unknown to JCE before ... - final String dsigProvider = "POIXmlDsigProvider"; - if (Security.getProperty(dsigProvider) == null) { - Provider p = new Provider(dsigProvider, 1.0, dsigProvider){ - static final long serialVersionUID = 1L; - }; - p.put("TransformService." + TRANSFORM_URI, RelationshipTransformService.class.getName()); - p.put("TransformService." + TRANSFORM_URI + " MechanismType", "DOM"); - Security.addProvider(p); + // which is of course unknown to JCE before ... + if (Security.getProperty(POIXmlDsigProvider.NAME) == null) { + Security.addProvider(new POIXmlDsigProvider()); } } - - + + @Override public void init(TransformParameterSpec params) throws InvalidAlgorithmParameterException { LOG.log(POILogger.DEBUG, "init(params)"); @@ -134,7 +141,7 @@ public class RelationshipTransformService extends TransformService { LOG.log(POILogger.DEBUG, "parent java type: " + parent.getClass().getName()); DOMStructure domParent = (DOMStructure) parent; Node parentNode = domParent.getNode(); - + try { TransformDocument transDoc = TransformDocument.Factory.parse(parentNode, DEFAULT_XML_OPTIONS); XmlObject[] xoList = transDoc.getTransform().selectChildren(RelationshipReferenceDocument.type.getDocumentElementName()); @@ -157,7 +164,7 @@ public class RelationshipTransformService extends TransformService { DOMStructure domParent = (DOMStructure) parent; Element parentNode = (Element)domParent.getNode(); Document doc = parentNode.getOwnerDocument(); - + for (String sourceId : this.sourceIds) { Element el = doc.createElementNS(OO_DIGSIG_NS, "mdssi:RelationshipReference"); el.setAttributeNS(XML_NS, "xmlns:mdssi", OO_DIGSIG_NS); @@ -165,7 +172,7 @@ public class RelationshipTransformService extends TransformService { parentNode.appendChild(el); } } - + public AlgorithmParameterSpec getParameterSpec() { LOG.log(POILogger.DEBUG, "getParameterSpec"); return null; @@ -174,7 +181,7 @@ public class RelationshipTransformService extends TransformService { /** * The relationships transform takes the XML document from the Relationships part * and converts it to another XML document. - * + * * @see 13.2.4.24 Relationships Transform Algorithm * @see XML Relationship Transform Algorithm */ @@ -184,14 +191,14 @@ public class RelationshipTransformService extends TransformService { OctetStreamData octetStreamData = (OctetStreamData) data; LOG.log(POILogger.DEBUG, "URI: " + octetStreamData.getURI()); InputStream octetStream = octetStreamData.getOctetStream(); - + Document doc; try { doc = DocumentHelper.readDocument(octetStream); } catch (Exception e) { throw new TransformException(e.getMessage(), e); } - + // keep only those relationships which id is registered in the sourceIds Element root = doc.getDocumentElement(); NodeList nl = root.getChildNodes(); @@ -215,9 +222,9 @@ public class RelationshipTransformService extends TransformService { for (Element el : rsList.values()) { root.appendChild(el); } - + LOG.log(POILogger.DEBUG, "# Relationship elements: ", rsList.size()); - + return new ApacheNodeSetData(new XMLSignatureInput(root)); } diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SheetDataWriter.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SheetDataWriter.java index 2e8e7a7887..2c41313691 100644 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SheetDataWriter.java +++ b/src/ooxml/java/org/apache/poi/xssf/streaming/SheetDataWriter.java @@ -72,7 +72,7 @@ public class SheetDataWriter implements Closeable { _fd = createTempFile(); _out = createWriter(_fd); } - + public SheetDataWriter(Writer writer) throws IOException { _fd = null; _out = writer; @@ -188,8 +188,6 @@ public class SheetDataWriter implements Closeable { if (_fd.exists() && !_fd.delete()) { logger.log(POILogger.ERROR, "Can't delete temporary encryption file: "+_fd); } - - super.finalize(); } /** diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestFonts.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestFonts.java index 2b9963ecd7..28a958c8af 100644 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestFonts.java +++ b/src/ooxml/testcases/org/apache/poi/sl/tests/TestFonts.java @@ -40,6 +40,7 @@ import org.apache.poi.common.usermodel.fonts.FontGroup; import org.apache.poi.sl.draw.Drawable; import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; +import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; import org.apache.poi.sl.usermodel.TextBox; import org.apache.poi.sl.usermodel.TextParagraph; @@ -53,7 +54,7 @@ import org.junit.Test; * Test rendering - specific to font handling */ public class TestFonts { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); private static final String JPTEXT = "\u3061\u3087\u3063\u3068\u65E9\u3044\u3051\u3069T\u30B7\u30E3\u30C4\u304C\u7740\u305F\u304F\u306A" + @@ -78,9 +79,9 @@ public class TestFonts { } @Test - public void resizeToFitTextHSLF() throws IOException, ReflectiveOperationException { + public void resizeToFitTextHSLF() throws IOException { assumeFalse(xslfOnly()); - SlideShow ppt = (SlideShow)Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow").newInstance(); + SlideShow ppt = SlideShowFactory.create(false); resizeToFitText(ppt); ppt.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestOleShape.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestOleShape.java index f652bcc0e0..061b628f33 100644 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestOleShape.java +++ b/src/ooxml/testcases/org/apache/poi/sl/tests/TestOleShape.java @@ -147,12 +147,12 @@ public class TestOleShape { } } - private SlideShow createSlideShow() throws ReflectiveOperationException { + private SlideShow createSlideShow() throws IOException { if (api == Api.XSLF) { return new XMLSlideShow(); } else { assumeFalse(xslfOnly()); - return (SlideShow)Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow").newInstance(); + return SlideShowFactory.create(false); } } @@ -187,7 +187,7 @@ public class TestOleShape { } } - private void validateOleData(final InputStream in) throws IOException, InvalidFormatException, ReflectiveOperationException { + private void validateOleData(final InputStream in) throws IOException, ReflectiveOperationException { switch (app) { case EXCEL_V8: case EXCEL_V12: @@ -196,6 +196,7 @@ public class TestOleShape { } break; case WORD_V8: + @SuppressWarnings("unchecked") Class clazz = (Class)Class.forName("org.apache.poi.hwpf.HWPFDocument"); Constructor con = clazz.getDeclaredConstructor(InputStream.class); Method m = clazz.getMethod("getDocumentText"); diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestSlide.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestSlide.java index 47494b3407..19b8ab38b1 100644 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestSlide.java +++ b/src/ooxml/testcases/org/apache/poi/sl/tests/TestSlide.java @@ -29,6 +29,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.xslf.usermodel.XMLSlideShow; @@ -37,36 +38,36 @@ import org.junit.Test; public class TestSlide { @Test - public void hideHSLF() throws IOException, ReflectiveOperationException { + public void hideHSLF() throws IOException { assumeFalse(xslfOnly()); - SlideShow ppt1 = (SlideShow)Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow").newInstance(); - hideSlide(ppt1); - ppt1.close(); + try (SlideShow ppt1 = SlideShowFactory.create(false)) { + hideSlide(ppt1); + } } @Test public void hideXSLF() throws IOException { - SlideShow ppt1 = new XMLSlideShow(); - hideSlide(ppt1); - ppt1.close(); + try (SlideShow ppt1 = new XMLSlideShow()) { + hideSlide(ppt1); + } } private void hideSlide(SlideShow ppt1) throws IOException { ppt1.createSlide().setHidden(true); ppt1.createSlide(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ppt1.write(bos); - ppt1.close(); + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + ppt1.write(bos); - InputStream is = new ByteArrayInputStream(bos.toByteArray()); - SlideShow ppt2 = SlideShowFactory.create(is); + try (InputStream is = new ByteArrayInputStream(bos.toByteArray()); + SlideShow ppt2 = SlideShowFactory.create(is)) { - Boolean[] hiddenState = ppt2.getSlides().stream().map(e -> e.isHidden()).toArray(Boolean[]::new); + Boolean[] hiddenState = ppt2.getSlides().stream().map(Slide::isHidden).toArray(Boolean[]::new); - assertTrue(hiddenState[0]); - assertFalse(hiddenState[1]); + assertTrue(hiddenState[0]); + assertFalse(hiddenState[1]); - ppt2.close(); + } + } } } \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestTable.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestTable.java index fd31762b8d..2ab404b030 100644 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestTable.java +++ b/src/ooxml/testcases/org/apache/poi/sl/tests/TestTable.java @@ -95,9 +95,9 @@ public class TestTable { } @Test - public void directionHSLF() throws IOException, ReflectiveOperationException { + public void directionHSLF() throws IOException { assumeFalse(xslfOnly()); - SlideShow ppt1 = (SlideShow)Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow").newInstance(); + SlideShow ppt1 = SlideShowFactory.create(false); testTextDirection(ppt1); ppt1.close(); } diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java index f184b01516..28c1bcc06a 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java +++ b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java @@ -50,6 +50,7 @@ import org.apache.poi.sl.usermodel.AutoShape; import org.apache.poi.sl.usermodel.ShapeType; import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; +import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.ss.extractor.EmbeddedData; import org.apache.poi.ss.extractor.EmbeddedExtractor; import org.apache.poi.ss.usermodel.ClientAnchor; @@ -58,7 +59,6 @@ import org.apache.poi.ss.usermodel.ObjectData; import org.apache.poi.ss.usermodel.Shape; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFObjectData; import org.apache.poi.xssf.usermodel.XSSFWorkbook; @@ -71,7 +71,7 @@ public class TestEmbedOLEPackage { private static final POIDataSamples ssamples = POIDataSamples.getSpreadSheetInstance(); @BeforeClass - public static void init() throws IOException, ReflectiveOperationException { + public static void init() throws IOException { samplePPT = getSamplePPT(false); samplePPTX = getSamplePPT(true); samplePNG = ssamples.readFile("logoKarmokar4.png"); @@ -83,7 +83,6 @@ public class TestEmbedOLEPackage { XSSFWorkbook wb = new XSSFWorkbook(is)) { List oleShapes = new ArrayList<>(); List ole10s = new ArrayList<>(); - List digests = new ArrayList<>(); final boolean digestMatch = wb.getSheetAt(0).getDrawingPatriarch().getShapes().stream() @@ -212,9 +211,8 @@ public class TestEmbedOLEPackage { pat2.createObjectData(anchor2, oleIdx2, picIdx); } - static byte[] getSamplePPT(boolean ooxml) throws IOException, ReflectiveOperationException { - SlideShow ppt = (ooxml) ? new XMLSlideShow() - : (SlideShow)Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow").newInstance(); + static byte[] getSamplePPT(boolean ooxml) throws IOException { + SlideShow ppt = SlideShowFactory.create(ooxml); Slide slide = ppt.createSlide(); AutoShape sh1 = slide.createAutoShape(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java index 6ba55c0692..13e79a6ffc 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java @@ -21,7 +21,6 @@ import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import java.io.IOException; import java.text.DateFormatSymbols; @@ -156,10 +155,10 @@ public class TestXSSFImportFromXML { //Check for Schema element XSSFSheet sheet = wb.getSheetAt(0); - assertEquals(new Double(id), sheet.getRow(28).getCell(1).getNumericCellValue(), 0); + assertEquals(id, sheet.getRow(28).getCell(1).getNumericCellValue(), 0); assertEquals(displayName, sheet.getRow(11).getCell(5).getStringCellValue()); assertEquals(ref, sheet.getRow(14).getCell(7).getStringCellValue()); - assertEquals(new Double(count), sheet.getRow(18).getCell(3).getNumericCellValue(), 0); + assertEquals(count, sheet.getRow(18).getCell(3).getNumericCellValue(), 0); } } @@ -225,13 +224,13 @@ public class TestXSSFImportFromXML { assertEquals(date, rowData.getCell(0).getDateCellValue()); assertEquals("Amount Int", rowHeadings.getCell(1).getStringCellValue()); - assertEquals(new Double(Integer.MIN_VALUE), rowData.getCell(1).getNumericCellValue(), 0); + assertEquals(Integer.MIN_VALUE, rowData.getCell(1).getNumericCellValue(), 0); assertEquals("Amount Double", rowHeadings.getCell(2).getStringCellValue()); assertEquals(1.0000123, rowData.getCell(2).getNumericCellValue(), 0); assertEquals("Amount UnsignedInt", rowHeadings.getCell(3).getStringCellValue()); - assertEquals(new Double(12345), rowData.getCell(3).getNumericCellValue(), 0); + assertEquals(12345d, rowData.getCell(3).getNumericCellValue(), 0); wb.close(); } diff --git a/src/resources/devtools/forbidden-signatures.txt b/src/resources/devtools/forbidden-signatures.txt index d296489896..facc47035f 100644 --- a/src/resources/devtools/forbidden-signatures.txt +++ b/src/resources/devtools/forbidden-signatures.txt @@ -17,7 +17,7 @@ # This file contains API signatures which are specific to POI. # The goal is to minimize implicit defaults -@ignoreUnresolvable +@ignoreMissingClasses @defaultMessage POI forbidden APIs # Locale related interfaces which we want to avoid to not have code which depends on the locale of the current machine @@ -120,8 +120,8 @@ java.lang.Object#notifyAll() @defaultMessage Don't interrupt threads use FutureUtils#cancel(Future) instead java.util.concurrent.Future#cancel(boolean) -@defaultMessage Don't use ...InputStream.available() as it gives wrong result for certain streams - use IOUtils.toByteArray to read the stream fully and then count the available bytes -java.io.InputStream#available() +@defaultMessage Don't use ...InputStream.available() as it gives wrong result for certain streams - use IOUtils.toByteArray to read the stream fully and then count the available bytes +java.io.InputStream#available() @defaultMessage Use newInstance, as newFactory does not seem to work on Android - https://github.com/centic9/poi-on-android/issues/44#issuecomment-426517981 javax.xml.stream.XMLEventFactory#newFactory() diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTable.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTable.java index 2dddf74950..265d81af41 100644 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTable.java +++ b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTable.java @@ -21,7 +21,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -45,41 +44,44 @@ import org.junit.Test; * Test Table object. */ public final class TestTable { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); /** * Test that ShapeFactory works properly and returns Table */ @Test public void testShapeFactory() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); + final int noColumns, noRows; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (HSLFSlideShow ppt = new HSLFSlideShow()) { + HSLFSlide slide = ppt.createSlide(); - HSLFSlide slide = ppt.createSlide(); + HSLFTable tbl = slide.createTable(2, 5); - HSLFTable tbl = slide.createTable(2, 5); + HSLFTableCell cell = tbl.getCell(0, 0); + assertNotNull(cell); + noColumns = tbl.getNumberOfColumns(); + noRows = tbl.getNumberOfRows(); - HSLFTableCell cell = tbl.getCell(0, 0); - //table cells have type=TextHeaderAtom.OTHER_TYPE, see bug #46033 - assertEquals(TextPlaceholder.OTHER.nativeId, cell.getTextParagraphs().get(0).getRunType()); + //table cells have type=TextHeaderAtom.OTHER_TYPE, see bug #46033 + assertEquals(TextPlaceholder.OTHER.nativeId, cell.getTextParagraphs().get(0).getRunType()); - HSLFShape tblSh = slide.getShapes().get(0); - assertTrue(tblSh instanceof HSLFTable); - HSLFTable tbl2 = (HSLFTable)tblSh; - assertEquals(tbl.getNumberOfColumns(), tbl2.getNumberOfColumns()); - assertEquals(tbl.getNumberOfRows(), tbl2.getNumberOfRows()); + HSLFShape tblSh = slide.getShapes().get(0); + assertTrue(tblSh instanceof HSLFTable); + HSLFTable tbl2 = (HSLFTable) tblSh; + assertEquals(noColumns, tbl2.getNumberOfColumns()); + assertEquals(noRows, tbl2.getNumberOfRows()); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - ppt.close(); - - ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - slide = ppt.getSlides().get(0); - assertTrue(slide.getShapes().get(0) instanceof HSLFTable); - HSLFTable tbl3 = (HSLFTable)slide.getShapes().get(0); - assertEquals(tbl.getNumberOfColumns(), tbl3.getNumberOfColumns()); - assertEquals(tbl.getNumberOfRows(), tbl3.getNumberOfRows()); - ppt.close(); + ppt.write(out); + } + + try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray()))) { + HSLFSlide slide = ppt.getSlides().get(0); + assertTrue(slide.getShapes().get(0) instanceof HSLFTable); + HSLFTable tbl3 = (HSLFTable) slide.getShapes().get(0); + assertEquals(noColumns, tbl3.getNumberOfColumns()); + assertEquals(noRows, tbl3.getNumberOfRows()); + } } /** @@ -87,66 +89,65 @@ public final class TestTable { */ @Test public void test45889() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - List shapes; - HSLFTable tbl1 = slide.createTable(1, 5); - assertEquals(5, tbl1.getNumberOfColumns()); - assertEquals(1, tbl1.getNumberOfRows()); - - shapes = slide.getShapes(); - assertEquals(1, shapes.size()); - - HSLFTable tbl2 = (HSLFTable)shapes.get(0); - assertSame(tbl1.getSpContainer(), tbl2.getSpContainer()); - - assertEquals(tbl1.getNumberOfColumns(), tbl2.getNumberOfColumns()); - assertEquals(tbl1.getNumberOfRows(), tbl2.getNumberOfRows()); - ppt.close(); + try (HSLFSlideShow ppt = new HSLFSlideShow()) { + HSLFSlide slide = ppt.createSlide(); + List shapes; + HSLFTable tbl1 = slide.createTable(1, 5); + assertEquals(5, tbl1.getNumberOfColumns()); + assertEquals(1, tbl1.getNumberOfRows()); + + shapes = slide.getShapes(); + assertEquals(1, shapes.size()); + + HSLFTable tbl2 = (HSLFTable) shapes.get(0); + assertSame(tbl1.getSpContainer(), tbl2.getSpContainer()); + + assertEquals(tbl1.getNumberOfColumns(), tbl2.getNumberOfColumns()); + assertEquals(tbl1.getNumberOfRows(), tbl2.getNumberOfRows()); + } } + // Table(rownum, colnum) must throw IllegalArgumentException if any of the arguments is less than 1 @Test(expected=IllegalArgumentException.class) public void testIllegalRowCnstruction() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - slide.createTable(0, 5); - fail("Table(rownum, colnum) must throw IllegalArgumentException if any of tghe arguments is less than 1"); - ppt.close(); + try (HSLFSlideShow ppt = new HSLFSlideShow()) { + HSLFSlide slide = ppt.createSlide(); + slide.createTable(0, 5); + } } + // Table(rownum, colnum) must throw IllegalArgumentException if any of the arguments is less than 1 @Test(expected=IllegalArgumentException.class) public void testIllegalColConstruction() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - slide.createTable(5, 0); - fail("Table(rownum, colnum) must throw IllegalArgumentException if any of tghe arguments is less than 1"); - ppt.close(); + try (HSLFSlideShow ppt = new HSLFSlideShow()) { + HSLFSlide slide = ppt.createSlide(); + slide.createTable(5, 0); + } } - + /** * Bug 57820: initTable throws NullPointerException * when the table is positioned with its top at -1 */ @Test public void test57820() throws IOException { - SlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("bug57820-initTableNullRefrenceException.ppt")); + try (SlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("bug57820-initTableNullRefrenceException.ppt"))) { - List> slides = ppt.getSlides(); - assertEquals(1, slides.size()); + List> slides = ppt.getSlides(); + assertEquals(1, slides.size()); - List> shapes = slides.get(0).getShapes(); //throws NullPointerException + List> shapes = slides.get(0).getShapes(); //throws NullPointerException - TableShape tbl = null; - for(Shape s : shapes) { - if(s instanceof TableShape) { - tbl = (TableShape)s; - break; + TableShape tbl = null; + for (Shape s : shapes) { + if (s instanceof TableShape) { + tbl = (TableShape) s; + break; + } } - } - assertNotNull(tbl); - assertEquals(-1, tbl.getAnchor().getY(), 0); - - ppt.close(); + assertNotNull(tbl); + assertEquals(-1, tbl.getAnchor().getY(), 0); + } } } diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java b/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java index de4dea27ef..9347699566 100644 --- a/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java +++ b/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java @@ -18,6 +18,7 @@ package org.apache.poi.hpsf.basic; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -55,7 +56,7 @@ public final class TestMetaDataIPI { public void tearDown() throws Exception { poifs.close(); } - + /** * Setup is used to get the document ready. Gets the DocumentSummaryInformation and the * SummaryInformation to reasonable values @@ -96,12 +97,12 @@ public final class TestMetaDataIPI { /* Insert some custom properties into the container. */ customProperties.put("Key1", "Value1"); customProperties.put("Schl\u00fcssel2", "Wert2"); - customProperties.put("Sample Integer", new Integer(12345)); - customProperties.put("Sample Boolean", Boolean.TRUE); + customProperties.put("Sample Integer", 12345); + customProperties.put("Sample Boolean", true); Date date = new Date(); customProperties.put("Sample Date", date); - customProperties.put("Sample Double", new Double(-1.0001)); - customProperties.put("Sample Negative Integer", new Integer(-100000)); + customProperties.put("Sample Double", -1.0001); + customProperties.put("Sample Negative Integer", -100000); dsi.setCustomProperties(customProperties); @@ -136,17 +137,17 @@ public final class TestMetaDataIPI { String a2 = (String) customProperties.get("Schl\u00fcssel2"); assertEquals("Schl\u00fcssel2", "Wert2", a2); Integer a3 = (Integer) customProperties.get("Sample Integer"); - assertEquals("Sample Number", new Integer(12345), a3); + assertEquals("Sample Number", 12345, (int)a3); Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertEquals("Sample Boolean", Boolean.TRUE, a4); + assertTrue("Sample Boolean", a4); Date a5 = (Date) customProperties.get("Sample Date"); assertEquals("Custom Date:", date, a5); Double a6 = (Double) customProperties.get("Sample Double"); - assertEquals("Custom Float", new Double(-1.0001), a6); + assertEquals("Custom Float", -1.0001, a6, 0); Integer a7 = (Integer) customProperties.get("Sample Negative Integer"); - assertEquals("Neg", new Integer(-100000), a7); + assertEquals("Neg", -100000, (int)a7); } /** @@ -185,7 +186,7 @@ public final class TestMetaDataIPI { /* Insert some custom properties into the container. */ customProperties.put(k1, p1); customProperties.put(k2, p2); - customProperties.put("Sample Number", new Integer(12345)); + customProperties.put("Sample Number", 12345); customProperties.put("Sample Boolean", Boolean.TRUE); Date date = new Date(); customProperties.put("Sample Date", date); @@ -226,9 +227,9 @@ public final class TestMetaDataIPI { String a2 = (String) customProperties.get(k2); assertEquals("Schl\u00fcssel2", p2, a2); Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals("Sample Number", new Integer(12345), a3); + assertEquals("Sample Number", 12345, (int)a3); Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertEquals("Sample Boolean", Boolean.TRUE, a4); + assertTrue("Sample Boolean", a4); Date a5 = (Date) customProperties.get("Sample Date"); assertEquals("Custom Date:", date, a5); @@ -271,8 +272,8 @@ public final class TestMetaDataIPI { /* Insert some custom properties into the container. */ customProperties.put(k1, p1); customProperties.put(k2, p2); - customProperties.put("Sample Number", new Integer(12345)); - customProperties.put("Sample Boolean", Boolean.FALSE); + customProperties.put("Sample Number", 12345); + customProperties.put("Sample Boolean", false); Date date = new Date(0); customProperties.put("Sample Date", date); @@ -313,9 +314,9 @@ public final class TestMetaDataIPI { String a2 = (String) customProperties.get(k2); assertEquals("Schl\u00fcssel2", p2, a2); Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals("Sample Number", new Integer(12345), a3); + assertEquals("Sample Number", 12345, (int)a3); Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertEquals("Sample Boolean", Boolean.FALSE, a4); + assertFalse("Sample Boolean", a4); Date a5 = (Date) customProperties.get("Sample Date"); assertEquals("Custom Date:", date, a5); @@ -359,13 +360,13 @@ public final class TestMetaDataIPI { si.setComments(comments); si.setKeywords(keywords); si.setSubject(subject); - + CustomProperties customProperties = new CustomProperties(); /* Insert some custom properties into the container. */ customProperties.put(k1, p1); customProperties.put(k2, p2); - customProperties.put("Sample Number", new Integer(12345)); - customProperties.put("Sample Boolean", Boolean.TRUE); + customProperties.put("Sample Number", 12345); + customProperties.put("Sample Boolean", true); Date date = new Date(); customProperties.put("Sample Date", date); @@ -404,9 +405,9 @@ public final class TestMetaDataIPI { String a2 = (String) customProperties.get(k2); assertEquals("Schl\u00fcssel2", p2, a2); Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals("Sample Number", new Integer(12345), a3); + assertEquals("Sample Number", 12345, (int)a3); Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertEquals("Sample Boolean", Boolean.TRUE, a4); + assertTrue("Sample Boolean", a4); Date a5 = (Date) customProperties.get("Sample Date"); assertEquals("Custom Date:", date, a5); } @@ -437,16 +438,16 @@ public final class TestMetaDataIPI { } /* Insert some custom properties into the container. */ - customProperties.put("int", new Integer(12345)); - customProperties.put("negint", new Integer(-12345)); - customProperties.put("long", new Long(12345)); - customProperties.put("neglong", new Long(-12345)); - customProperties.put("boolean", Boolean.TRUE); + customProperties.put("int", 12345); + customProperties.put("negint", -12345); + customProperties.put("long", 12345L); + customProperties.put("neglong", -12345L); + customProperties.put("boolean", true); customProperties.put("string", "a String"); // customProperties.put("float", new Float(12345.0)); is not valid // customProperties.put("negfloat", new Float(-12345.1)); is not valid - customProperties.put("double", new Double(12345.2)); - customProperties.put("negdouble", new Double(-12345.3)); + customProperties.put("double", 12345.2); + customProperties.put("negdouble", -12345.3); // customProperties.put("char", new Character('a')); is not valid Date date = new Date(); @@ -485,28 +486,28 @@ public final class TestMetaDataIPI { /* Insert some custom properties into the container. */ Integer a3 = (Integer) customProperties.get("int"); - assertEquals("int", new Integer(12345), a3); + assertEquals("int", 12345, (int)a3); a3 = (Integer) customProperties.get("negint"); - assertEquals("negint", new Integer(-12345), a3); + assertEquals("negint", -12345, (int)a3); Long al = (Long) customProperties.get("neglong"); - assertEquals("neglong", new Long(-12345), al); + assertEquals("neglong", -12345L, (long)al); al = (Long) customProperties.get("long"); - assertEquals("long", new Long(12345), al); + assertEquals("long", 12345L, (long)al); Boolean a4 = (Boolean) customProperties.get("boolean"); - assertEquals("boolean", Boolean.TRUE, a4); + assertTrue("boolean", a4); Date a5 = (Date) customProperties.get("date"); assertEquals("Custom Date:", date, a5); Double d = (Double) customProperties.get("double"); - assertEquals("int", new Double(12345.2), d); + assertEquals("int", 12345.2, d, 0); d = (Double) customProperties.get("negdouble"); - assertEquals("string", new Double(-12345.3), d); + assertEquals("string", -12345.3, d, 0); String s = (String) customProperties.get("string"); assertEquals("sring", "a String", s); @@ -543,7 +544,7 @@ public final class TestMetaDataIPI { /* Read the document summary information. */ DirectoryEntry dir = poifs.getRoot(); - + dsi = (DocumentSummaryInformation)PropertySetFactory.create(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME); si = (SummaryInformation)PropertySetFactory.create(dir, SummaryInformation.DEFAULT_STREAM_NAME); } @@ -595,7 +596,6 @@ public final class TestMetaDataIPI { sb.append(" "); char j = (char) rand.nextInt(220); j += 33; - // System.out.println(j); sb.append(">"); sb.append(Character.valueOf(j)); sb.append("="); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/DummyGraphics2d.java b/src/testcases/org/apache/poi/hssf/usermodel/DummyGraphics2d.java index 6275fc0d02..a10cc1309d 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/DummyGraphics2d.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/DummyGraphics2d.java @@ -56,13 +56,13 @@ public class DummyGraphics2d extends Graphics2D { public DummyGraphics2d() { this(System.out); } - + public DummyGraphics2d(PrintStream log) { bufimg = new BufferedImage(1000, 1000, 2); g2D = (Graphics2D)bufimg.getGraphics(); this.log = log; } - + public DummyGraphics2d(PrintStream log, Graphics2D g2D) { this.g2D = g2D; this.log = log; @@ -86,7 +86,7 @@ public class DummyGraphics2d extends Graphics2D { public void draw(Shape s) { String l = - "draw(Shape):" + + "draw(Shape):" + "\n s = " + s; log.println( l ); g2D.draw( s ); @@ -715,8 +715,8 @@ public class DummyGraphics2d extends Graphics2D { @Override public final void finalize() { log.println( "finalize():" ); - g2D.finalize(); // NOSOLAR - super.finalize(); + g2D.dispose(); + dispose(); } public Shape getClip() { diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java b/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java index e5ddcaa7f7..1e3fc381cc 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java @@ -61,14 +61,14 @@ public final class TestDataValidation extends BaseTestDataValidation { public void assertDataValidation(Workbook wb) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(22000); - try { + byte[] generatedContent; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(22000)) { wb.write(baos); - baos.close(); + generatedContent = baos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } - byte[] generatedContent = baos.toByteArray(); + boolean isSame; // if (false) { // // TODO - add proof spreadsheet and compare @@ -76,23 +76,21 @@ public final class TestDataValidation extends BaseTestDataValidation { // isSame = compareStreams(proofStream, generatedContent); // } isSame = true; - + if (isSame) { return; } File tempDir = new File(System.getProperty("java.io.tmpdir")); File generatedFile = new File(tempDir, "GeneratedTestDataValidation.xls"); - try { - FileOutputStream fileOut = new FileOutputStream(generatedFile); + try (FileOutputStream fileOut = new FileOutputStream(generatedFile)) { fileOut.write(generatedContent); - fileOut.close(); } catch (IOException e) { throw new RuntimeException(e); } - + PrintStream ps = System.out; - - ps.println("This test case has failed because the generated file differs from proof copy '" + + ps.println("This test case has failed because the generated file differs from proof copy '" ); // TODO+ proofFile.getAbsolutePath() + "'."); ps.println("The cause is usually a change to this test, or some common spreadsheet generation code. " + "The developer has to decide whether the changes were wanted or unwanted."); @@ -104,68 +102,43 @@ public final class TestDataValidation extends BaseTestDataValidation { ps.println("One other possible (but less likely) cause of a failed test is a problem in the " + "comparison logic used here. Perhaps some extra file regions need to be ignored."); ps.println("The generated file has been saved to '" + generatedFile.getAbsolutePath() + "' for manual inspection."); - - fail("Generated file differs from proof copy. See sysout comments for details on how to fix."); - - } - -// private static boolean compareStreams(InputStream isA, byte[] generatedContent) { -// -// InputStream isB = new ByteArrayInputStream(generatedContent); -// -// // The allowable regions where the generated file can differ from the -// // proof should be small (i.e. much less than 1K) -// int[] allowableDifferenceRegions = { -// 0x0228, 16, // a region of the file containing the OS username -// 0x506C, 8, // See RootProperty (super fields _seconds_2 and _days_2) -// }; -// int[] diffs = StreamUtility.diffStreams(isA, isB, allowableDifferenceRegions); -// if (diffs == null) { -// return true; -// } -// System.err.println("Diff from proof: "); -// for (int i = 0; i < diffs.length; i++) { -// System.err.println("diff at offset: 0x" + Integer.toHexString(diffs[i])); -// } -// return false; -// } - - + fail("Generated file differs from proof copy. See sysout comments for details on how to fix."); + } /* package */ static void setCellValue(HSSFCell cell, String text) { cell.setCellValue(new HSSFRichTextString(text)); - + } - + @Test public void testAddToExistingSheet() throws Exception { - // dvEmpty.xls is a simple one sheet workbook. With a DataValidations header record but no + // dvEmpty.xls is a simple one sheet workbook. With a DataValidations header record but no // DataValidations. It's important that the example has one SHEETPROTECTION record. // Such a workbook can be created in Excel (2007) by adding datavalidation for one cell // and then deleting the row that contains the cell. - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("dvEmpty.xls"); - int dvRow = 0; - Sheet sheet = wb.getSheetAt(0); - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint dc = dataValidationHelper.createIntegerConstraint(OperatorType.EQUAL, "42", null); - DataValidation dv = dataValidationHelper.createValidation(dc,new CellRangeAddressList(dvRow, dvRow, 0, 0)); - - dv.setEmptyCellAllowed(false); - dv.setErrorStyle(ErrorStyle.STOP); - dv.setShowPromptBox(true); - dv.createErrorBox("Xxx", "Yyy"); - dv.setSuppressDropDownArrow(true); - - sheet.addValidationData(dv); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - wb.write(baos); - - byte[] wbData = baos.toByteArray(); - + try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("dvEmpty.xls")) { + int dvRow = 0; + Sheet sheet = wb.getSheetAt(0); + DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); + DataValidationConstraint dc = dataValidationHelper.createIntegerConstraint(OperatorType.EQUAL, "42", null); + DataValidation dv = dataValidationHelper.createValidation(dc, new CellRangeAddressList(dvRow, dvRow, 0, 0)); + + dv.setEmptyCellAllowed(false); + dv.setErrorStyle(ErrorStyle.STOP); + dv.setShowPromptBox(true); + dv.createErrorBox("Xxx", "Yyy"); + dv.setSuppressDropDownArrow(true); + + sheet.addValidationData(dv); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + wb.write(baos); + + byte[] wbData = baos.toByteArray(); + // if (false) { // TODO (Jul 2008) fix EventRecordFactory to process unknown records, (and DV records for that matter) // // ERFListener erfListener = null; // new MyERFListener(); @@ -179,27 +152,25 @@ public final class TestDataValidation extends BaseTestDataValidation { // throw new RuntimeException(e); // } // } - // else verify record ordering by navigating the raw bytes - - byte[] dvHeaderRecStart= { (byte)0xB2, 0x01, 0x12, 0x00, }; - int dvHeaderOffset = findIndex(wbData, dvHeaderRecStart); - assertTrue(dvHeaderOffset > 0); - int nextRecIndex = dvHeaderOffset + 22; - int nextSid - = ((wbData[nextRecIndex + 0] << 0) & 0x00FF) - + ((wbData[nextRecIndex + 1] << 8) & 0xFF00) - ; - // nextSid should be for a DVRecord. If anything comes between the DV header record - // and the DV records, Excel will not be able to open the workbook without error. - - if (nextSid == 0x0867) { - fail("Identified bug 45519"); - } - assertEquals(DVRecord.sid, nextSid); - - wb.close(); + // else verify record ordering by navigating the raw bytes + + byte[] dvHeaderRecStart = {(byte) 0xB2, 0x01, 0x12, 0x00,}; + int dvHeaderOffset = findIndex(wbData, dvHeaderRecStart); + assertTrue(dvHeaderOffset > 0); + int nextRecIndex = dvHeaderOffset + 22; + int nextSid + = ((wbData[nextRecIndex + 0] << 0) & 0x00FF) + + ((wbData[nextRecIndex + 1] << 8) & 0xFF00); + // nextSid should be for a DVRecord. If anything comes between the DV header record + // and the DV records, Excel will not be able to open the workbook without error. + + if (nextSid == 0x0867) { + fail("Identified bug 45519"); + } + assertEquals(DVRecord.sid, nextSid); + } } - + private int findIndex(byte[] largeData, byte[] searchPattern) { byte firstByte = searchPattern[0]; for (int i = 0; i < largeData.length; i++) { @@ -222,256 +193,243 @@ public final class TestDataValidation extends BaseTestDataValidation { @Test public void testGetDataValidationsAny() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createNumericConstraint(ValidationType.ANY, - OperatorType.IGNORED, null, null); - CellRangeAddressList addressList = new CellRangeAddressList(1, 2, 3, 4); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - validation.setEmptyCellAllowed(true); - validation.createErrorBox("error-title", "error-text"); - validation.createPromptBox("prompt-title", "prompt-text"); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - { - CellRangeAddressList regions = dv.getRegions(); - assertEquals(1, regions.countRanges()); - - CellRangeAddress address = regions.getCellRangeAddress(0); - assertEquals(1, address.getFirstRow()); - assertEquals(2, address.getLastRow()); - assertEquals(3, address.getFirstColumn()); - assertEquals(4, address.getLastColumn()); + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFSheet sheet = wb.createSheet(); + List list = sheet.getDataValidations(); + assertEquals(0, list.size()); + + DataValidationHelper dvh = sheet.getDataValidationHelper(); + DataValidationConstraint constraint = dvh.createNumericConstraint(ValidationType.ANY, OperatorType.IGNORED, null, null); + CellRangeAddressList addressList = new CellRangeAddressList(1, 2, 3, 4); + DataValidation validation = dvh.createValidation(constraint, addressList); + validation.setEmptyCellAllowed(true); + validation.createErrorBox("error-title", "error-text"); + validation.createPromptBox("prompt-title", "prompt-text"); + sheet.addValidationData(validation); + + list = sheet.getDataValidations(); // <-- works + assertEquals(1, list.size()); + + HSSFDataValidation dv = list.get(0); + { + CellRangeAddressList regions = dv.getRegions(); + assertEquals(1, regions.countRanges()); + + CellRangeAddress address = regions.getCellRangeAddress(0); + assertEquals(1, address.getFirstRow()); + assertEquals(2, address.getLastRow()); + assertEquals(3, address.getFirstColumn()); + assertEquals(4, address.getLastColumn()); + } + assertTrue(dv.getEmptyCellAllowed()); + assertFalse(dv.getSuppressDropDownArrow()); + assertTrue(dv.getShowErrorBox()); + assertEquals("error-title", dv.getErrorBoxTitle()); + assertEquals("error-text", dv.getErrorBoxText()); + assertTrue(dv.getShowPromptBox()); + assertEquals("prompt-title", dv.getPromptBoxTitle()); + assertEquals("prompt-text", dv.getPromptBoxText()); + + DataValidationConstraint c = dv.getValidationConstraint(); + assertEquals(ValidationType.ANY, c.getValidationType()); + assertEquals(OperatorType.IGNORED, c.getOperator()); } - assertTrue(dv.getEmptyCellAllowed()); - assertFalse(dv.getSuppressDropDownArrow()); - assertTrue(dv.getShowErrorBox()); - assertEquals("error-title", dv.getErrorBoxTitle()); - assertEquals("error-text", dv.getErrorBoxText()); - assertTrue(dv.getShowPromptBox()); - assertEquals("prompt-title", dv.getPromptBoxTitle()); - assertEquals("prompt-text", dv.getPromptBoxText()); - - DataValidationConstraint c = dv.getValidationConstraint(); - assertEquals(ValidationType.ANY, c.getValidationType()); - assertEquals(OperatorType.IGNORED, c.getOperator()); - - wb.close(); } @Test public void testGetDataValidationsIntegerFormula() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createIntegerConstraint(OperatorType.BETWEEN, "=A2", - "=A3"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.INTEGER, c.getValidationType()); - assertEquals(OperatorType.BETWEEN, c.getOperator()); - assertEquals("A2", c.getFormula1()); - assertEquals("A3", c.getFormula2()); - assertNull(c.getValue1()); - assertNull(c.getValue2()); - - wb.close(); + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFSheet sheet = wb.createSheet(); + List list = sheet.getDataValidations(); + assertEquals(0, list.size()); + + DataValidationHelper dvh = sheet.getDataValidationHelper(); + DataValidationConstraint constraint = dvh.createIntegerConstraint(OperatorType.BETWEEN, "=A2", "=A3"); + CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); + DataValidation validation = dvh.createValidation(constraint, addressList); + sheet.addValidationData(validation); + + list = sheet.getDataValidations(); // <-- works + assertEquals(1, list.size()); + + HSSFDataValidation dv = list.get(0); + DVConstraint c = dv.getConstraint(); + assertEquals(ValidationType.INTEGER, c.getValidationType()); + assertEquals(OperatorType.BETWEEN, c.getOperator()); + assertEquals("A2", c.getFormula1()); + assertEquals("A3", c.getFormula2()); + assertNull(c.getValue1()); + assertNull(c.getValue2()); + } } @Test public void testGetDataValidationsIntegerValue() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createIntegerConstraint(OperatorType.BETWEEN, "100", - "200"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.INTEGER, c.getValidationType()); - assertEquals(OperatorType.BETWEEN, c.getOperator()); - assertNull(c.getFormula1()); - assertNull(c.getFormula2()); - assertEquals(new Double("100"), c.getValue1()); - assertEquals(new Double("200"), c.getValue2()); - - wb.close(); + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFSheet sheet = wb.createSheet(); + List list = sheet.getDataValidations(); + assertEquals(0, list.size()); + + DataValidationHelper dvh = sheet.getDataValidationHelper(); + DataValidationConstraint constraint = dvh.createIntegerConstraint(OperatorType.BETWEEN, "100", "200"); + CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); + DataValidation validation = dvh.createValidation(constraint, addressList); + sheet.addValidationData(validation); + + list = sheet.getDataValidations(); // <-- works + assertEquals(1, list.size()); + + HSSFDataValidation dv = list.get(0); + DVConstraint c = dv.getConstraint(); + assertEquals(ValidationType.INTEGER, c.getValidationType()); + assertEquals(OperatorType.BETWEEN, c.getOperator()); + assertNull(c.getFormula1()); + assertNull(c.getFormula2()); + assertEquals(100d, c.getValue1(), 0); + assertEquals(200d, c.getValue2(), 0); + } } @Test public void testGetDataValidationsDecimal() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createDecimalConstraint(OperatorType.BETWEEN, "=A2", - "200"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.DECIMAL, c.getValidationType()); - assertEquals(OperatorType.BETWEEN, c.getOperator()); - assertEquals("A2", c.getFormula1()); - assertNull(c.getFormula2()); - assertNull(c.getValue1()); - assertEquals(new Double("200"), c.getValue2()); - - wb.close(); + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFSheet sheet = wb.createSheet(); + List list = sheet.getDataValidations(); + assertEquals(0, list.size()); + + DataValidationHelper dvh = sheet.getDataValidationHelper(); + DataValidationConstraint constraint = dvh.createDecimalConstraint(OperatorType.BETWEEN, "=A2", "200"); + CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); + DataValidation validation = dvh.createValidation(constraint, addressList); + sheet.addValidationData(validation); + + list = sheet.getDataValidations(); // <-- works + assertEquals(1, list.size()); + + HSSFDataValidation dv = list.get(0); + DVConstraint c = dv.getConstraint(); + assertEquals(ValidationType.DECIMAL, c.getValidationType()); + assertEquals(OperatorType.BETWEEN, c.getOperator()); + assertEquals("A2", c.getFormula1()); + assertNull(c.getFormula2()); + assertNull(c.getValue1()); + assertEquals(200, c.getValue2(), 0); + } } @Test public void testGetDataValidationsDate() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createDateConstraint(OperatorType.EQUAL, - "2014/10/25", null, null); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.DATE, c.getValidationType()); - assertEquals(OperatorType.EQUAL, c.getOperator()); - assertNull(c.getFormula1()); - assertNull(c.getFormula2()); - assertEquals(DateUtil.getExcelDate(DateUtil.parseYYYYMMDDDate("2014/10/25")), c.getValue1(), 0); - assertNull(c.getValue2()); - - wb.close(); + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFSheet sheet = wb.createSheet(); + List list = sheet.getDataValidations(); + assertEquals(0, list.size()); + + DataValidationHelper dvh = sheet.getDataValidationHelper(); + DataValidationConstraint constraint = dvh.createDateConstraint(OperatorType.EQUAL, "2014/10/25", null, null); + CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); + DataValidation validation = dvh.createValidation(constraint, addressList); + sheet.addValidationData(validation); + + list = sheet.getDataValidations(); // <-- works + assertEquals(1, list.size()); + + HSSFDataValidation dv = list.get(0); + DVConstraint c = dv.getConstraint(); + assertEquals(ValidationType.DATE, c.getValidationType()); + assertEquals(OperatorType.EQUAL, c.getOperator()); + assertNull(c.getFormula1()); + assertNull(c.getFormula2()); + assertEquals(DateUtil.getExcelDate(DateUtil.parseYYYYMMDDDate("2014/10/25")), c.getValue1(), 0); + assertNull(c.getValue2()); + } } @Test public void testGetDataValidationsListExplicit() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createExplicitListConstraint(new String[] { "aaa", - "bbb", "ccc" }); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - validation.setSuppressDropDownArrow(true); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - assertTrue(dv.getSuppressDropDownArrow()); - - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.LIST, c.getValidationType()); - assertNull(c.getFormula1()); - assertNull(c.getFormula2()); - assertNull(c.getValue1()); - assertNull(c.getValue2()); - String[] values = c.getExplicitListValues(); - assertEquals(3, values.length); - assertEquals("aaa", values[0]); - assertEquals("bbb", values[1]); - assertEquals("ccc", values[2]); - - wb.close(); + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFSheet sheet = wb.createSheet(); + List list = sheet.getDataValidations(); + assertEquals(0, list.size()); + + DataValidationHelper dvh = sheet.getDataValidationHelper(); + DataValidationConstraint constraint = dvh.createExplicitListConstraint(new String[]{"aaa", "bbb", "ccc"}); + CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); + DataValidation validation = dvh.createValidation(constraint, addressList); + validation.setSuppressDropDownArrow(true); + sheet.addValidationData(validation); + + list = sheet.getDataValidations(); // <-- works + assertEquals(1, list.size()); + + HSSFDataValidation dv = list.get(0); + assertTrue(dv.getSuppressDropDownArrow()); + + DVConstraint c = dv.getConstraint(); + assertEquals(ValidationType.LIST, c.getValidationType()); + assertNull(c.getFormula1()); + assertNull(c.getFormula2()); + assertNull(c.getValue1()); + assertNull(c.getValue2()); + String[] values = c.getExplicitListValues(); + assertEquals(3, values.length); + assertEquals("aaa", values[0]); + assertEquals("bbb", values[1]); + assertEquals("ccc", values[2]); + } } @Test public void testGetDataValidationsListFormula() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createFormulaListConstraint("A2"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - validation.setSuppressDropDownArrow(true); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - assertTrue(dv.getSuppressDropDownArrow()); - - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.LIST, c.getValidationType()); - assertEquals("A2", c.getFormula1()); - assertNull(c.getFormula2()); - assertNull(c.getValue1()); - assertNull(c.getValue2()); - - wb.close(); + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFSheet sheet = wb.createSheet(); + List list = sheet.getDataValidations(); + assertEquals(0, list.size()); + + DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); + DataValidationConstraint constraint = dataValidationHelper.createFormulaListConstraint("A2"); + CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); + DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); + validation.setSuppressDropDownArrow(true); + sheet.addValidationData(validation); + + list = sheet.getDataValidations(); // <-- works + assertEquals(1, list.size()); + + HSSFDataValidation dv = list.get(0); + assertTrue(dv.getSuppressDropDownArrow()); + + DVConstraint c = dv.getConstraint(); + assertEquals(ValidationType.LIST, c.getValidationType()); + assertEquals("A2", c.getFormula1()); + assertNull(c.getFormula2()); + assertNull(c.getValue1()); + assertNull(c.getValue2()); + } } @Test public void testGetDataValidationsFormula() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("A2:A3"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.FORMULA, c.getValidationType()); - assertEquals("A2:A3", c.getFormula1()); - assertNull(c.getFormula2()); - assertNull(c.getValue1()); - assertNull(c.getValue2()); - wb.close(); + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFSheet sheet = wb.createSheet(); + List list = sheet.getDataValidations(); + assertEquals(0, list.size()); + + DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); + DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("A2:A3"); + CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); + DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); + sheet.addValidationData(validation); + + list = sheet.getDataValidations(); // <-- works + assertEquals(1, list.size()); + + HSSFDataValidation dv = list.get(0); + DVConstraint c = dv.getConstraint(); + assertEquals(ValidationType.FORMULA, c.getValidationType()); + assertEquals("A2:A3", c.getFormula1()); + assertNull(c.getFormula2()); + assertNull(c.getValue1()); + assertNull(c.getValue2()); + } } } diff --git a/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java b/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java index 08ce2d96e4..72a9bcc0d8 100644 --- a/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java +++ b/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java @@ -34,7 +34,7 @@ public final class TestConstantValueParser { private static final Object[] SAMPLE_VALUES = { Boolean.TRUE, null, - new Double(1.1), + 1.1, "Sample text", ErrorConstant.valueOf(FormulaError.DIV0.getCode()), }; @@ -44,29 +44,29 @@ public final class TestConstantValueParser { "01 9A 99 99 99 99 99 F1 3F " + "02 0B 00 00 53 61 6D 70 6C 65 20 74 65 78 74 " + "10 07 00 00 00 00 00 00 00"); - + @Test public void testGetEncodedSize() { int actual = ConstantValueParser.getEncodedSize(SAMPLE_VALUES); assertEquals(51, actual); } - + @Test public void testEncode() { int size = ConstantValueParser.getEncodedSize(SAMPLE_VALUES); byte[] data = new byte[size]; - + ConstantValueParser.encode(new LittleEndianByteArrayOutputStream(data, 0), SAMPLE_VALUES); - + if (!Arrays.equals(data, SAMPLE_ENCODING)) { fail("Encoding differs"); } } - + @Test public void testDecode() { LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(SAMPLE_ENCODING); - + Object[] values = ConstantValueParser.parse(in, 4); for (int i = 0; i < values.length; i++) { if(!isEqual(SAMPLE_VALUES[i], values[i])) { diff --git a/src/testcases/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java b/src/testcases/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java index ac2551665d..c408dd527b 100644 --- a/src/testcases/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java +++ b/src/testcases/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java @@ -39,19 +39,20 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; -import java.util.zip.ZipException; import java.util.zip.ZipFile; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + import org.apache.poi.poifs.crypt.CryptoFunctions; import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.util.TempFile; +import org.apache.poi.util.XMLHelper; import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; +import org.xml.sax.helpers.DefaultHandler; /** * This class is not used during normal POI run-time but is used at development time to generate @@ -229,7 +230,7 @@ public final class ExcelFileFormatDocFunctionExtractor { /** * To avoid drag-in - parse XML using only JDK. */ - private static class EFFDocHandler implements ContentHandler { + private static class EFFDocHandler extends DefaultHandler { private static final String[] HEADING_PATH_NAMES = { "office:document-content", "office:body", "office:text", "text:h", }; @@ -339,7 +340,7 @@ public final class ExcelFileFormatDocFunctionExtractor { processFunction(cellData, noteFlags, 0); processFunction(cellData, noteFlags, 8); } - + public void processFunction(String[] cellData, Boolean[] noteFlags, int i) { String funcIxStr = cellData[i + 0]; if (funcIxStr.length() < 1) { @@ -428,27 +429,18 @@ public final class ExcelFileFormatDocFunctionExtractor { } private static void extractFunctionData(FunctionDataCollector fdc, InputStream is) { - XMLReader xr; + SAXParserFactory sf = XMLHelper.getSaxParserFactory(); + SAXParser xr; try { // First up, try the default one - xr = XMLReaderFactory.createXMLReader(); - } catch (SAXException e) { - // Try one for java 1.4 - System.setProperty("org.xml.sax.driver", "org.apache.crimson.parser.XMLReaderImpl"); - try { - xr = XMLReaderFactory.createXMLReader(); - } catch (SAXException e2) { - throw new RuntimeException(e2); - } + xr = sf.newSAXParser(); + } catch (SAXException | ParserConfigurationException e) { + throw new RuntimeException(e); } - xr.setContentHandler(new EFFDocHandler(fdc)); - InputSource inSrc = new InputSource(is); - - try { - xr.parse(inSrc); - is.close(); + try (InputStream is2 = is) { + xr.parse(is2, new EFFDocHandler(fdc)); } catch (IOException | SAXException e) { throw new RuntimeException(e); } @@ -463,7 +455,7 @@ public final class ExcelFileFormatDocFunctionExtractor { public SimpleAsciiOutputStream(OutputStream os) { _os = os; } - + @Override public void write(int b) throws IOException { checkByte(b); diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java b/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java index bb8b8e62bb..9c4fdcb2f2 100644 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java +++ b/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java @@ -220,7 +220,7 @@ public class TestStatsLib extends BaseTestNumeric { } private static void confirmMode(double[] v, double expectedResult) { - confirmMode(v, new Double(expectedResult)); + confirmMode(v, (Double)expectedResult); } private static void confirmMode(double[] v, Double expectedResult) { diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java index 960209681b..170c06719b 100644 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java +++ b/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java @@ -67,7 +67,7 @@ public final class TestArrayPtg { assertEquals(Boolean.TRUE, values[0][0]); assertEquals("ABCD", values[0][1]); - assertEquals(new Double(0), values[1][0]); + assertEquals(0d, values[1][0]); assertEquals(Boolean.FALSE, values[1][1]); assertEquals("FG", values[1][2]); -- 2.39.5