<forbiddenapis
classpathref="forbiddenapis.classpath"
suppressAnnotation="org.apache.poi.util.SuppressForbidden"
- targetVersion="${jdk.version.source}"
+ targetVersion="${ant.java.version}"
>
<bundledsignatures name="jdk-unsafe"/>
<bundledsignatures name="jdk-deprecated"/>
* <p>
* 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.
* <p>
* 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.
* <p>
- * 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
* <code>IExcelAntWorkbookHandler</code> 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() ) ;
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;
* @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);
}
ClassLoader cl = CryptoFunctions.class.getClassLoader();
String bcProviderName = "org.bouncycastle.jce.provider.BouncyCastleProvider";
Class<Provider> clazz = (Class<Provider>)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);
}
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 {
}
/**
- * 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() {
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.
*/
public enum EncryptionMode {
/* @see <a href="http://msdn.microsoft.com/en-us/library/dd907466(v=office.12).aspx">2.3.6 Office Binary Document RC4 Encryption</a> */
- binaryRC4("org.apache.poi.poifs.crypt.binaryrc4.BinaryRC4EncryptionInfoBuilder", 1, 1, 0x0),
+ binaryRC4(BinaryRC4EncryptionInfoBuilder::new, 1, 1, 0x0),
/* @see <a href="http://msdn.microsoft.com/en-us/library/dd905225(v=office.12).aspx">2.3.5 Office Binary Document RC4 CryptoAPI Encryption</a> */
- cryptoAPI("org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionInfoBuilder", 4, 2, 0x04),
+ cryptoAPI(CryptoAPIEncryptionInfoBuilder::new, 4, 2, 0x04),
/* @see <a href="http://msdn.microsoft.com/en-us/library/dd906097(v=office.12).aspx">2.3.4.5 \EncryptionInfo Stream (Standard Encryption)</a> */
- standard("org.apache.poi.poifs.crypt.standard.StandardEncryptionInfoBuilder", 4, 2, 0x24),
+ standard(StandardEncryptionInfoBuilder::new, 4, 2, 0x24),
/* @see <a href="http://msdn.microsoft.com/en-us/library/dd925810(v=office.12).aspx">2.3.4.10 \EncryptionInfo Stream (Agile Encryption)</a> */
- agile("org.apache.poi.poifs.crypt.agile.AgileEncryptionInfoBuilder", 4, 4, 0x40),
+ agile(AgileEncryptionInfoBuilder::new, 4, 4, 0x40),
/* @see <a href="https://msdn.microsoft.com/en-us/library/dd907599(v=office.12).aspx">XOR Obfuscation</a> */
- xor("org.apache.poi.poifs.crypt.xor.XOREncryptionInfoBuilder", 0, 0, 0)
+ xor(XOREncryptionInfoBuilder::new, 0, 0, 0)
;
-
- public final String builder;
+
+ public final Supplier<EncryptionInfoBuilder> builder;
public final int versionMajor;
public final int versionMinor;
public final int encryptionFlags;
-
- EncryptionMode(String builder, int versionMajor, int versionMinor, int encryptionFlags) {
+
+ EncryptionMode(Supplier<EncryptionInfoBuilder> builder, int versionMajor, int versionMinor, int encryptionFlags) {
this.builder = builder;
this.versionMajor = versionMajor;
this.versionMinor = versionMinor;
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;
public DrawPictureShape(PictureShape<?,?> shape) {
super(shape);
}
-
+
@Override
public void drawContent(Graphics2D graphics) {
PictureShape<?,?> ps = getShape();
for (String kr : KNOWN_RENDERER) {
final ImageRenderer ir;
try {
- ir = ((Class<? extends ImageRenderer>)cl.loadClass(kr)).newInstance();
- } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
+ ir = ((Class<? extends ImageRenderer>)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;
protected PictureShape<?,?> getShape() {
return (PictureShape<?,?>)shape;
}
-
+
/**
* Resize this picture to the default size.
*
==================================================================== */
package org.apache.poi.ss.usermodel;
+import java.beans.PropertyChangeSupport;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
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;
* 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 "#" */
/** 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);
*/
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)
}
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.
}
private Format createFormat(double cellValue, int formatIndex, String sFormat) {
- localeChangedObservable.checkForLocaleChange();
+ checkForLocaleChange();
String formatStr = sFormat;
return getDefaultFormat(cell.getNumericCellValue());
}
private Format getDefaultFormat(double cellValue) {
- localeChangedObservable.checkForLocaleChange();
+ checkForLocaleChange();
// for numeric cells try user supplied default
if (defaultNumFormat != null) {
* @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)) {
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);
* @return a string value of the cell
*/
public String formatCellValue(Cell cell, FormulaEvaluator evaluator, ConditionalFormattingEvaluator cfEvaluator) {
- localeChangedObservable.checkForLocaleChange();
+ checkForLocaleChange();
if (cell == null) {
return "";
* 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;
addFormat("000-00-0000", ssnFormat);
}
-
-
/**
* Format class for Excel's SSN format. This class mimics Excel's built-in
* SSN formatting.
// 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
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;
/* ====================================================================
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;
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;
/**
* JSR105 implementation of the RelationshipTransform transformation.
- *
+ *
* <p>
* Specs: http://openiso.org/Ecma/376/Part2/12.2.4#26
* </p>
private final List<String> sourceIds;
private static final POILogger LOG = POILogFactory.getLogger(RelationshipTransformService.class);
-
+
/**
* Relationship Transform parameter specification class.
*/
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");
/**
* 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)");
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());
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);
parentNode.appendChild(el);
}
}
-
+
public AlgorithmParameterSpec getParameterSpec() {
LOG.log(POILogger.DEBUG, "getParameterSpec");
return null;
/**
* The relationships transform takes the XML document from the Relationships part
* and converts it to another XML document.
- *
+ *
* @see <a href="https://www.ecma-international.org/activities/Office%20Open%20XML%20Formats/Draft%20ECMA-376%203rd%20edition,%20March%202011/Office%20Open%20XML%20Part%202%20-%20Open%20Packaging%20Conventions.pdf">13.2.4.24 Relationships Transform Algorithm</a>
* @see <a href="https://stackoverflow.com/questions/36063375">XML Relationship Transform Algorithm</a>
*/
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();
for (Element el : rsList.values()) {
root.appendChild(el);
}
-
+
LOG.log(POILogger.DEBUG, "# Relationship elements: ", rsList.size());
-
+
return new ApacheNodeSetData(new XMLSignatureInput(root));
}
_fd = createTempFile();
_out = createWriter(_fd);
}
-
+
public SheetDataWriter(Writer writer) throws IOException {
_fd = null;
_out = writer;
if (_fd.exists() && !_fd.delete()) {
logger.log(POILogger.ERROR, "Can't delete temporary encryption file: "+_fd);
}
-
- super.finalize();
}
/**
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;
* 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" +
}
@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();
}
}
}
- 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);
}
}
}
}
- 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:
}
break;
case WORD_V8:
+ @SuppressWarnings("unchecked")
Class<? extends POIDocument> clazz = (Class<? extends POIDocument>)Class.forName("org.apache.poi.hwpf.HWPFDocument");
Constructor<? extends POIDocument> con = clazz.getDeclaredConstructor(InputStream.class);
Method m = clazz.getMethod("getDocumentText");
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;
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
}
@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();
}
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;
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;
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");
XSSFWorkbook wb = new XSSFWorkbook(is)) {
List<XSSFObjectData> oleShapes = new ArrayList<>();
List<Ole10Native> ole10s = new ArrayList<>();
- List<String> digests = new ArrayList<>();
final boolean digestMatch =
wb.getSheetAt(0).getDrawingPatriarch().getShapes().stream()
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();
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;
//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);
}
}
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();
}
# This file contains API signatures which are specific to POI.\r
# The goal is to minimize implicit defaults\r
\r
-@ignoreUnresolvable\r
+@ignoreMissingClasses\r
@defaultMessage POI forbidden APIs\r
\r
# Locale related interfaces which we want to avoid to not have code which depends on the locale of the current machine\r
@defaultMessage Don't interrupt threads use FutureUtils#cancel(Future<T>) instead\r
java.util.concurrent.Future#cancel(boolean)\r
\r
-@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 \r
-java.io.InputStream#available() \r
+@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\r
+java.io.InputStream#available()\r
\r
@defaultMessage Use newInstance, as newFactory does not seem to work on Android - https://github.com/centic9/poi-on-android/issues/44#issuecomment-426517981\r
javax.xml.stream.XMLEventFactory#newFactory()\r
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;
* Test <code>Table</code> 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 <code>Table</code>
*/
@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());
+ }
}
/**
*/
@Test
public void test45889() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow();
- HSLFSlide slide = ppt.createSlide();
- List<HSLFShape> 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<HSLFShape> 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<? extends Slide<?,?>> slides = ppt.getSlides();
- assertEquals(1, slides.size());
+ List<? extends Slide<?, ?>> slides = ppt.getSlides();
+ assertEquals(1, slides.size());
- List<? extends Shape<?,?>> shapes = slides.get(0).getShapes(); //throws NullPointerException
+ List<? extends Shape<?, ?>> 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);
+ }
}
}
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;
public void tearDown() throws Exception {
poifs.close();
}
-
+
/**
* Setup is used to get the document ready. Gets the DocumentSummaryInformation and the
* SummaryInformation to reasonable values
/* 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);
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);
}
/**
/* 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);
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);
/* 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);
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);
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);
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);
}
}
/* 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();
/* 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);
/* 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);
}
sb.append(" ");
char j = (char) rand.nextInt(220);
j += 33;
- // System.out.println(j);
sb.append(">");
sb.append(Character.valueOf(j));
sb.append("=");
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;
public void draw(Shape s) {
String l =
- "draw(Shape):" +
+ "draw(Shape):" +
"\n s = " + s;
log.println( l );
g2D.draw( s );
@Override
public final void finalize() {
log.println( "finalize():" );
- g2D.finalize(); // NOSOLAR
- super.finalize();
+ g2D.dispose();
+ dispose();
}
public Shape getClip() {
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
// 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.");
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();
// 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++) {
@Test
public void testGetDataValidationsAny() throws Exception {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet();
- List<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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<HSSFDataValidation> 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());
+ }
}
}
private static final Object[] SAMPLE_VALUES = {
Boolean.TRUE,
null,
- new Double(1.1),
+ 1.1,
"Sample text",
ErrorConstant.valueOf(FormulaError.DIV0.getCode()),
};
"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])) {
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
/**
* 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",
};
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) {
}
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);
}
public SimpleAsciiOutputStream(OutputStream os) {
_os = os;
}
-
+
@Override
public void write(int b) throws IOException {
checkByte(b);
}
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) {
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]);