From 65b7c9e273083921f0596524932cbf9c4222454a Mon Sep 17 00:00:00 2001
From: Alain Béarez
Date: Wed, 10 Oct 2018 17:49:53 +0000
Subject: fix most alerts reported by LGTM on OOXML
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1843481 13f79535-47bb-0310-9956-ffa450edef68
---
.../poi/poifs/crypt/dsig/SignatureConfig.java | 100 ++++++------
.../org/apache/poi/xdgf/usermodel/XDGFShape.java | 181 ++++++++++++++-------
.../org/apache/poi/xdgf/usermodel/XDGFText.java | 22 ++-
.../org/apache/poi/xdgf/util/HierarchyPrinter.java | 24 +--
.../java/org/apache/poi/xdgf/util/VsdxToPng.java | 19 ++-
.../apache/poi/xslf/usermodel/XMLSlideShow.java | 6 +-
.../org/apache/poi/xslf/usermodel/XSLFColor.java | 32 ++--
.../org/apache/poi/xslf/usermodel/XSLFNotes.java | 6 +-
.../org/apache/poi/xslf/usermodel/XSLFShape.java | 93 ++++++-----
.../java/org/apache/poi/xslf/util/PPTX2PNG.java | 16 +-
.../org/apache/poi/xssf/binary/XSSFBUtils.java | 2 +-
.../org/apache/poi/xssf/streaming/SXSSFRow.java | 44 ++---
.../org/apache/poi/xssf/usermodel/XSSFDrawing.java | 2 +-
.../org/apache/poi/xssf/usermodel/XSSFRow.java | 77 +++++----
.../apache/poi/xwpf/usermodel/XWPFSDTContent.java | 20 ++-
.../org/apache/poi/xwpf/usermodel/XWPFTable.java | 107 ++++++------
16 files changed, 429 insertions(+), 322 deletions(-)
(limited to 'src/ooxml/java')
diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureConfig.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureConfig.java
index 9fa93f7a06..8e276f896e 100644
--- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureConfig.java
+++ b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureConfig.java
@@ -63,7 +63,7 @@ import org.w3c.dom.events.EventListener;
* This class bundles the configuration options used for the existing
* signature facets.
* Apart of the thread local members (e.g. opc-package) most values will probably be constant, so
- * it might be configured centrally (e.g. by spring)
+ * it might be configured centrally (e.g. by spring)
*/
@SuppressWarnings({"unused","WeakerAccess"})
public class SignatureConfig {
@@ -76,14 +76,14 @@ public class SignatureConfig {
public interface SignatureConfigurable {
- void setSignatureConfig(SignatureConfig signatureConfig);
+ void setSignatureConfig(SignatureConfig signatureConfig);
}
private ThreadLocal opcPackage = new ThreadLocal<>();
private ThreadLocal signatureFactory = new ThreadLocal<>();
private ThreadLocal keyInfoFactory = new ThreadLocal<>();
private ThreadLocal provider = new ThreadLocal<>();
-
+
private List signatureFacets = new ArrayList<>();
private HashAlgorithm digestAlgo = HashAlgorithm.sha256;
private Date executionTime = new Date();
@@ -96,11 +96,11 @@ public class SignatureConfig {
private SignaturePolicyService signaturePolicyService;
private URIDereferencer uriDereferencer;
private String canonicalizationMethod = CanonicalizationMethod.INCLUSIVE;
-
+
private boolean includeEntireCertificateChain = true;
private boolean includeIssuerSerial;
private boolean includeKeyValue;
-
+
/**
* the time-stamp service used for XAdES-T and XAdES-X.
*/
@@ -123,7 +123,7 @@ public class SignatureConfig {
private String tspRequestPolicy = "1.3.6.1.4.1.13762.3";
private String userAgent = "POI XmlSign Service TSP Client";
private String proxyUrl;
-
+
/**
* the optional revocation data service used for XAdES-C and XAdES-X-L.
* When null
the signature will be limited to XAdES-T only.
@@ -148,16 +148,16 @@ public class SignatureConfig {
* null
value will trigger an automatically generated signature Id.
*/
private String packageSignatureId = "idPackageSignature";
-
+
/**
* Gives back the human-readable description of what the citizen will be
* signing. The default value is "Office OpenXML Document".
*/
private String signatureDescription = "Office OpenXML Document";
-
+
/**
* The process of signing includes the marshalling of xml structures.
- * This also includes the canonicalization. Currently this leads to problems
+ * This also includes the canonicalization. Currently this leads to problems
* with certain namespaces, so this EventListener is used to interfere
* with the marshalling process.
*/
@@ -177,7 +177,7 @@ public class SignatureConfig {
/**
* Inits and checks the config object.
- * If not set previously, complex configuration properties also get
+ * If not set previously, complex configuration properties also get
* created/initialized via this initialization call.
*
* @param onlyValidation if true, only a subset of the properties
@@ -202,7 +202,7 @@ public class SignatureConfig {
namespacePrefixes.put(OO_DIGSIG_NS, "mdssi");
namespacePrefixes.put(XADES_132_NS, "xd");
}
-
+
if (onlyValidation) {
return;
}
@@ -210,15 +210,15 @@ public class SignatureConfig {
if (signatureMarshalListener == null) {
signatureMarshalListener = new SignatureMarshalListener();
}
-
+
if (signatureMarshalListener instanceof SignatureConfigurable) {
((SignatureConfigurable)signatureMarshalListener).setSignatureConfig(this);
}
-
+
if (tspService != null) {
tspService.setSignatureConfig(this);
}
-
+
if (signatureFacets.isEmpty()) {
addSignatureFacet(new OOXMLSignatureFacet());
addSignatureFacet(new KeyInfoSignatureFacet());
@@ -230,14 +230,14 @@ public class SignatureConfig {
sf.setSignatureConfig(this);
}
}
-
+
/**
- * @param signatureFacet the signature facet is appended to facet list
+ * @param signatureFacet the signature facet is appended to facet list
*/
public void addSignatureFacet(SignatureFacet signatureFacet) {
signatureFacets.add(signatureFacet);
}
-
+
/**
* @return the list of facets, may be empty when the config object is not initialized
*/
@@ -265,14 +265,14 @@ public class SignatureConfig {
public void setDigestAlgo(HashAlgorithm digestAlgo) {
this.digestAlgo = digestAlgo;
}
-
+
/**
* @return the opc package to be used by this thread, stored as thread-local
*/
public OPCPackage getOpcPackage() {
return opcPackage.get();
}
-
+
/**
* @param opcPackage the opc package to be handled by this thread, stored as thread-local
*/
@@ -398,14 +398,14 @@ public class SignatureConfig {
public void setSignatureDescription(String signatureDescription) {
this.signatureDescription = signatureDescription;
}
-
+
/**
* @return the default canonicalization method, defaults to INCLUSIVE
*/
public String getCanonicalizationMethod() {
return canonicalizationMethod;
}
-
+
/**
* @param canonicalizationMethod the default canonicalization method
*/
@@ -459,15 +459,15 @@ public class SignatureConfig {
public void setTspUrl(String tspUrl) {
this.tspUrl = tspUrl;
}
-
+
/**
* @return if true, uses timestamp-request/response mimetype,
- * if false, timestamp-query/reply mimetype
+ * if false, timestamp-query/reply mimetype
*/
public boolean isTspOldProtocol() {
return tspOldProtocol;
}
-
+
/**
* @param tspOldProtocol defines the timestamp-protocol mimetype
* @see #isTspOldProtocol
@@ -475,7 +475,7 @@ public class SignatureConfig {
public void setTspOldProtocol(boolean tspOldProtocol) {
this.tspOldProtocol = tspOldProtocol;
}
-
+
/**
* @return the hash algorithm to be used for the timestamp entry.
* Defaults to the hash algorithm of the main entry
@@ -483,7 +483,7 @@ public class SignatureConfig {
public HashAlgorithm getTspDigestAlgo() {
return nvl(tspDigestAlgo,digestAlgo);
}
-
+
/**
* @param tspDigestAlgo the algorithm to be used for the timestamp entry.
* if null
, the hash algorithm of the main entry
@@ -499,7 +499,7 @@ public class SignatureConfig {
public String getProxyUrl() {
return proxyUrl;
}
-
+
/**
* @param proxyUrl the proxy url to be used for all communications.
* Currently this affects the timestamp service
@@ -507,56 +507,56 @@ public class SignatureConfig {
public void setProxyUrl(String proxyUrl) {
this.proxyUrl = proxyUrl;
}
-
+
/**
* @return the timestamp service. Defaults to {@link TSPTimeStampService}
*/
public TimeStampService getTspService() {
return tspService;
}
-
+
/**
* @param tspService the timestamp service
*/
public void setTspService(TimeStampService tspService) {
this.tspService = tspService;
}
-
+
/**
* @return the user id for the timestamp service - currently only basic authorization is supported
*/
public String getTspUser() {
return tspUser;
}
-
+
/**
* @param tspUser the user id for the timestamp service - currently only basic authorization is supported
*/
public void setTspUser(String tspUser) {
this.tspUser = tspUser;
}
-
+
/**
* @return the password for the timestamp service
*/
public String getTspPass() {
return tspPass;
}
-
+
/**
* @param tspPass the password for the timestamp service
*/
public void setTspPass(String tspPass) {
this.tspPass = tspPass;
}
-
+
/**
* @return the validator for the timestamp service (certificate)
*/
public TimeStampServiceValidator getTspValidator() {
return tspValidator;
}
-
+
/**
* @param tspValidator the validator for the timestamp service (certificate)
*/
@@ -586,7 +586,7 @@ public class SignatureConfig {
public HashAlgorithm getXadesDigestAlgo() {
return nvl(xadesDigestAlgo,digestAlgo);
}
-
+
/**
* @param xadesDigestAlgo hash algorithm used for XAdES.
* When null
, defaults to {@link #getDigestAlgo()}
@@ -611,7 +611,7 @@ public class SignatureConfig {
public String getUserAgent() {
return userAgent;
}
-
+
/**
* @param userAgent the user agent used for http communication (e.g. to the TSP)
*/
@@ -626,7 +626,7 @@ public class SignatureConfig {
public String getTspRequestPolicy() {
return tspRequestPolicy;
}
-
+
/**
* @param tspRequestPolicy the asn.1 object id for the tsp request policy.
*/
@@ -636,7 +636,7 @@ public class SignatureConfig {
/**
* @return true, if the whole certificate chain is included in the signature.
- * When false, only the signer cert will be included
+ * When false, only the signer cert will be included
*/
public boolean isIncludeEntireCertificateChain() {
return includeEntireCertificateChain;
@@ -728,7 +728,7 @@ public class SignatureConfig {
* Make sure the DN is encoded using the same order as present
* within the certificate. This is an Office2010 work-around.
* Should be reverted back.
- *
+ *
* XXX: not correct according to RFC 4514.
*
* @return when true, the issuer DN is used instead of the issuer X500 principal
@@ -744,7 +744,7 @@ public class SignatureConfig {
this.xadesIssuerNameNoReverseOrder = xadesIssuerNameNoReverseOrder;
}
-
+
/**
* @return the event listener which is active while xml structure for
* the signature is created.
@@ -813,8 +813,8 @@ public class SignatureConfig {
/**
* Converts the digest algorithm - currently only sha* and ripemd160 is supported.
- * MS Office only supports sha1, sha256, sha384, sha512.
- *
+ * MS Office only supports sha1, sha256, sha384, sha512.
+ *
* @param digestAlgo the digest algorithm
* @return the uri for the given digest
*/
@@ -835,7 +835,7 @@ public class SignatureConfig {
* Converts the digest algorithm ur - currently only sha* and ripemd160 is supported.
* MS Office only supports sha1, sha256, sha384, sha512.
*
- * @param digestAlgo the digest algorithm uri
+ * @param digestMethodUri the digest algorithm uri
* @return the hash algorithm for the given digest
*/
private static HashAlgorithm getDigestMethodAlgo(String digestMethodUri) {
@@ -895,7 +895,7 @@ public class SignatureConfig {
public void setSignatureFactory(XMLSignatureFactory signatureFactory) {
this.signatureFactory.set(signatureFactory);
}
-
+
/**
* @return the xml signature factory (thread-local)
*/
@@ -914,7 +914,7 @@ public class SignatureConfig {
public void setKeyInfoFactory(KeyInfoFactory keyInfoFactory) {
this.keyInfoFactory.set(keyInfoFactory);
}
-
+
/**
* @return the key factory (thread-local)
*/
@@ -934,10 +934,10 @@ public class SignatureConfig {
* the Santuario xmlsec provider
* the JDK xmlsec provider
*
- *
+ *
* For signing the classes are linked against the Santuario xmlsec, so this might
* only work for validation (not tested).
- *
+ *
* @return the xml dsig provider
*/
public Provider getProvider() {
@@ -948,7 +948,7 @@ public class SignatureConfig {
// Santuario xmlsec
"org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI",
// JDK xmlsec
- "org.jcp.xml.dsig.internal.dom.XMLDSigRI"
+ "org.jcp.xml.dsig.internal.dom.XMLDSigRI"
};
for (String pn : dsigProviderNames) {
if (pn == null) {
@@ -966,7 +966,7 @@ public class SignatureConfig {
if (prov == null) {
throw new RuntimeException("JRE doesn't support default xml signature provider - set jsr105Provider system property!");
}
-
+
return prov;
}
diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFShape.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFShape.java
index c2b22de4f2..0427817fdd 100644
--- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFShape.java
+++ b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFShape.java
@@ -116,13 +116,15 @@ public class XDGFShape extends XDGFSheet {
_parentPage = parentPage;
TextType text = shapeSheet.getText();
- if (text != null)
+ if (text != null) {
_text = new XDGFText(text, this);
+ }
if (shapeSheet.isSetShapes()) {
_shapes = new ArrayList<>();
- for (ShapeSheetType shape : shapeSheet.getShapes().getShapeArray())
+ for (ShapeSheetType shape : shapeSheet.getShapes().getShapeArray()) {
_shapes.add(new XDGFShape(this, shape, parentPage, document));
+ }
}
readProperties();
@@ -130,10 +132,11 @@ public class XDGFShape extends XDGFSheet {
@Override
public String toString() {
- if (_parentPage instanceof XDGFMasterContents)
+ if (_parentPage instanceof XDGFMasterContents) {
return _parentPage + ": ";
- else
+ } else {
return "";
+ }
}
protected void readProperties() {
@@ -181,9 +184,10 @@ public class XDGFShape extends XDGFSheet {
if (obj.isSetMaster()) {
_master = pageContents.getMasterById(obj.getMaster());
- if (_master == null)
+ if (_master == null) {
throw XDGFException.error("refers to non-existant master "
+ obj.getMaster(), this);
+ }
/*
* If a master has one top-level shape, a shape that inherits from
@@ -209,11 +213,12 @@ public class XDGFShape extends XDGFSheet {
}
} else if (obj.isSetMasterShape()) {
- _masterShape = master.getShapeById(obj.getMasterShape());
- if (_masterShape == null)
+ _masterShape = (master == null) ? null : master.getShapeById(obj.getMasterShape());
+ if (_masterShape == null) {
throw XDGFException.error(
"refers to non-existant master shape "
+ obj.getMasterShape(), this);
+ }
}
@@ -229,21 +234,24 @@ public class XDGFShape extends XDGFSheet {
protected void setupSectionMasters() {
- if (_masterShape == null)
+ if (_masterShape == null) {
return;
+ }
try {
for (Entry section : _sections.entrySet()) {
XDGFSection master = _masterShape.getSection(section.getKey());
- if (master != null)
+ if (master != null) {
section.getValue().setupMaster(master);
+ }
}
for (Entry section : _geometry.entrySet()) {
GeometrySection master = _masterShape.getGeometryByIdx(section
.getKey());
- if (master != null)
+ if (master != null) {
section.getValue().setupMaster(master);
+ }
}
} catch (POIXMLException e) {
throw XDGFException.wrap(this.toString(), e);
@@ -266,8 +274,9 @@ public class XDGFShape extends XDGFSheet {
public String getTextAsString() {
XDGFText text = getText();
- if (text == null)
+ if (text == null) {
return "";
+ }
return text.getTextContent();
}
@@ -294,7 +303,7 @@ public class XDGFShape extends XDGFSheet {
}
/**
- * Only available if this shape is a shape group, may be null
+ * Only available if this shape is a shape group, may be null
*/
// -> May be null
public List getShapes() {
@@ -304,28 +313,32 @@ public class XDGFShape extends XDGFSheet {
// unique to this shape on the page?
public String getName() {
String name = getXmlObject().getName();
- if (name == null)
+ if (name == null) {
return "";
+ }
return name;
}
// unique to this shape on the page?
public String getShapeType() {
String type = getXmlObject().getType();
- if (type == null)
+ if (type == null) {
return "";
+ }
return type;
}
// name of the symbol that this was derived from
public String getSymbolName() {
- if (_master == null)
+ if (_master == null) {
return "";
+ }
String name = _master.getName();
- if (name == null)
+ if (name == null) {
return "";
+ }
return name;
}
@@ -345,8 +358,9 @@ public class XDGFShape extends XDGFSheet {
XDGFShape top = null;
if (_parent != null) {
top = _parent.getTopmostParentShape();
- if (top == null)
+ if (top == null) {
top = _parent;
+ }
}
return top;
@@ -381,190 +395,223 @@ public class XDGFShape extends XDGFSheet {
}
public XDGFText getText() {
- if (_text == null && _masterShape != null)
+ if (_text == null && _masterShape != null) {
return _masterShape.getText();
+ }
return _text;
}
public Double getPinX() {
- if (_pinX == null && _masterShape != null)
+ if (_pinX == null && _masterShape != null) {
return _masterShape.getPinX();
+ }
- if (_pinX == null)
+ if (_pinX == null) {
throw XDGFException.error("PinX not set!", this);
+ }
return _pinX;
}
public Double getPinY() {
- if (_pinY == null && _masterShape != null)
+ if (_pinY == null && _masterShape != null) {
return _masterShape.getPinY();
+ }
- if (_pinY == null)
+ if (_pinY == null) {
throw XDGFException.error("PinY not specified!", this);
+ }
return _pinY;
}
public Double getWidth() {
- if (_width == null && _masterShape != null)
+ if (_width == null && _masterShape != null) {
return _masterShape.getWidth();
+ }
- if (_width == null)
+ if (_width == null) {
throw XDGFException.error("Width not specified!", this);
+ }
return _width;
}
public Double getHeight() {
- if (_height == null && _masterShape != null)
+ if (_height == null && _masterShape != null) {
return _masterShape.getHeight();
+ }
- if (_height == null)
+ if (_height == null) {
throw XDGFException.error("Height not specified!", this);
+ }
return _height;
}
public Double getLocPinX() {
- if (_locPinX == null && _masterShape != null)
+ if (_locPinX == null && _masterShape != null) {
return _masterShape.getLocPinX();
+ }
- if (_locPinX == null)
+ if (_locPinX == null) {
throw XDGFException.error("LocPinX not specified!", this);
+ }
return _locPinX;
}
public Double getLocPinY() {
- if (_locPinY == null && _masterShape != null)
+ if (_locPinY == null && _masterShape != null) {
return _masterShape.getLocPinY();
+ }
- if (_locPinY == null)
+ if (_locPinY == null) {
throw XDGFException.error("LocPinY not specified!", this);
+ }
return _locPinY;
}
public Double getBeginX() {
- if (_beginX == null && _masterShape != null)
+ if (_beginX == null && _masterShape != null) {
return _masterShape.getBeginX();
+ }
return _beginX;
}
public Double getBeginY() {
- if (_beginY == null && _masterShape != null)
+ if (_beginY == null && _masterShape != null) {
return _masterShape.getBeginY();
+ }
return _beginY;
}
public Double getEndX() {
- if (_endX == null && _masterShape != null)
+ if (_endX == null && _masterShape != null) {
return _masterShape.getEndX();
+ }
return _endX;
}
public Double getEndY() {
- if (_endY == null && _masterShape != null)
+ if (_endY == null && _masterShape != null) {
return _masterShape.getEndY();
+ }
return _endY;
}
public Double getAngle() {
- if (_angle == null && _masterShape != null)
+ if (_angle == null && _masterShape != null) {
return _masterShape.getAngle();
+ }
return _angle;
}
public Boolean getFlipX() {
- if (_flipX == null && _masterShape != null)
+ if (_flipX == null && _masterShape != null) {
return _masterShape.getFlipX();
+ }
return _flipX;
}
public Boolean getFlipY() {
- if (_flipY == null && _masterShape != null)
+ if (_flipY == null && _masterShape != null) {
return _masterShape.getFlipY();
+ }
return _flipY;
}
public Double getTxtPinX() {
if (_txtPinX == null && _masterShape != null
- && _masterShape._txtPinX != null)
+ && _masterShape._txtPinX != null) {
return _masterShape._txtPinX;
+ }
- if (_txtPinX == null)
+ if (_txtPinX == null) {
return getWidth() * 0.5;
+ }
return _txtPinX;
}
public Double getTxtPinY() {
if (_txtLocPinY == null && _masterShape != null
- && _masterShape._txtLocPinY != null)
+ && _masterShape._txtLocPinY != null) {
return _masterShape._txtLocPinY;
+ }
- if (_txtPinY == null)
+ if (_txtPinY == null) {
return getHeight() * 0.5;
+ }
return _txtPinY;
}
public Double getTxtLocPinX() {
if (_txtLocPinX == null && _masterShape != null
- && _masterShape._txtLocPinX != null)
+ && _masterShape._txtLocPinX != null) {
return _masterShape._txtLocPinX;
+ }
- if (_txtLocPinX == null)
+ if (_txtLocPinX == null) {
return getTxtWidth() * 0.5;
+ }
return _txtLocPinX;
}
public Double getTxtLocPinY() {
if (_txtLocPinY == null && _masterShape != null
- && _masterShape._txtLocPinY != null)
+ && _masterShape._txtLocPinY != null) {
return _masterShape._txtLocPinY;
+ }
- if (_txtLocPinY == null)
+ if (_txtLocPinY == null) {
return getTxtHeight() * 0.5;
+ }
return _txtLocPinY;
}
public Double getTxtAngle() {
- if (_txtAngle == null && _masterShape != null)
+ if (_txtAngle == null && _masterShape != null) {
return _masterShape.getTxtAngle();
+ }
return _txtAngle;
}
public Double getTxtWidth() {
if (_txtWidth == null && _masterShape != null
- && _masterShape._txtWidth != null)
+ && _masterShape._txtWidth != null) {
return _masterShape._txtWidth;
+ }
- if (_txtWidth == null)
+ if (_txtWidth == null) {
return getWidth();
+ }
return _txtWidth;
}
public Double getTxtHeight() {
if (_txtHeight == null && _masterShape != null
- && _masterShape._txtHeight != null)
+ && _masterShape._txtHeight != null) {
return _masterShape._txtHeight;
+ }
- if (_txtHeight == null)
+ if (_txtHeight == null) {
return getHeight();
+ }
return _txtHeight;
}
@@ -573,8 +620,9 @@ public class XDGFShape extends XDGFSheet {
public Integer getLineCap() {
Integer lineCap = super.getLineCap();
- if (lineCap != null)
+ if (lineCap != null) {
return lineCap;
+ }
// get from master
if (_masterShape != null) {
@@ -589,8 +637,9 @@ public class XDGFShape extends XDGFSheet {
public Color getLineColor() {
Color lineColor = super.getLineColor();
- if (lineColor != null)
+ if (lineColor != null) {
return lineColor;
+ }
// get from master
if (_masterShape != null) {
@@ -605,8 +654,9 @@ public class XDGFShape extends XDGFSheet {
public Integer getLinePattern() {
Integer linePattern = super.getLinePattern();
- if (linePattern != null)
+ if (linePattern != null) {
return linePattern;
+ }
// get from master
if (_masterShape != null) {
@@ -621,8 +671,9 @@ public class XDGFShape extends XDGFSheet {
public Double getLineWeight() {
Double lineWeight = super.getLineWeight();
- if (lineWeight != null)
+ if (lineWeight != null) {
return lineWeight;
+ }
// get from master
if (_masterShape != null) {
@@ -637,8 +688,9 @@ public class XDGFShape extends XDGFSheet {
public Color getFontColor() {
Color fontColor = super.getFontColor();
- if (fontColor != null)
+ if (fontColor != null) {
return fontColor;
+ }
// get from master
if (_masterShape != null) {
@@ -653,8 +705,9 @@ public class XDGFShape extends XDGFSheet {
public Double getFontSize() {
Double fontSize = super.getFontSize();
- if (fontSize != null)
+ if (fontSize != null) {
return fontSize;
+ }
// get from master
if (_masterShape != null) {
@@ -791,11 +844,11 @@ public class XDGFShape extends XDGFSheet {
public Rectangle2D.Double getBounds() {
return new Rectangle2D.Double(0, 0, getWidth(), getHeight());
}
-
+
/**
* @return returns bounds as a path in local coordinates, which is
* userful if you need to transform to global coordinates
- *
+ *
* Warning: Don't use this for 1d objects, and will fail for
* infinite line objects
*/
@@ -819,8 +872,9 @@ public class XDGFShape extends XDGFSheet {
*/
public Path2D.Double getPath() {
for (GeometrySection geoSection : getGeometrySections()) {
- if (geoSection.getNoShow())
+ if (geoSection.getNoShow()) {
continue;
+ }
return geoSection.getPath(this);
}
@@ -833,8 +887,9 @@ public class XDGFShape extends XDGFSheet {
*/
public boolean hasGeometry() {
for (GeometrySection geoSection : getGeometrySections()) {
- if (!geoSection.getNoShow())
+ if (!geoSection.getNoShow()) {
return true;
+ }
}
return false;
}
@@ -889,8 +944,9 @@ public class XDGFShape extends XDGFSheet {
tr.concatenate(getParentTransform());
try {
- if (visitor.accept(this))
+ if (visitor.accept(this)) {
visitor.visit(this, tr, level);
+ }
if (_shapes != null) {
for (XDGFShape shape : _shapes) {
@@ -914,8 +970,9 @@ public class XDGFShape extends XDGFSheet {
public void visitShapes(ShapeVisitor visitor, int level) {
try {
- if (visitor.accept(this))
+ if (visitor.accept(this)) {
visitor.visit(this, null, level);
+ }
if (_shapes != null) {
for (XDGFShape shape : _shapes) {
diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFText.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFText.java
index f3b24f9054..c823bb343d 100644
--- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFText.java
+++ b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFText.java
@@ -52,7 +52,7 @@ public class XDGFText {
// is a mixed type)
return ((TextTypeImpl) _text).getStringValue();
}
-
+
/**
* These are in the shape coordinate system
*
@@ -82,8 +82,8 @@ public class XDGFText {
public Path2D.Double getBoundsAsPath() {
Rectangle2D.Double rect = getTextBounds();
- Double w = rect.getWidth();
- Double h = rect.getHeight();
+ double w = rect.getWidth();
+ double h = rect.getHeight();
Path2D.Double bounds = new Path2D.Double();
bounds.moveTo(0, 0);
@@ -94,7 +94,7 @@ public class XDGFText {
return bounds;
}
-
+
/**
* @return Center of text in local coordinates
*/
@@ -110,8 +110,9 @@ public class XDGFText {
public void draw(Graphics2D graphics) {
String textContent = getTextContent();
- if (textContent.length() == 0)
+ if (textContent.length() == 0) {
return;
+ }
Rectangle2D.Double bounds = getTextBounds();
@@ -140,22 +141,25 @@ public class XDGFText {
}
Double txtAngle = _parent.getTxtAngle();
- if (txtAngle != null && Math.abs(txtAngle) > 0.01)
+ if (txtAngle != null && Math.abs(txtAngle) > 0.01) {
graphics.rotate(txtAngle);
+ }
float nextY = 0;
for (String line : lines) {
- if (line.length() == 0)
+ if (line.length() == 0) {
continue;
+ }
TextLayout layout = new TextLayout(line, font, frc);
- if (layout.isLeftToRight())
+ if (layout.isLeftToRight()) {
layout.draw(graphics, 0, nextY);
- else
+ } else {
layout.draw(graphics,
(float) (bounds.width - layout.getAdvance()), nextY);
+ }
nextY += layout.getAscent() + layout.getDescent()
+ layout.getLeading();
diff --git a/src/ooxml/java/org/apache/poi/xdgf/util/HierarchyPrinter.java b/src/ooxml/java/org/apache/poi/xdgf/util/HierarchyPrinter.java
index 92fbcb0d2c..eb37159ba4 100644
--- a/src/ooxml/java/org/apache/poi/xdgf/util/HierarchyPrinter.java
+++ b/src/ooxml/java/org/apache/poi/xdgf/util/HierarchyPrinter.java
@@ -22,6 +22,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
+import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
@@ -38,17 +39,17 @@ import org.apache.poi.xdgf.usermodel.shape.ShapeVisitor;
public class HierarchyPrinter {
public static void printHierarchy(XDGFPage page, File outDir)
- throws FileNotFoundException, UnsupportedEncodingException {
+ throws FileNotFoundException, UnsupportedEncodingException, IOException {
File pageFile = new File(outDir, "page" + page.getPageNumber() + "-"
+ Util.sanitizeFilename(page.getName()) + ".txt");
- OutputStream os = new FileOutputStream(pageFile);
- PrintStream pos = new PrintStream(os, false, "utf-8");
-
- printHierarchy(page, pos);
-
- pos.close();
+ try (
+ OutputStream os = new FileOutputStream(pageFile);
+ PrintStream pos = new PrintStream(os, false, "utf-8")
+ ) {
+ printHierarchy(page, pos);
+ }
}
public static void printHierarchy(XDGFPage page, final PrintStream os) {
@@ -71,7 +72,7 @@ public class HierarchyPrinter {
}
public static void printHierarchy(XmlVisioDocument document,
- String outDirname) throws FileNotFoundException, UnsupportedEncodingException {
+ String outDirname) throws FileNotFoundException, UnsupportedEncodingException, IOException {
File outDir = new File(outDirname);
@@ -89,8 +90,9 @@ public class HierarchyPrinter {
String inFilename = args[0];
String outDir = args[1];
- XmlVisioDocument doc = new XmlVisioDocument(new FileInputStream(
- inFilename));
- printHierarchy(doc, outDir);
+ try (FileInputStream is = new FileInputStream(inFilename)) {
+ XmlVisioDocument doc = new XmlVisioDocument(is);
+ printHierarchy(doc, outDir);
+ }
}
}
diff --git a/src/ooxml/java/org/apache/poi/xdgf/util/VsdxToPng.java b/src/ooxml/java/org/apache/poi/xdgf/util/VsdxToPng.java
index 7706ca19e3..815eaee826 100644
--- a/src/ooxml/java/org/apache/poi/xdgf/util/VsdxToPng.java
+++ b/src/ooxml/java/org/apache/poi/xdgf/util/VsdxToPng.java
@@ -21,7 +21,10 @@ import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
-import java.io.*;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
import javax.imageio.ImageIO;
@@ -33,7 +36,7 @@ import org.apache.poi.xdgf.usermodel.shape.ShapeRenderer;
/**
* Converts a Visio diagram to a PNG file.
- *
+ *
* As more elements and styles are added/supported the output will get
* better, but it's very rough right now.
*/
@@ -91,11 +94,8 @@ public class VsdxToPng {
graphics.dispose();
- OutputStream out = new FileOutputStream(outFile);
- try {
+ try (FileOutputStream out = new FileOutputStream(outFile)) {
ImageIO.write(img, "png", out);
- } finally {
- out.close();
}
}
@@ -127,8 +127,9 @@ public class VsdxToPng {
renderer = new ShapeDebuggerRenderer();
}
- XmlVisioDocument doc = new XmlVisioDocument(new FileInputStream(
- inFilename));
- renderToPng(doc, pngDir, 2000 / 11.0, renderer);
+ try (FileInputStream is = new FileInputStream(inFilename)) {
+ XmlVisioDocument doc = new XmlVisioDocument(is);
+ renderToPng(doc, pngDir, 2000 / 11.0, renderer);
+ }
}
}
diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XMLSlideShow.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XMLSlideShow.java
index 4019030761..687ddc5f5b 100644
--- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XMLSlideShow.java
+++ b/src/ooxml/java/org/apache/poi/xslf/usermodel/XMLSlideShow.java
@@ -36,6 +36,7 @@ import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ooxml.POIXMLException;
import org.apache.poi.ooxml.extractor.POIXMLPropertiesTextExtractor;
+import org.apache.poi.ooxml.util.PackageHelper;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
@@ -50,7 +51,6 @@ import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
-import org.apache.poi.ooxml.util.PackageHelper;
import org.apache.poi.util.Units;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
@@ -362,7 +362,7 @@ public class XMLSlideShow extends POIXMLDocument
CTNotesMasterIdListEntry notesMasterId = notesMasterIdList.addNewNotesMasterId();
notesMasterId.setId(rp.getRelationship().getId());
- Integer themeIndex = 1;
+ int themeIndex = 1;
// TODO: check if that list can be replaced by idx = Math.max(idx,themeIdx)
List themeIndexList = new ArrayList<>();
for (POIXMLDocumentPart p : getRelations()) {
@@ -626,7 +626,7 @@ public class XMLSlideShow extends POIXMLDocument
// TODO: implement!
throw new UnsupportedOperationException();
}
-
+
@Override
public POIXMLPropertiesTextExtractor getMetadataTextExtractor() {
return new POIXMLPropertiesTextExtractor(this);
diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFColor.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFColor.java
index d7aed091b1..50b82df3b0 100644
--- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFColor.java
+++ b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFColor.java
@@ -48,7 +48,7 @@ import org.w3c.dom.Node;
@Internal
public class XSLFColor {
private final static POILogger LOGGER = POILogFactory.getLogger(XSLFColor.class);
-
+
private XmlObject _xmlObject;
private Color _color;
private CTSchemeColor _phClr;
@@ -128,7 +128,7 @@ public class XSLFColor {
}
};
}
-
+
private Color toColor(XmlObject obj, XSLFTheme theme) {
Color color = null;
for (XmlObject ch : obj.selectPath("*")) {
@@ -207,19 +207,19 @@ public class XSLFColor {
if (fill.isSetScrgbClr()) {
fill.unsetScrgbClr();
}
-
+
if (fill.isSetHslClr()) {
fill.unsetHslClr();
}
-
+
if (fill.isSetPrstClr()) {
fill.unsetPrstClr();
}
-
+
if (fill.isSetSchemeClr()) {
fill.unsetSchemeClr();
}
-
+
if (fill.isSetSysClr()) {
fill.unsetSysClr();
}
@@ -227,12 +227,12 @@ public class XSLFColor {
float[] rgbaf = color.getRGBComponents(null);
boolean addAlpha = (rgbaf.length == 4 && rgbaf[3] < 1f);
CTPositiveFixedPercentage alphaPct;
-
+
// see office open xml part 4 - 5.1.2.2.30 and 5.1.2.2.32
if (isInt(rgbaf[0]) && isInt(rgbaf[1]) && isInt(rgbaf[2])) {
// sRGB has a gamma of 2.2
CTSRgbColor rgb = fill.addNewSrgbClr();
-
+
byte rgbBytes[] = { (byte)color.getRed(), (byte)color.getGreen(), (byte)color.getBlue() };
rgb.setVal(rgbBytes);
alphaPct = (addAlpha) ? rgb.addNewAlpha() : null;
@@ -249,14 +249,14 @@ public class XSLFColor {
alphaPct.setVal((int)(100000 * rgbaf[3]));
}
}
-
+
/**
* @return true, if this is an integer color value
*/
private static boolean isInt(float f) {
- return Math.abs((f*255f) - Math.rint(f*255f)) < 0.00001f;
+ return Math.abs((f*255d) - Math.rint(f*255d)) < 0.00001;
}
-
+
private int getRawValue(String elem) {
String query = "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' $this//a:" + elem;
@@ -281,9 +281,9 @@ public class XSLFColor {
}
}
- return -1;
+ return -1;
}
-
+
/**
* Read a perecentage value from the supplied xml bean.
* Example:
@@ -305,7 +305,7 @@ public class XSLFColor {
* or -1 if the value is not set
*/
int getAlpha(){
- return getPercentageValue("alpha");
+ return getPercentageValue("alpha");
}
/**
@@ -413,7 +413,7 @@ public class XSLFColor {
/**
* specifies the input color with the specific red component, but with the blue and green color
* components unchanged
- *
+ *
* @return the value of the red component specified as a
* percentage with 0% indicating minimal blue and 100% indicating maximum
* or -1 if the value is not set
@@ -479,7 +479,7 @@ public class XSLFColor {
/**
* specifies a darker version of its input color.
* A 10% shade is 10% of the input color combined with 90% black.
- *
+ *
* @return the value of the shade specified as a
* percentage with 0% indicating minimal shade and 100% indicating maximum
* or -1 if the value is not set
diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFNotes.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFNotes.java
index 64b92a9bbf..72d19e7aee 100644
--- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFNotes.java
+++ b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFNotes.java
@@ -49,9 +49,7 @@ implements Notes {
*
* @param part the package part holding the notes data,
* the content type must be application/vnd.openxmlformats-officedocument.notes+xml
- * @param rel the package relationship holding this notes,
- * the relationship type must be http://schemas.openxmlformats.org/officeDocument/2006/relationships/notes
- *
+ *
* @since POI 3.14-Beta1
*/
XSLFNotes(PackagePart part) throws IOException, XmlException {
@@ -77,7 +75,7 @@ implements Notes {
@Override
protected String getRootElementName(){
- return "notes";
+ return "notes";
}
@Override
diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShape.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShape.java
index 4d162027e8..aded851db5 100644
--- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShape.java
+++ b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShape.java
@@ -70,7 +70,7 @@ import org.openxmlformats.schemas.presentationml.x2006.main.STPlaceholderType;
@Beta
public abstract class XSLFShape implements Shape {
static final String PML_NS = "http://schemas.openxmlformats.org/presentationml/2006/main";
-
+
private final XmlObject _shape;
private final XSLFSheet _sheet;
private XSLFShapeContainer _parent;
@@ -82,7 +82,7 @@ public abstract class XSLFShape implements Shape {
_shape = shape;
_sheet = sheet;
}
-
+
/**
* @return the xml bean holding this shape's data
*/
@@ -91,11 +91,12 @@ public abstract class XSLFShape implements Shape {
// the (not existing) xmlbeans hierarchy and subclasses shouldn't narrow it's return value
return _shape;
}
-
+
+ @Override
public XSLFSheet getSheet() {
return _sheet;
}
-
+
@Override
public String getShapeName(){
return getCNvPr().getName();
@@ -124,22 +125,24 @@ public abstract class XSLFShape implements Shape {
PlaceableShape,?> ps = (PlaceableShape,?>)this;
ps.setAnchor(sh.getAnchor());
}
-
-
+
+
}
-
+
public void setParent(XSLFShapeContainer parent) {
this._parent = parent;
}
-
+
+ @Override
public XSLFShapeContainer getParent() {
return this._parent;
}
-
+
protected PaintStyle getFillPaint() {
final XSLFTheme theme = getSheet().getTheme();
final boolean hasPlaceholder = getPlaceholder() != null;
PropertyFetcher fetcher = new PropertyFetcher() {
+ @Override
public boolean fetch(XSLFShape shape) {
XSLFFillProperties fp = XSLFPropertiesDelegate.getFillDelegate(shape.getShapeProperties());
if (fp == null) {
@@ -150,7 +153,7 @@ public abstract class XSLFShape implements Shape {
setValue(null);
return true;
}
-
+
PackagePart pp = shape.getSheet().getPackagePart();
PaintStyle paint = selectPaint(fp, null, pp, theme, hasPlaceholder);
if (paint != null) {
@@ -167,8 +170,8 @@ public abstract class XSLFShape implements Shape {
setValue(paint);
return true;
}
-
-
+
+
return false;
}
};
@@ -181,16 +184,16 @@ public abstract class XSLFShape implements Shape {
protected CTBackgroundProperties getBgPr() {
return getChild(CTBackgroundProperties.class, PML_NS, "bgPr");
}
-
+
@SuppressWarnings("unused")
protected CTStyleMatrixReference getBgRef() {
return getChild(CTStyleMatrixReference.class, PML_NS, "bgRef");
}
-
+
protected CTGroupShapeProperties getGrpSpPr() {
return getChild(CTGroupShapeProperties.class, PML_NS, "grpSpPr");
}
-
+
protected CTNonVisualDrawingProps getCNvPr() {
if (_nvPr == null) {
String xquery = "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' .//*/p:cNvPr";
@@ -239,7 +242,7 @@ public abstract class XSLFShape implements Shape {
public Placeholder getPlaceholder() {
return getPlaceholderDetails().getPlaceholder();
}
-
+
/**
* @see PlaceholderDetails#setPlaceholder(Placeholder)
*/
@@ -268,7 +271,9 @@ public abstract class XSLFShape implements Shape {
@SuppressWarnings({"unchecked", "WeakerAccess"})
protected T selectProperty(Class resultClass, String xquery) {
XmlObject[] rs = getXmlObject().selectPath(xquery);
- if (rs.length == 0) return null;
+ if (rs.length == 0) {
+ return null;
+ }
return (resultClass.isInstance(rs[0])) ? (T)rs[0] : null;
}
@@ -281,7 +286,7 @@ public abstract class XSLFShape implements Shape {
* slideLayout
* slideMaster
*
- *
+ *
* Currently themes and their defaults aren't correctly handled
*
* @param visitor the object that collects the desired property
@@ -299,7 +304,7 @@ public abstract class XSLFShape implements Shape {
return false;
}
MasterSheet sm = getSheet().getMasterSheet();
-
+
// try slide layout
if (sm instanceof XSLFSlideLayout) {
XSLFSlideLayout slideLayout = (XSLFSlideLayout)sm;
@@ -309,7 +314,7 @@ public abstract class XSLFShape implements Shape {
}
sm = slideLayout.getMasterSheet();
}
-
+
// try slide master
if (sm instanceof XSLFSlideMaster) {
XSLFSlideMaster master = (XSLFSlideMaster)sm;
@@ -317,15 +322,15 @@ public abstract class XSLFShape implements Shape {
XSLFSimpleShape masterShape = master.getPlaceholderByType(textType);
return masterShape != null && visitor.fetch(masterShape);
}
-
+
return false;
}
-
+
private static int getPlaceholderType(CTPlaceholder ph) {
if ( !ph.isSetType()) {
return STPlaceholderType.INT_BODY;
}
-
+
switch (ph.getType().intValue()) {
case STPlaceholderType.INT_TITLE:
case STPlaceholderType.INT_CTR_TITLE:
@@ -397,7 +402,8 @@ public abstract class XSLFShape implements Shape {
throw new RuntimeException(e);
}
}
-
+
+ @Override
public InputStream getImageData() {
try {
return getPart().getInputStream();
@@ -406,17 +412,19 @@ public abstract class XSLFShape implements Shape {
}
}
+ @Override
public String getContentType() {
/* TOOD: map content-type */
return getPart().getContentType();
}
+ @Override
public int getAlpha() {
return (blip.sizeOfAlphaModFixArray() > 0)
? blip.getAlphaModFixArray(0).getAmt()
: 100000;
}
- };
+ };
}
@SuppressWarnings("WeakerAccess")
@@ -426,14 +434,14 @@ public abstract class XSLFShape implements Shape {
final CTGradientStop[] gs = gradFill.getGsLst().getGsArray();
Arrays.sort(gs, (o1, o2) -> {
- Integer pos1 = o1.getPos();
- Integer pos2 = o2.getPos();
- return pos1.compareTo(pos2);
+ int pos1 = o1.getPos();
+ int pos2 = o2.getPos();
+ return Integer.compare(pos1, pos2);
});
final ColorStyle cs[] = new ColorStyle[gs.length];
final float fractions[] = new float[gs.length];
-
+
int i=0;
for (CTGradientStop cgs : gs) {
CTSchemeColor phClrCgs = phClr;
@@ -444,32 +452,37 @@ public abstract class XSLFShape implements Shape {
fractions[i] = cgs.getPos() / 100000.f;
i++;
}
-
+
return new GradientPaint() {
+ @Override
public double getGradientAngle() {
return (gradFill.isSetLin())
? gradFill.getLin().getAng() / 60000.d
: 0;
}
+ @Override
public ColorStyle[] getGradientColors() {
return cs;
}
+ @Override
public float[] getGradientFractions() {
return fractions;
}
+ @Override
public boolean isRotatedWithShape() {
return gradFill.getRotWithShape();
}
+ @Override
public GradientType getGradientType() {
if (gradFill.isSetLin()) {
return GradientType.linear;
}
-
+
if (gradFill.isSetPath()) {
/* TODO: handle rect path */
STPathShadeType.Enum ps = gradFill.getPath().getPath();
@@ -479,16 +492,18 @@ public abstract class XSLFShape implements Shape {
return GradientType.shape;
}
}
-
+
return GradientType.linear;
}
- };
+ };
}
-
+
@SuppressWarnings("WeakerAccess")
protected static PaintStyle selectPaint(CTStyleMatrixReference fillRef, final XSLFTheme theme, boolean isLineStyle, boolean hasPlaceholder) {
- if (fillRef == null) return null;
-
+ if (fillRef == null) {
+ return null;
+ }
+
// The idx attribute refers to the index of a fill style or
// background fill style within the presentation's style matrix, defined by the fmtScheme element.
// value of 0 or 1000 indicates no background,
@@ -513,7 +528,7 @@ public abstract class XSLFShape implements Shape {
fp = XSLFPropertiesDelegate.getFillDelegate(cur.getObject());
}
cur.dispose();
-
+
CTSchemeColor phClr = fillRef.getSchemeClr();
PaintStyle res = selectPaint(fp, phClr, theme.getPackagePart(), theme, hasPlaceholder);
// check for empty placeholder value
@@ -524,12 +539,12 @@ public abstract class XSLFShape implements Shape {
XSLFColor col = new XSLFColor(fillRef, theme, phClr);
return DrawPaint.createSolidPaint(col.getColorStyle());
}
-
+
@Override
public void draw(Graphics2D graphics, Rectangle2D bounds) {
DrawFactory.getInstance(graphics).drawShape(graphics, this, bounds);
}
-
+
/**
* Return the shape specific (visual) properties
*
diff --git a/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java b/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java
index 79327bce4f..b3288d46f3 100644
--- a/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java
+++ b/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java
@@ -74,13 +74,13 @@ public class PPTX2PNG {
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("-")) {
if ("-scale".equals(args[i])) {
- scale = Float.parseFloat(args[++i]);
+ scale = Float.parseFloat(args[++i]); // lgtm[java/index-out-of-bounds]
} else if ("-slide".equals(args[i])) {
- slidenumStr = args[++i];
+ slidenumStr = args[++i]; // lgtm[java/index-out-of-bounds]
} else if ("-format".equals(args[i])) {
- format = args[++i];
+ format = args[++i]; // lgtm[java/index-out-of-bounds]
} else if ("-outdir".equals(args[i])) {
- outdir = new File(args[++i]);
+ outdir = new File(args[++i]); // lgtm[java/index-out-of-bounds]
} else if ("-quiet".equals(args[i])) {
quiet = true;
}
@@ -98,11 +98,11 @@ public class PPTX2PNG {
usage("Invalid format given");
return;
}
-
+
if (outdir == null) {
outdir = file.getParentFile();
}
-
+
if (!"null".equals(format) && (outdir == null || !outdir.exists() || !outdir.isDirectory())) {
usage("Output directory doesn't exist");
return;
@@ -112,7 +112,7 @@ public class PPTX2PNG {
usage("Invalid scale given");
return;
}
-
+
if (!quiet) {
System.out.println("Processing " + file);
}
@@ -169,7 +169,7 @@ public class PPTX2PNG {
System.out.println("Done");
}
}
-
+
private static Set slideIndexes(final int slideCount, String range) {
Set slideIdx = new TreeSet<>();
if ("-1".equals(range)) {
diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBUtils.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBUtils.java
index b2176d2d5b..6f1dd70bd3 100644
--- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBUtils.java
+++ b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBUtils.java
@@ -51,7 +51,7 @@ public class XSSFBUtils {
int numBytes = 2*(int)numChars;
offset += 4;
if (offset+numBytes > data.length) {
- throw new XSSFBParseException("trying to read beyond data length:" +
+ throw new XSSFBParseException("trying to read beyond data length: " +
"offset="+offset+", numBytes="+numBytes+", data.length="+data.length);
}
sb.append(new String(data, offset, numBytes, StandardCharsets.UTF_16LE));
diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFRow.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFRow.java
index 9884ce0935..9f0379493b 100644
--- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFRow.java
+++ b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFRow.java
@@ -39,22 +39,22 @@ import org.apache.poi.util.NotImplemented;
public class SXSSFRow implements Row, Comparable
{
private static final Boolean UNDEFINED = null;
-
+
private final SXSSFSheet _sheet; // parent sheet
private final SortedMap _cells = new TreeMap<>();
private short _style = -1; // index of cell style in style table
private short _height = -1; // row height in twips (1/20 point)
private boolean _zHeight; // row zero-height (this is somehow different than being hidden)
private int _outlineLevel; // Outlining level of the row, when outlining is on
- // use Boolean to have a tri-state for on/off/undefined
+ // use Boolean to have a tri-state for on/off/undefined
private Boolean _hidden = UNDEFINED;
private Boolean _collapsed = UNDEFINED;
-
+
public SXSSFRow(SXSSFSheet sheet)
{
_sheet=sheet;
}
-
+
public Iterator allCellsIterator()
{
return new CellIterator();
@@ -71,7 +71,7 @@ public class SXSSFRow implements Row, Comparable
void setOutlineLevel(int level){
_outlineLevel = level;
}
-
+
/**
* get row hidden state: Hidden (true), Unhidden (false), Undefined (null)
*
@@ -235,7 +235,7 @@ public class SXSSFRow implements Row, Comparable
public SXSSFCell getCell(int cellnum, MissingCellPolicy policy)
{
checkBounds(cellnum);
-
+
final SXSSFCell cell = _cells.get(cellnum);
switch (policy) {
case RETURN_NULL_AND_BLANK:
@@ -345,10 +345,11 @@ public class SXSSFRow implements Row, Comparable
@Override
public void setHeightInPoints(float height)
{
- if(height==-1)
+ if(height==-1) {
_height=-1;
- else
+ } else {
_height=(short)(height*20);
+ }
}
/**
@@ -375,7 +376,7 @@ public class SXSSFRow implements Row, Comparable
{
return (float)(_height==-1?getSheet().getDefaultRowHeightInPoints():_height/20.0);
}
-
+
/**
* Is this row formatted? Most aren't, but some rows
* do have whole-row styles. For those that do, you
@@ -392,16 +393,18 @@ public class SXSSFRow implements Row, Comparable
*/
@Override
public CellStyle getRowStyle() {
- if(!isFormatted()) return null;
-
+ if(!isFormatted()) {
+ return null;
+ }
+
return getSheet().getWorkbook().getCellStyleAt(_style);
}
-
+
@Internal
/*package*/ int getRowStyleIndex() {
return _style;
}
-
+
/**
* Applies a whole-row cell styling to the row.
* The row style can be cleared by passing in null .
@@ -440,7 +443,7 @@ public class SXSSFRow implements Row, Comparable
/**
* Create an iterator over the cells from [0, getLastCellNum()).
* Includes blank cells, excludes empty cells
- *
+ *
* Returns an iterator over all filled cells (created via Row.createCell())
* Throws ConcurrentModificationException if cells are added, moved, or
* removed after the iterator is created.
@@ -485,10 +488,11 @@ public class SXSSFRow implements Row, Comparable
@Override
public Cell next() throws NoSuchElementException
{
- if (hasNext())
+ if (hasNext()) {
return _cells.get(pos++);
- else
+ } else {
throw new NoSuchElementException();
+ }
}
@Override
public void remove()
@@ -496,7 +500,7 @@ public class SXSSFRow implements Row, Comparable
throw new UnsupportedOperationException();
}
}
-
+
/**
* Compares two SXSSFRow objects. Two rows are equal if they belong to the same worksheet and
* their row indexes are equal.
@@ -524,9 +528,9 @@ public class SXSSFRow implements Row, Comparable
throw new IllegalArgumentException("The compared rows must belong to the same sheet");
}
- Integer thisRow = this.getRowNum();
- Integer otherRow = other.getRowNum();
- return thisRow.compareTo(otherRow);
+ int thisRow = this.getRowNum();
+ int otherRow = other.getRowNum();
+ return Integer.compare(thisRow, otherRow);
}
@Override
diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDrawing.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDrawing.java
index 3f42faab5f..1ae1e99217 100644
--- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDrawing.java
+++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDrawing.java
@@ -446,7 +446,7 @@ public final class XSSFDrawing extends POIXMLDocumentPart implements Drawing {
_cells.put(colI, cell);
sheet.onReadCell(cell);
}
-
+
if (! row.isSetR()) {
// Certain file format writers skip the row number
// Assume no gaps, and give this the next row number
@@ -158,9 +158,9 @@ public class XSSFRow implements Row, Comparable {
throw new IllegalArgumentException("The compared rows must belong to the same sheet");
}
- Integer thisRow = this.getRowNum();
- Integer otherRow = other.getRowNum();
- return thisRow.compareTo(otherRow);
+ int thisRow = this.getRowNum();
+ int otherRow = other.getRowNum();
+ return Integer.compare(thisRow, otherRow);
}
@Override
@@ -245,7 +245,9 @@ public class XSSFRow implements Row, Comparable {
*/
@Override
public XSSFCell getCell(int cellnum, MissingCellPolicy policy) {
- if(cellnum < 0) throw new IllegalArgumentException("Cell index must be >= 0");
+ if(cellnum < 0) {
+ throw new IllegalArgumentException("Cell index must be >= 0");
+ }
// Performance optimization for bug 57840: explicit boxing is slightly faster than auto-unboxing, though may use more memory
final Integer colI = Integer.valueOf(cellnum); // NOSONAR
@@ -332,8 +334,12 @@ public class XSSFRow implements Row, Comparable {
@Override
public void setHeight(short height) {
if (height == -1) {
- if (_row.isSetHt()) _row.unsetHt();
- if (_row.isSetCustomHeight()) _row.unsetCustomHeight();
+ if (_row.isSetHt()) {
+ _row.unsetHt();
+ }
+ if (_row.isSetCustomHeight()) {
+ _row.unsetCustomHeight();
+ }
} else {
_row.setHt((double) height / 20);
_row.setCustomHeight(true);
@@ -425,8 +431,10 @@ public class XSSFRow implements Row, Comparable {
*/
@Override
public XSSFCellStyle getRowStyle() {
- if(!isFormatted()) return null;
-
+ if(!isFormatted()) {
+ return null;
+ }
+
StylesTable stylesSource = getSheet().getWorkbook().getStylesSource();
if(stylesSource.getNumCellStyles() > 0) {
return stylesSource.getStyleAt((int)_row.getS());
@@ -434,7 +442,7 @@ public class XSSFRow implements Row, Comparable {
return null;
}
}
-
+
/**
* Applies a whole-row cell styling to the row.
* If the value is null then the style information is removed,
@@ -449,7 +457,7 @@ public class XSSFRow implements Row, Comparable {
}
} else {
StylesTable styleSource = getSheet().getWorkbook().getStylesSource();
-
+
XSSFCellStyle xStyle = (XSSFCellStyle)style;
xStyle.verifyBelongsToStylesSource(styleSource);
@@ -458,7 +466,7 @@ public class XSSFRow implements Row, Comparable {
_row.setCustomFormat(true);
}
}
-
+
/**
* Remove the Cell from this row.
*
@@ -502,8 +510,8 @@ public class XSSFRow implements Row, Comparable {
int i = 0;
for (XSSFCell xssfCell : _cells.values()) {
cArray[i] = (CTCell) xssfCell.getCTCell().copy();
-
- // we have to copy and re-create the XSSFCell here because the
+
+ // we have to copy and re-create the XSSFCell here because the
// elements as otherwise setCArray below invalidates all the columns!
// see Bug 56170, XMLBeans seems to always release previous objects
// in the CArray, so we need to provide completely new ones here!
@@ -537,7 +545,7 @@ public class XSSFRow implements Row, Comparable {
}
setRowNum(rownum);
}
-
+
/**
* Copy the cells from srcRow to this row
* If this row is not a blank row, this will merge the two rows, overwriting
@@ -589,7 +597,7 @@ public class XSSFRow implements Row, Comparable {
final int srcRowNum = srcRow.getRowNum();
final int destRowNum = getRowNum();
final int rowDifference = destRowNum - srcRowNum;
-
+
final FormulaShifter formulaShifter = FormulaShifter.createForRowCopy(sheetIndex, sheetName, srcRowNum, srcRowNum, rowDifference, SpreadsheetVersion.EXCEL2007);
final XSSFRowShifter rowShifter = new XSSFRowShifter(_sheet);
rowShifter.updateRowFormulas(this, formulaShifter);
@@ -617,7 +625,7 @@ public class XSSFRow implements Row, Comparable {
public int getOutlineLevel() {
return _row.getOutlineLevel();
}
-
+
/**
* Shifts column range [firstShiftColumnIndex-lastShiftColumnIndex] step places to the right.
* @param firstShiftColumnIndex the column to start shifting
@@ -626,20 +634,23 @@ public class XSSFRow implements Row, Comparable {
*/
@Override
public void shiftCellsRight(int firstShiftColumnIndex, int lastShiftColumnIndex, int step) {
- if(step < 0)
+ if(step < 0) {
throw new IllegalArgumentException("Shifting step may not be negative ");
- if(firstShiftColumnIndex > lastShiftColumnIndex)
+ }
+ if(firstShiftColumnIndex > lastShiftColumnIndex) {
throw new IllegalArgumentException(String.format(LocaleUtil.getUserLocale(),
"Incorrect shifting range : %d-%d", firstShiftColumnIndex, lastShiftColumnIndex));
- for (int columnIndex = lastShiftColumnIndex; columnIndex >= firstShiftColumnIndex; columnIndex--){ // process cells backwards, because of shifting
+ }
+ for (int columnIndex = lastShiftColumnIndex; columnIndex >= firstShiftColumnIndex; columnIndex--){ // process cells backwards, because of shifting
shiftCell(columnIndex, step);
}
for (int columnIndex = firstShiftColumnIndex; columnIndex <= firstShiftColumnIndex+step-1; columnIndex++)
{
_cells.remove(columnIndex);
XSSFCell targetCell = getCell(columnIndex);
- if(targetCell != null)
+ if(targetCell != null) {
targetCell.getCTCell().set(CTCell.Factory.newInstance());
+ }
}
}
/**
@@ -650,27 +661,32 @@ public class XSSFRow implements Row, Comparable {
*/
@Override
public void shiftCellsLeft(int firstShiftColumnIndex, int lastShiftColumnIndex, int step) {
- if(step < 0)
+ if(step < 0) {
throw new IllegalArgumentException("Shifting step may not be negative ");
- if(firstShiftColumnIndex > lastShiftColumnIndex)
+ }
+ if(firstShiftColumnIndex > lastShiftColumnIndex) {
throw new IllegalArgumentException(String.format(LocaleUtil.getUserLocale(),
"Incorrect shifting range : %d-%d", firstShiftColumnIndex, lastShiftColumnIndex));
- if(firstShiftColumnIndex - step < 0)
+ }
+ if(firstShiftColumnIndex - step < 0) {
throw new IllegalStateException("Column index less than zero : " + (Integer.valueOf(firstShiftColumnIndex + step)).toString());
- for (int columnIndex = firstShiftColumnIndex; columnIndex <= lastShiftColumnIndex; columnIndex++){
+ }
+ for (int columnIndex = firstShiftColumnIndex; columnIndex <= lastShiftColumnIndex; columnIndex++){
shiftCell(columnIndex, -step);
}
for (int columnIndex = lastShiftColumnIndex-step+1; columnIndex <= lastShiftColumnIndex; columnIndex++){
_cells.remove(columnIndex);
XSSFCell targetCell = getCell(columnIndex);
- if(targetCell != null)
+ if(targetCell != null) {
targetCell.getCTCell().set(CTCell.Factory.newInstance());
+ }
}
}
private void shiftCell(int columnIndex, int step/*pass negative value for left shift*/){
- if(columnIndex + step < 0) // only for shifting left
+ if(columnIndex + step < 0) {
throw new IllegalStateException("Column index less than zero : " + (Integer.valueOf(columnIndex + step)).toString());
-
+ }
+
XSSFCell currentCell = getCell(columnIndex);
if(currentCell != null){
currentCell.setCellNum(columnIndex+step);
@@ -679,8 +695,9 @@ public class XSSFRow implements Row, Comparable {
else {
_cells.remove(columnIndex+step);
XSSFCell targetCell = getCell(columnIndex+step);
- if(targetCell != null)
+ if(targetCell != null) {
targetCell.getCTCell().set(CTCell.Factory.newInstance());
+ }
}
}
}
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java
index 587674edc3..99ab66a7ee 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java
@@ -40,16 +40,16 @@ public class XWPFSDTContent implements ISDTContent {
// private final IBody part;
// private final XWPFDocument document;
- private List paragraphs = new ArrayList<>();
- private List tables = new ArrayList<>();
- private List runs = new ArrayList<>();
- private List contentControls = new ArrayList<>();
+ // private List paragraphs = new ArrayList<>();
+ // private List tables = new ArrayList<>();
+ // private List runs = new ArrayList<>();
+ // private List contentControls = new ArrayList<>();
private List bodyElements = new ArrayList<>();
public XWPFSDTContent(CTSdtContentRun sdtRun, IBody part, IRunBody parent) {
for (CTR ctr : sdtRun.getRArray()) {
XWPFRun run = new XWPFRun(ctr, parent);
- runs.add(run);
+ // runs.add(run);
bodyElements.add(run);
}
}
@@ -62,24 +62,25 @@ public class XWPFSDTContent implements ISDTContent {
if (o instanceof CTP) {
XWPFParagraph p = new XWPFParagraph((CTP) o, part);
bodyElements.add(p);
- paragraphs.add(p);
+ // paragraphs.add(p);
} else if (o instanceof CTTbl) {
XWPFTable t = new XWPFTable((CTTbl) o, part);
bodyElements.add(t);
- tables.add(t);
+ // tables.add(t);
} else if (o instanceof CTSdtBlock) {
XWPFSDT c = new XWPFSDT(((CTSdtBlock) o), part);
bodyElements.add(c);
- contentControls.add(c);
+ // contentControls.add(c);
} else if (o instanceof CTR) {
XWPFRun run = new XWPFRun((CTR) o, parent);
- runs.add(run);
+ // runs.add(run);
bodyElements.add(run);
}
}
cursor.dispose();
}
+ @Override
public String getText() {
StringBuilder text = new StringBuilder();
boolean addNewLine = false;
@@ -130,6 +131,7 @@ public class XWPFSDTContent implements ISDTContent {
}
}
+ @Override
public String toString() {
return getText();
}
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java
index 0caca8c6dd..9352fe8a1d 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java
@@ -161,8 +161,9 @@ public class XWPFTable implements IBodyElement, ISDTContents {
this.ctTbl = table;
// is an empty table: I add one row and one column as default
- if (table.sizeOfTrArray() == 0)
+ if (table.sizeOfTrArray() == 0) {
createEmptyTable(table);
+ }
for (CTRow row : table.getTrList()) {
StringBuilder rowText = new StringBuilder();
@@ -233,7 +234,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
return text.toString();
}
-
+
/**
* This method has existed since 2008 without an implementation.
* It will be removed unless an implementation is provided.
@@ -288,7 +289,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get the width value as an integer.
* If the width type is AUTO, DXA, or NIL, the value is 20ths of a point. If
- * the width type is PCT, the value is the percentage times 50 (e.g., 2500 for 50%).
+ * the width type is PCT, the value is the percentage times 50 (e.g., 2500 for 50%). |
* @return width value as an integer
*/
public int getWidth() {
@@ -322,7 +323,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
}
/**
- * Returns CTTblPr object for table. If force parameter is true, will
+ * Returns CTTblPr object for table. If force parameter is true, will
* create the element if necessary. If force parameter is false, returns
* null when CTTblPr element is missing.
*
@@ -343,7 +344,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
private CTTblBorders getTblBorders(boolean force) {
CTTblPr tblPr = getTblPr(force);
return tblPr == null ? null
- : tblPr.isSetTblBorders() ? tblPr.getTblBorders()
+ : tblPr.isSetTblBorders() ? tblPr.getTblBorders()
: force ? tblPr.addNewTblBorders()
: null;
}
@@ -413,18 +414,18 @@ public class XWPFTable implements IBodyElement, ISDTContents {
: tPr.isSetJc() ? TableRowAlign.valueOf(tPr.getJc().getVal().intValue())
: null;
}
-
+
/**
* Set table alignment to specified {@link TableRowAlign}
*
- * @param ha {@link TableRowAlign} to set
+ * @param tra {@link TableRowAlign} to set
*/
public void setTableAlignment(TableRowAlign tra) {
CTTblPr tPr = getTblPr(true);
CTJc jc = tPr.isSetJc() ? tPr.getJc() : tPr.addNewJc();
jc.setVal(STJc.Enum.forInt(tra.getValue()));
}
-
+
/**
* Removes the table alignment attribute from a table
*/
@@ -434,7 +435,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
tPr.unsetJc();
}
}
-
+
private void addColumn(XWPFTableRow tabRow, int sizeCol) {
if (sizeCol > 0) {
for (int i = 0; i < sizeCol; i++) {
@@ -486,7 +487,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get inside horizontal border size
- *
+ *
* @return The width of the Inside Horizontal borders in 1/8th points,
* -1 if missing.
*/
@@ -496,7 +497,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get inside horizontal border spacing
- *
+ *
* @return The offset to the Inside Horizontal borders in points,
* -1 if missing.
*/
@@ -506,7 +507,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get inside horizontal border color
- *
+ *
* @return The color of the Inside Horizontal borders, null if missing.
*/
public String getInsideHBorderColor() {
@@ -524,7 +525,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get inside vertical border size
- *
+ *
* @return The width of the Inside vertical borders in 1/8th points,
* -1 if missing.
*/
@@ -534,7 +535,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get inside vertical border spacing
- *
+ *
* @return The offset to the Inside vertical borders in points,
* -1 if missing.
*/
@@ -544,7 +545,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get inside vertical border color
- *
+ *
* @return The color of the Inside vertical borders, null if missing.
*/
public String getInsideVBorderColor() {
@@ -562,7 +563,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get top border size
- *
+ *
* @return The width of the top borders in 1/8th points,
* -1 if missing.
*/
@@ -572,7 +573,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get top border spacing
- *
+ *
* @return The offset to the top borders in points,
* -1 if missing.
*/
@@ -582,7 +583,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get top border color
- *
+ *
* @return The color of the top borders, null if missing.
*/
public String getTopBorderColor() {
@@ -600,7 +601,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get bottom border size
- *
+ *
* @return The width of the bottom borders in 1/8th points,
* -1 if missing.
*/
@@ -610,7 +611,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get bottom border spacing
- *
+ *
* @return The offset to the bottom borders in points,
* -1 if missing.
*/
@@ -620,7 +621,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get bottom border color
- *
+ *
* @return The color of the bottom borders, null if missing.
*/
public String getBottomBorderColor() {
@@ -638,7 +639,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get Left border size
- *
+ *
* @return The width of the Left borders in 1/8th points,
* -1 if missing.
*/
@@ -648,7 +649,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get Left border spacing
- *
+ *
* @return The offset to the Left borders in points,
* -1 if missing.
*/
@@ -658,7 +659,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get Left border color
- *
+ *
* @return The color of the Left borders, null if missing.
*/
public String getLeftBorderColor() {
@@ -676,7 +677,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get Right border size
- *
+ *
* @return The width of the Right borders in 1/8th points,
* -1 if missing.
*/
@@ -686,7 +687,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get Right border spacing
- *
+ *
* @return The offset to the Right borders in points,
* -1 if missing.
*/
@@ -696,7 +697,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* Get Right border color
- *
+ *
* @return The color of the Right borders, null if missing.
*/
public String getRightBorderColor() {
@@ -770,7 +771,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
* of a point) and a maximum value of 96 (twelve points). Any values outside this
* range may be reassigned to a more appropriate value.
* @param space - Specifies the spacing offset that shall be used to place this border on the table
- * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
+ * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
* or auto to allow a consumer to automatically determine the border color as appropriate.
*/
public void setInsideHBorder(XWPFBorderType type, int size, int space, String rgbColor) {
@@ -786,7 +787,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
* of a point) and a maximum value of 96 (twelve points). Any values outside this
* range may be reassigned to a more appropriate value.
* @param space - Specifies the spacing offset that shall be used to place this border on the table
- * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
+ * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
* or auto to allow a consumer to automatically determine the border color as appropriate.
*/
public void setInsideVBorder(XWPFBorderType type, int size, int space, String rgbColor) {
@@ -802,7 +803,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
* of a point) and a maximum value of 96 (twelve points). Any values outside this
* range may be reassigned to a more appropriate value.
* @param space - Specifies the spacing offset that shall be used to place this border on the table
- * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
+ * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
* or auto to allow a consumer to automatically determine the border color as appropriate.
*/
public void setTopBorder(XWPFBorderType type, int size, int space, String rgbColor) {
@@ -818,7 +819,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
* of a point) and a maximum value of 96 (twelve points). Any values outside this
* range may be reassigned to a more appropriate value.
* @param space - Specifies the spacing offset that shall be used to place this border on the table
- * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
+ * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
* or auto to allow a consumer to automatically determine the border color as appropriate.
*/
public void setBottomBorder(XWPFBorderType type, int size, int space, String rgbColor) {
@@ -834,7 +835,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
* of a point) and a maximum value of 96 (twelve points). Any values outside this
* range may be reassigned to a more appropriate value.
* @param space - Specifies the spacing offset that shall be used to place this border on the table
- * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
+ * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
* or auto to allow a consumer to automatically determine the border color as appropriate.
*/
public void setLeftBorder(XWPFBorderType type, int size, int space, String rgbColor) {
@@ -850,7 +851,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
* of a point) and a maximum value of 96 (twelve points). Any values outside this
* range may be reassigned to a more appropriate value.
* @param space - Specifies the spacing offset that shall be used to place this border on the table
- * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
+ * @param rgbColor - This color may either be presented as a hex value (in RRGGBB format),
* or auto to allow a consumer to automatically determine the border color as appropriate.
*/
public void setRightBorder(XWPFBorderType type, int size, int space, String rgbColor) {
@@ -872,14 +873,14 @@ public class XWPFTable implements IBodyElement, ISDTContents {
public void removeInsideHBorder() {
removeBorder(Border.INSIDE_H);
}
-
+
/**
* Remove inside vertical borders for table
*/
public void removeInsideVBorder() {
removeBorder(Border.INSIDE_V);
}
-
+
/**
* Remove top borders for table
*/
@@ -893,21 +894,21 @@ public class XWPFTable implements IBodyElement, ISDTContents {
public void removeBottomBorder() {
removeBorder(Border.BOTTOM);
}
-
+
/**
* Remove left borders for table
*/
public void removeLeftBorder() {
removeBorder(Border.LEFT);
}
-
+
/**
* Remove right borders for table
*/
public void removeRightBorder() {
removeBorder(Border.RIGHT);
}
-
+
/**
* Remove all borders from table
*/
@@ -959,7 +960,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
}
/**
- * removes the Borders node from Table properties if there are
+ * removes the Borders node from Table properties if there are
* no border elements
*/
private void cleanupTblBorders() {
@@ -976,7 +977,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
}
}
}
-
+
public int getCellMarginTop() {
return getCellMargin(CTTblCellMar::getTop);
}
@@ -1095,10 +1096,12 @@ public class XWPFTable implements IBodyElement, ISDTContents {
*
* @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType()
*/
+ @Override
public BodyElementType getElementType() {
return BodyElementType.TABLE;
}
+ @Override
public IBody getBody() {
return part;
}
@@ -1108,6 +1111,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/
+ @Override
public POIXMLDocumentPart getPart() {
if (part != null) {
return part.getPart();
@@ -1120,6 +1124,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
+ @Override
public BodyType getPartType() {
return part.getPartType();
}
@@ -1130,11 +1135,13 @@ public class XWPFTable implements IBodyElement, ISDTContents {
*/
public XWPFTableRow getRow(CTRow row) {
for (int i = 0; i < getRows().size(); i++) {
- if (getRows().get(i).getCtRow() == row) return getRow(i);
+ if (getRows().get(i).getCtRow() == row) {
+ return getRow(i);
+ }
}
return null;
}
-
+
/**
* Get the table width as a decimal value.
* If the width type is DXA or AUTO, then the value will always have
@@ -1159,14 +1166,14 @@ public class XWPFTable implements IBodyElement, ISDTContents {
protected static double getWidthDecimal(CTTblWidth ctWidth) {
double result = 0.0;
STTblWidth.Enum typeValue = ctWidth.getType();
- if (typeValue == STTblWidth.DXA
- || typeValue == STTblWidth.AUTO
+ if (typeValue == STTblWidth.DXA
+ || typeValue == STTblWidth.AUTO
|| typeValue == STTblWidth.NIL) {
result = 0.0 + ctWidth.getW().intValue();
} else if (typeValue == STTblWidth.PCT) {
// Percentage values are stored as integers that are 50 times
// percentage.
- result = ctWidth.getW().intValue() / 50.0;
+ result = ctWidth.getW().intValue() / 50.0;
} else {
// Should never get here
}
@@ -1230,7 +1237,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
protected static void setWidthValue(String widthValue, CTTblWidth ctWidth) {
if (!widthValue.matches(REGEX_WIDTH_VALUE)) {
throw new RuntimeException("Table width value \"" + widthValue + "\" "
- + "must match regular expression \"" + REGEX_WIDTH_VALUE + "\".");
+ + "must match regular expression \"" + REGEX_WIDTH_VALUE + "\".");
}
if (widthValue.matches("auto")) {
ctWidth.setType(STTblWidth.AUTO);
@@ -1240,13 +1247,13 @@ public class XWPFTable implements IBodyElement, ISDTContents {
} else {
// Must be an integer
ctWidth.setW(new BigInteger(widthValue));
- ctWidth.setType(STTblWidth.DXA);
+ ctWidth.setType(STTblWidth.DXA);
}
}
/**
* Set the underlying table width value to a percentage value.
- * @param ctWidth The CTTblWidth to set the value on
+ * @param ctWidth The CTTblWidth to set the value on
* @param widthValue String width value in form "33.3%" or an integer that is 50 times desired percentage value (e.g,
* 2500 for 50%)
* @since 4.0.0
@@ -1257,7 +1264,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
String numberPart = widthValue.substring(0, widthValue.length() - 1);
double percentage = Double.parseDouble(numberPart) * 50;
long intValue = Math.round(percentage);
- ctWidth.setW(BigInteger.valueOf(intValue));
+ ctWidth.setW(BigInteger.valueOf(intValue));
} else if (widthValue.matches("[0-9]+")) {
ctWidth.setW(new BigInteger(widthValue));
} else {
@@ -1275,7 +1282,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
* @since 4.0.0
*/
public void setWidthType(TableWidthType widthType) {
- setWidthType(widthType, getTblPr().getTblW());
+ setWidthType(widthType, getTblPr().getTblW());
}
/**
--
cgit v1.2.3
From 870c1b2cf567209a0c159415cefd89a1615c3e2c Mon Sep 17 00:00:00 2001
From: Tim Allison
Date: Thu, 11 Oct 2018 14:14:07 +0000
Subject: 62815 -- some numeric values not correctly extracted from xlsb
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1843553 13f79535-47bb-0310-9956-ffa450edef68
---
.../apache/poi/xssf/binary/XSSFBSheetHandler.java | 6 +-
.../TestXSSFBEventBasedExcelExtractor.java | 23 ++
test-data/spreadsheet/62815.xlsb | Bin 0 -> 10665 bytes
test-data/spreadsheet/62815.xlsb.txt | 284 +++++++++++++++++++++
4 files changed, 310 insertions(+), 3 deletions(-)
create mode 100644 test-data/spreadsheet/62815.xlsb
create mode 100644 test-data/spreadsheet/62815.xlsb.txt
(limited to 'src/ooxml/java')
diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBSheetHandler.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBSheetHandler.java
index fb3f433bd6..726c2eeb89 100644
--- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBSheetHandler.java
+++ b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBSheetHandler.java
@@ -302,9 +302,8 @@ public class XSSFBSheetHandler extends XSSFBParser {
}
private double rkNumber(byte[] data, int offset) {
- //see 2.5.122 for this abomination
+ //see 2.5.122
byte b0 = data[offset];
- String s = Integer.toString(b0, 2);
boolean numDivBy100 = ((b0 & 1) == 1); // else as is
boolean floatingPoint = ((b0 >> 1 & 1) == 0); // else signed integer
@@ -320,7 +319,8 @@ public class XSSFBSheetHandler extends XSSFBParser {
if (floatingPoint) {
d = LittleEndian.getDouble(rkBuffer);
} else {
- d = LittleEndian.getInt(rkBuffer);
+ int rawInt = LittleEndian.getInt(rkBuffer, 4);
+ d = rawInt >> 2;//divide by 4/shift bits coz 30 bit int, not 32
}
d = (numDivBy100) ? d/100 : d;
return d;
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java
index 4fd9a5c1d7..e173876188 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java
@@ -26,6 +26,10 @@ import static org.junit.Assert.assertTrue;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
+import java.io.BufferedReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+
/**
* Tests for {@link XSSFBEventBasedExcelExtractor}
*/
@@ -110,4 +114,23 @@ public class TestXSSFBEventBasedExcelExtractor {
"This is an example spreadsheet created with Microsoft Excel 2007 Beta 2.");
}
+ @Test
+ public void test62815() throws Exception {
+ //test file based on http://oss.sheetjs.com/test_files/RkNumber.xlsb
+ XSSFEventBasedExcelExtractor extractor = getExtractor("62815.xlsb");
+ extractor.setIncludeCellComments(true);
+ String[] rows = extractor.getText().split("[\r\n]+");
+ assertEquals(283, rows.length);
+ BufferedReader reader = Files.newBufferedReader(XSSFTestDataSamples.getSampleFile("62815.xlsb.txt").toPath(),
+ StandardCharsets.UTF_8);
+ String line = reader.readLine();
+ for (int i = 0; i < rows.length; i++) {
+ assertEquals(line, rows[i]);
+ line = reader.readLine();
+ while (line != null && line.startsWith("#")) {
+ line = reader.readLine();
+ }
+ }
+ }
+
}
diff --git a/test-data/spreadsheet/62815.xlsb b/test-data/spreadsheet/62815.xlsb
new file mode 100644
index 0000000000..66d8e652b0
Binary files /dev/null and b/test-data/spreadsheet/62815.xlsb differ
diff --git a/test-data/spreadsheet/62815.xlsb.txt b/test-data/spreadsheet/62815.xlsb.txt
new file mode 100644
index 0000000000..94060e3171
--- /dev/null
+++ b/test-data/spreadsheet/62815.xlsb.txt
@@ -0,0 +1,284 @@
+RkNumber
+10000000
+1200455
+0.01
+12004.55
+-10000000
+-1200455
+-0.01
+-12004.55
+10268609
+1071427521
+-1071427521
+273214017855
+69942788570880
+17905353874145300
+17835411085574400
+273214017855
+273214017856
+273214017857
+273214017858
+273214017859
+273214017860
+273214017861
+273214017862
+273214017863
+273214017864
+273214017865
+273214017866
+273214017867
+273214017868
+273214017869
+273214017870
+273214017871
+273214017872
+273214017873
+273214017874
+273214017875
+273214017876
+273214017877
+273214017878
+273214017879
+273214017880
+273214017881
+273214017882
+273214017883
+273214017884
+273214017885
+273214017886
+273214017887
+273214017888
+273214017889
+273214017890
+273214017891
+273214017892
+273214017893
+273214017894
+273214017895
+273214017896
+273214017897
+273214017898
+273214017899
+273214017900
+273214017901
+273214017902
+273214017903
+273214017904
+273214017905
+273214017906
+273214017907
+273214017908
+273214017909
+273214017910
+273214017911
+273214017912
+273214017913
+273214017914
+273214017915
+273214017916
+273214017917
+273214017918
+273214017919
+273214017920
+273214017921
+273214017922
+273214017923
+273214017924
+273214017925
+273214017926
+273214017927
+273214017928
+273214017929
+273214017930
+273214017931
+273214017932
+273214017933
+273214017934
+273214017935
+273214017936
+273214017937
+273214017938
+273214017939
+273214017940
+273214017941
+273214017942
+273214017943
+273214017944
+273214017945
+273214017946
+273214017947
+273214017948
+273214017949
+273214017950
+273214017951
+273214017952
+273214017953
+273214017954
+273214017955
+273214017956
+273214017957
+273214017958
+273214017959
+273214017960
+273214017961
+273214017962
+273214017963
+273214017964
+273214017965
+273214017966
+273214017967
+273214017968
+273214017969
+273214017970
+273214017971
+273214017972
+273214017973
+273214017974
+273214017975
+273214017976
+273214017977
+273214017978
+273214017979
+273214017980
+273214017981
+273214017982
+273214017983
+273214017984
+273214017985
+273214017986
+273214017987
+273214017988
+273214017989
+273214017990
+273214017991
+273214017992
+273214017993
+273214017994
+273214017995
+273214017996
+273214017997
+273214017998
+273214017999
+273214018000
+273214018001
+273214018002
+273214018003
+273214018004
+273214018005
+273214018006
+273214018007
+273214018008
+273214018009
+273214018010
+273214018011
+273214018012
+273214018013
+273214018014
+273214018015
+273214018016
+273214018017
+273214018018
+273214018019
+273214018020
+273214018021
+273214018022
+273214018023
+273214018024
+273214018025
+273214018026
+273214018027
+273214018028
+273214018029
+273214018030
+273214018031
+273214018032
+273214018033
+273214018034
+273214018035
+273214018036
+273214018037
+273214018038
+273214018039
+273214018040
+273214018041
+273214018042
+273214018043
+273214018044
+273214018045
+273214018046
+273214018047
+273214018048
+273214018049
+273214018050
+273214018051
+273214018052
+273214018053
+273214018054
+273214018055
+273214018056
+273214018057
+273214018058
+273214018059
+273214018060
+273214018061
+273214018062
+273214018063
+273214018064
+273214018065
+273214018066
+273214018067
+273214018068
+273214018069
+273214018070
+273214018071
+273214018072
+273214018073
+273214018074
+273214018075
+273214018076
+273214018077
+273214018078
+273214018079
+273214018080
+273214018081
+273214018082
+273214018083
+273214018084
+273214018085
+273214018086
+273214018087
+273214018088
+273214018089
+273214018090
+273214018091
+273214018092
+273214018093
+273214018094
+273214018095
+273214018096
+273214018097
+273214018098
+273214018099
+273214018100
+273214018101
+273214018102
+273214018103
+273214018104
+273214018105
+273214018106
+273214018107
+273214018108
+273214018109
+273214018110
+273214018111
+273214018112
+273214018113
+273214018114
+273214018115
+910713.3937166670
+3.03571131238889
+0.000010119037707963000
+3.37E-11
+1.12E-16
+#excel doesn't display ...863, this was manually altered to get the test to work
+3.7477917436899863E-22
--
cgit v1.2.3
From 6b433ae8b34b8c32a0457d74fe3b023222fe7945 Mon Sep 17 00:00:00 2001
From: Greg Woolsey
Date: Fri, 19 Oct 2018 01:11:47 +0000
Subject: #62834 FormulaEvaluator.evaluateInCell() throws Exception
added cell type = formula check when looping through the shared formula range, to ignore any non-formula cells.
Also refactored a bit to enable passing in the evaluation context, as getCellFormula() uses it behind the scenes when evaluating a shared formula cell (has to shift the formula references based on the master cell). Review of these changes is welcome, as always.
Checked all other code referencing the "SHARED" enum, and didn't see anything else that dealt with formula cell values and thus would need to notice non-formula cells.
Added unit test based on the failing file from Bugzilla. Test failed until the fixed code was in place.
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1844295 13f79535-47bb-0310-9956-ffa450edef68
---
.../poi/ss/formula/BaseFormulaEvaluator.java | 26 ++++++++++++-
src/java/org/apache/poi/ss/usermodel/Sheet.java | 5 ++-
.../xssf/usermodel/BaseXSSFFormulaEvaluator.java | 9 +++++
.../org/apache/poi/xssf/usermodel/XSSFCell.java | 23 +++++++++--
.../org/apache/poi/xssf/usermodel/XSSFSheet.java | 8 ++--
.../xssf/usermodel/TestXSSFFormulaEvaluation.java | 43 ++++++++++++++++++++-
test-data/spreadsheet/62834.xlsx | Bin 0 -> 9629 bytes
7 files changed, 102 insertions(+), 12 deletions(-)
create mode 100644 test-data/spreadsheet/62834.xlsx
(limited to 'src/ooxml/java')
diff --git a/src/java/org/apache/poi/ss/formula/BaseFormulaEvaluator.java b/src/java/org/apache/poi/ss/formula/BaseFormulaEvaluator.java
index 51a99d5950..ee0615057d 100644
--- a/src/java/org/apache/poi/ss/formula/BaseFormulaEvaluator.java
+++ b/src/java/org/apache/poi/ss/formula/BaseFormulaEvaluator.java
@@ -64,6 +64,14 @@ public abstract class BaseFormulaEvaluator implements FormulaEvaluator, Workbook
return _bookEvaluator;
}
+ /**
+ * internal use
+ * @return evaluation workbook
+ */
+ protected EvaluationWorkbook getEvaluationWorkbook() {
+ return _bookEvaluator.getWorkbook();
+ }
+
/**
* Should be called whenever there are major changes (e.g. moving sheets) to input cells
* in the evaluated workbook. If performance is not critical, a single call to this method
@@ -208,14 +216,19 @@ public abstract class BaseFormulaEvaluator implements FormulaEvaluator, Workbook
return evaluateFormulaCell(cell);
}
- protected static void setCellType(Cell cell, CellValue cv) {
+ /**
+ * set the cell type
+ * @param cell
+ * @param cv
+ */
+ protected void setCellType(Cell cell, CellValue cv) {
CellType cellType = cv.getCellType();
switch (cellType) {
case BOOLEAN:
case ERROR:
case NUMERIC:
case STRING:
- cell.setCellType(cellType);
+ setCellType(cell, cellType);
return;
case BLANK:
// never happens - blanks eventually get translated to zero
@@ -227,6 +240,15 @@ public abstract class BaseFormulaEvaluator implements FormulaEvaluator, Workbook
throw new IllegalStateException("Unexpected cell value type (" + cellType + ")");
}
}
+
+ /**
+ * Override if a different variation is needed, e.g. passing the evaluator to the cell method
+ * @param cell
+ * @param cellType
+ */
+ protected void setCellType(Cell cell, CellType cellType) {
+ cell.setCellType(cellType);
+ }
protected abstract RichTextString createRichTextString(String str);
diff --git a/src/java/org/apache/poi/ss/usermodel/Sheet.java b/src/java/org/apache/poi/ss/usermodel/Sheet.java
index 7e3eb3c574..d9dd4ec132 100644
--- a/src/java/org/apache/poi/ss/usermodel/Sheet.java
+++ b/src/java/org/apache/poi/ss/usermodel/Sheet.java
@@ -1006,7 +1006,10 @@ public interface Sheet extends Iterable {
/**
* Sets array formula to specified region for result.
- *
+ *
+ * Note if there are shared formulas this will invalidate any
+ * {@link FormulaEvaluator} instances based on this workbook
+ *
* @param formula text representation of the formula
* @param range Region of array formula for result.
* @return the {@link CellRange} of cells affected by this change
diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java
index adb951d77a..0e41e50cb5 100644
--- a/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java
+++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java
@@ -19,6 +19,7 @@ package org.apache.poi.xssf.usermodel;
import org.apache.poi.ss.formula.BaseFormulaEvaluator;
import org.apache.poi.ss.formula.EvaluationCell;
+import org.apache.poi.ss.formula.EvaluationWorkbook;
import org.apache.poi.ss.formula.WorkbookEvaluator;
import org.apache.poi.ss.formula.eval.BoolEval;
import org.apache.poi.ss.formula.eval.ErrorEval;
@@ -26,6 +27,7 @@ import org.apache.poi.ss.formula.eval.NumberEval;
import org.apache.poi.ss.formula.eval.StringEval;
import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.RichTextString;
@@ -69,4 +71,11 @@ public abstract class BaseXSSFFormulaEvaluator extends BaseFormulaEvaluator {
}
throw new RuntimeException("Unexpected eval class (" + eval.getClass().getName() + ")");
}
+
+ protected void setCellType(Cell cell, CellType cellType) {
+ EvaluationWorkbook evaluationWorkbook = getEvaluationWorkbook();
+ BaseXSSFEvaluationWorkbook xewb = BaseXSSFEvaluationWorkbook.class.isAssignableFrom(evaluationWorkbook.getClass()) ? (BaseXSSFEvaluationWorkbook) evaluationWorkbook : null;
+
+ ((XSSFCell) cell).setCellType(cellType, xewb);
+ }
}
diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java
index b3113203a6..a9490694c0 100644
--- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java
+++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java
@@ -37,6 +37,7 @@ import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaError;
+import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
@@ -477,7 +478,7 @@ public final class XSSFCell implements Cell {
* @return a formula for the cell
* @throws IllegalStateException if the cell type returned by {@link #getCellType()} is not {@link CellType#FORMULA}
*/
- protected String getCellFormula(XSSFEvaluationWorkbook fpb) {
+ protected String getCellFormula(BaseXSSFEvaluationWorkbook fpb) {
CellType cellType = getCellType();
if(cellType != CellType.FORMULA) {
throw typeMismatch(CellType.FORMULA, cellType, false);
@@ -506,7 +507,7 @@ public final class XSSFCell implements Cell {
* @param si Shared Group Index
* @return non shared formula created for the given shared formula and this cell
*/
- private String convertSharedFormula(int si, XSSFEvaluationWorkbook fpb){
+ private String convertSharedFormula(int si, BaseXSSFEvaluationWorkbook fpb){
XSSFSheet sheet = getSheet();
CTCellFormula f = sheet.getSharedFormula(si);
@@ -536,6 +537,10 @@ public final class XSSFCell implements Cell {
* Note, this method only sets the formula string and does not calculate the formula value.
* To set the precalculated value use {@link #setCellValue(double)} or {@link #setCellValue(String)}
*
+ *
+ * Note, if there are any shared formulas, his will invalidate any
+ * {@link FormulaEvaluator} instances based on this workbook.
+ *
*
* @param formula the formula to set, e.g. "SUM(C4:E4)"
.
* If the argument is null
then the current formula is removed.
@@ -563,7 +568,7 @@ public final class XSSFCell implements Cell {
if (formula == null) {
wb.onDeleteFormula(this);
if (_cell.isSetF()) {
- _row.getSheet().onDeleteFormula(this);
+ _row.getSheet().onDeleteFormula(this, null);
_cell.unsetF();
}
return;
@@ -962,6 +967,16 @@ public final class XSSFCell implements Cell {
*/
@Override
public void setCellType(CellType cellType) {
+ setCellType(cellType, null);
+ }
+
+ /**
+ * Needed by bug #62834, which points out getCellFormula() expects an evaluation context or creates a new one,
+ * so if there is one in use, it needs to be carried on through.
+ * @param cellType
+ * @param evalWb BaseXSSFEvaluationWorkbook already in use, or null if a new implicit one should be used
+ */
+ protected void setCellType(CellType cellType, BaseXSSFEvaluationWorkbook evalWb) {
CellType prevType = getCellType();
if(isPartOfArrayFormulaGroup()){
@@ -969,7 +984,7 @@ public final class XSSFCell implements Cell {
}
if(prevType == CellType.FORMULA && cellType != CellType.FORMULA) {
if (_cell.isSetF()) {
- _row.getSheet().onDeleteFormula(this);
+ _row.getSheet().onDeleteFormula(this, evalWb);
}
getSheet().getWorkbook().onDeleteFormula(this);
}
diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java
index 423561b2ce..cd9620d79c 100644
--- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java
+++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java
@@ -4621,8 +4621,10 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
/**
* when a cell with a 'master' shared formula is removed, the next cell in the range becomes the master
+ * @param cell
+ * @param evalWb BaseXSSFEvaluationWorkbook in use, if one exists
*/
- protected void onDeleteFormula(XSSFCell cell){
+ protected void onDeleteFormula(XSSFCell cell, BaseXSSFEvaluationWorkbook evalWb){
CTCellFormula f = cell.getCTCell().getF();
if (f != null && f.getT() == STCellFormulaType.SHARED && f.isSetRef() && f.getStringValue() != null) {
@@ -4634,9 +4636,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
XSSFRow row = getRow(i);
if(row != null) for(int j = cell.getColumnIndex(); j <= ref.getLastColumn(); j++){
XSSFCell nextCell = row.getCell(j);
- if(nextCell != null && nextCell != cell){
+ if(nextCell != null && nextCell != cell && nextCell.getCellType() == CellType.FORMULA){
CTCellFormula nextF = nextCell.getCTCell().getF();
- nextF.setStringValue(nextCell.getCellFormula());
+ nextF.setStringValue(nextCell.getCellFormula(evalWb));
CellRangeAddress nextRef = new CellRangeAddress(
nextCell.getRowIndex(), ref.getLastRow(),
nextCell.getColumnIndex(), ref.getLastColumn());
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java
index f8f71686fa..418eb268e8 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java
@@ -17,14 +17,24 @@
package org.apache.poi.xssf.usermodel;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellValue;
+import org.apache.poi.ss.usermodel.CreationHelper;
+import org.apache.poi.ss.usermodel.FormulaEvaluator;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.xssf.XSSFTestDataSamples;
@@ -437,6 +447,10 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
assertEquals("D 0,068", evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(1)));
}
+ /**
+ * see bug 62275
+ * @throws IOException
+ */
@Test
public void testBug62275() throws IOException {
try (Workbook wb = new XSSFWorkbook()) {
@@ -451,4 +465,29 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
eval.evaluate(cell);
}
}
+
+ /**
+ * see bug 62834, handle when a shared formula range doesn't contain only formula cells
+ * @throws IOException
+ */
+ @Test
+ public void testBug62834() throws IOException {
+ try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("62834.xlsx")) {
+ FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
+
+ Cell a2 = wb.getSheetAt(0).getRow(1).getCell(0);
+ Cell value = evaluator.evaluateInCell(a2);
+ assertEquals("wrong value A2", "a value", value.getStringCellValue());
+
+// evaluator.clearAllCachedResultValues();
+
+ Cell a3 = wb.getSheetAt(0).getRow(2).getCell(0);
+ value = evaluator.evaluateInCell(a3);
+ assertEquals("wrong value A3", "a value", value.getStringCellValue());
+
+ Cell a5 = wb.getSheetAt(0).getRow(4).getCell(0);
+ value = evaluator.evaluateInCell(a5);
+ assertEquals("wrong value A5", "another value", value.getStringCellValue());
+ }
+ }
}
diff --git a/test-data/spreadsheet/62834.xlsx b/test-data/spreadsheet/62834.xlsx
new file mode 100644
index 0000000000..2f265e69c2
Binary files /dev/null and b/test-data/spreadsheet/62834.xlsx differ
--
cgit v1.2.3
From 59ee53ca71cc2e97c77f43bb92e6e0c6ed1af4e6 Mon Sep 17 00:00:00 2001
From: PJ Fanning
Date: Fri, 19 Oct 2018 07:43:04 +0000
Subject: fix class cast issur recently introduced in BaseXSSFFormulaEvaluator
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1844311 13f79535-47bb-0310-9956-ffa450edef68
---
.../apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java | 13 +++++++++----
1 file changed, 9 insertions(+), 4 deletions(-)
(limited to 'src/ooxml/java')
diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java
index 0e41e50cb5..bbad20e518 100644
--- a/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java
+++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java
@@ -73,9 +73,14 @@ public abstract class BaseXSSFFormulaEvaluator extends BaseFormulaEvaluator {
}
protected void setCellType(Cell cell, CellType cellType) {
- EvaluationWorkbook evaluationWorkbook = getEvaluationWorkbook();
- BaseXSSFEvaluationWorkbook xewb = BaseXSSFEvaluationWorkbook.class.isAssignableFrom(evaluationWorkbook.getClass()) ? (BaseXSSFEvaluationWorkbook) evaluationWorkbook : null;
-
- ((XSSFCell) cell).setCellType(cellType, xewb);
+ if (cell instanceof XSSFCell) {
+ EvaluationWorkbook evaluationWorkbook = getEvaluationWorkbook();
+ BaseXSSFEvaluationWorkbook xewb = BaseXSSFEvaluationWorkbook.class.isAssignableFrom(evaluationWorkbook.getClass()) ? (BaseXSSFEvaluationWorkbook) evaluationWorkbook : null;
+
+ ((XSSFCell) cell).setCellType(cellType, xewb);
+ } else {
+ // could be an SXSSFCell
+ cell.setCellType(cellType);
+ }
}
}
--
cgit v1.2.3
From a8fd70ec7fba1b66474f1fdde159b4764ad83c41 Mon Sep 17 00:00:00 2001
From: Dominik Stadler
Date: Fri, 26 Oct 2018 09:32:57 +0000
Subject: Adjust sample for creating comments to also create a .xlsx file
Enhance workbook factory to allow to create new empty workbooks as well
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1844881 13f79535-47bb-0310-9956-ffa450edef68
---
.../poi/hssf/usermodel/examples/CellComments.java | 74 ++++++++++++++--------
.../poi/hssf/usermodel/HSSFWorkbookFactory.java | 9 +++
.../apache/poi/ss/usermodel/WorkbookFactory.java | 18 ++++++
.../exceptions/InvalidFormatException.java | 2 +-
.../org/apache/poi/openxml4j/opc/OPCPackage.java | 2 +
.../poi/xssf/usermodel/XSSFWorkbookFactory.java | 15 +++--
.../org/apache/poi/ss/TestWorkbookFactory.java | 71 ++++++++++++---------
7 files changed, 129 insertions(+), 62 deletions(-)
(limited to 'src/ooxml/java')
diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java
index b14cc53abe..877708bde8 100644
--- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java
+++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java
@@ -17,18 +17,22 @@
package org.apache.poi.hssf.usermodel.examples;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
-import org.apache.poi.hssf.usermodel.HSSFFont;
-import org.apache.poi.hssf.usermodel.HSSFPatriarch;
-import org.apache.poi.hssf.usermodel.HSSFRichTextString;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.ClientAnchor;
+import org.apache.poi.ss.usermodel.Comment;
+import org.apache.poi.ss.usermodel.CreationHelper;
+import org.apache.poi.ss.usermodel.Drawing;
+import org.apache.poi.ss.usermodel.Font;
+import org.apache.poi.ss.usermodel.IndexedColors;
+import org.apache.poi.ss.usermodel.RichTextString;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.ss.usermodel.WorkbookFactory;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
/**
* Demonstrates how to work with excel cell comments.
@@ -39,46 +43,64 @@ import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
public class CellComments {
public static void main(String[] args) throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet("Cell comments in POI HSSF");
+ createWorkbook(false, ".xls");
+ createWorkbook(true, ".xlsx");
+ }
+
+ private static void createWorkbook(boolean xssf, String extension) throws IOException {
+ try (Workbook wb = WorkbookFactory.create(xssf)) {
+ Sheet sheet = wb.createSheet("Cell comments in POI " + extension);
+ CreationHelper creationHelper = wb.getCreationHelper();
// Create the drawing patriarch. This is the top level container for all shapes including cell comments.
- HSSFPatriarch patr = sheet.createDrawingPatriarch();
+ Drawing> patr = sheet.createDrawingPatriarch();
//create a cell in row 3
- HSSFCell cell1 = sheet.createRow(3).createCell(1);
- cell1.setCellValue(new HSSFRichTextString("Hello, World"));
+ Cell cell1 = sheet.createRow(3).createCell(1);
+ cell1.setCellValue(creationHelper.createRichTextString("Hello, World"));
//anchor defines size and position of the comment in worksheet
- HSSFComment comment1 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
+ ClientAnchor clientAnchor = creationHelper.createClientAnchor();
+ clientAnchor.setCol1(4);
+ clientAnchor.setRow1(2);
+ clientAnchor.setCol2(6);
+ clientAnchor.setRow2(5);
+ Comment comment1 = patr.createCellComment(clientAnchor);
// set text in the comment
- comment1.setString(new HSSFRichTextString("We can set comments in POI"));
+ comment1.setString(creationHelper.createRichTextString("We can set comments in POI"));
//set comment author.
//you can see it in the status bar when moving mouse over the commented cell
comment1.setAuthor("Apache Software Foundation");
- // The first way to assign comment to a cell is via HSSFCell.setCellComment method
+ // The first way to assign comment to a cell is via Cell.setCellComment method
cell1.setCellComment(comment1);
//create another cell in row 6
- HSSFCell cell2 = sheet.createRow(6).createCell(1);
+ Cell cell2 = sheet.createRow(6).createCell(1);
cell2.setCellValue(36.6);
- HSSFComment comment2 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 8, (short) 6, 11));
- //modify background color of the comment
- comment2.setFillColor(204, 236, 255);
+ clientAnchor = creationHelper.createClientAnchor();
+ clientAnchor.setCol1(4);
+ clientAnchor.setRow1(8);
+ clientAnchor.setCol2(6);
+ clientAnchor.setRow2(11);
+ Comment comment2 = patr.createCellComment(clientAnchor);
+ //modify background color of the comment, only available in HSSF currently
+ if (wb instanceof HSSFWorkbook) {
+ ((HSSFComment) comment2).setFillColor(204, 236, 255);
+ }
- HSSFRichTextString string = new HSSFRichTextString("Normal body temperature");
+ RichTextString string = creationHelper.createRichTextString("Normal body temperature");
//apply custom font to the text in the comment
- HSSFFont font = wb.createFont();
+ Font font = wb.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 10);
font.setBold(true);
- font.setColor(HSSFColorPredefined.RED.getIndex());
+ font.setColor(IndexedColors.RED.getIndex());
string.applyFont(font);
comment2.setString(string);
@@ -94,7 +116,7 @@ public class CellComments {
comment2.setRow(6);
comment2.setColumn(1);
- try (FileOutputStream out = new FileOutputStream("poi_comment.xls")) {
+ try (FileOutputStream out = new FileOutputStream("poi_comment" + extension)) {
wb.write(out);
}
}
diff --git a/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbookFactory.java b/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbookFactory.java
index e1413aad3b..96196707f6 100644
--- a/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbookFactory.java
+++ b/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbookFactory.java
@@ -31,6 +31,15 @@ import org.apache.poi.util.Internal;
@SuppressWarnings("unused")
@Internal
public class HSSFWorkbookFactory extends WorkbookFactory {
+ /**
+ * Create a new empty Workbook
+ *
+ * @return The created workbook
+ */
+ public static HSSFWorkbook createWorkbook() {
+ return new HSSFWorkbook();
+ }
+
/**
* Creates a HSSFWorkbook from the given NPOIFSFileSystem
* Note that in order to properly release resources the
diff --git a/src/java/org/apache/poi/ss/usermodel/WorkbookFactory.java b/src/java/org/apache/poi/ss/usermodel/WorkbookFactory.java
index aae8c043ce..832795a07f 100644
--- a/src/java/org/apache/poi/ss/usermodel/WorkbookFactory.java
+++ b/src/java/org/apache/poi/ss/usermodel/WorkbookFactory.java
@@ -43,6 +43,24 @@ import org.apache.poi.util.Removal;
* by auto-detecting from the supplied input.
*/
public class WorkbookFactory {
+ /**
+ * Create a new empty Workbook, either XSSF or HSSF depending
+ * on the parameter
+ *
+ * @param xssf If an XSSFWorkbook or a HSSFWorkbook should be created
+ *
+ * @return The created workbook
+ *
+ * @throws IOException if an error occurs while reading the data
+ */
+ public static Workbook create(boolean xssf) throws IOException {
+ if(xssf) {
+ return createXSSFWorkbook();
+ } else {
+ return createHSSFWorkbook();
+ }
+ }
+
/**
* Creates a HSSFWorkbook from the given NPOIFSFileSystem
*
diff --git a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java b/src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java
index 832d47623b..0cf0cfbc19 100644
--- a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java
+++ b/src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java
@@ -18,7 +18,7 @@
package org.apache.poi.openxml4j.exceptions;
@SuppressWarnings("serial")
-public final class InvalidFormatException extends OpenXML4JException{
+public final class InvalidFormatException extends OpenXML4JException {
public InvalidFormatException(String message){
super(message);
diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java
index 9625a86ff9..767abc239d 100644
--- a/src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java
+++ b/src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java
@@ -291,6 +291,8 @@ public abstract class OPCPackage implements RelationshipSource, Closeable {
* @param in
* The InputStream to read the package from
* @return A PackageBase object
+ *
+ * @throws InvalidFormatException
*/
public static OPCPackage open(InputStream in) throws InvalidFormatException,
IOException {
diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbookFactory.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbookFactory.java
index 482654e8f9..7f72c163eb 100644
--- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbookFactory.java
+++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbookFactory.java
@@ -29,6 +29,14 @@ import org.apache.poi.openxml4j.opc.ZipPackage;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class XSSFWorkbookFactory extends WorkbookFactory {
+ /**
+ * Create a new empty Workbook
+ *
+ * @return The created workbook
+ */
+ public static XSSFWorkbook createWorkbook() {
+ return new XSSFWorkbook();
+ }
/**
* Creates a XSSFWorkbook from the given OOXML Package.
@@ -42,7 +50,6 @@ public class XSSFWorkbookFactory extends WorkbookFactory {
* @return The created Workbook
*
* @throws IOException if an error occurs while reading the data
- * @throws InvalidFormatException
*/
public static XSSFWorkbook create(OPCPackage pkg) throws IOException {
return createWorkbook(pkg);
@@ -59,7 +66,6 @@ public class XSSFWorkbookFactory extends WorkbookFactory {
* @return The created Workbook
*
* @throws IOException if an error occurs while reading the data
- * @throws InvalidFormatException
*/
public static XSSFWorkbook createWorkbook(ZipPackage pkg) throws IOException {
return createWorkbook((OPCPackage)pkg);
@@ -76,7 +82,6 @@ public class XSSFWorkbookFactory extends WorkbookFactory {
* @return The created Workbook
*
* @throws IOException if an error occurs while reading the data
- * @throws InvalidFormatException
*/
public static XSSFWorkbook createWorkbook(OPCPackage pkg) throws IOException {
try {
@@ -122,13 +127,11 @@ public class XSSFWorkbookFactory extends WorkbookFactory {
* @return The created Workbook
*
* @throws IOException if an error occurs while reading the data
- * @throws InvalidFormatException
+ * @throws InvalidFormatException if the package is not valid.
*/
@SuppressWarnings("resource")
public static XSSFWorkbook createWorkbook(InputStream stream) throws IOException, InvalidFormatException {
OPCPackage pkg = OPCPackage.open(stream);
return createWorkbook(pkg);
}
-
-
}
diff --git a/src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java b/src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java
index 32978df88c..878b536ec2 100644
--- a/src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java
+++ b/src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java
@@ -48,8 +48,8 @@ import org.junit.Test;
public final class TestWorkbookFactory {
private static final String xls = "SampleSS.xls";
private static final String xlsx = "SampleSS.xlsx";
- private static final String[] xls_prot = new String[] {"password.xls", "password"};
- private static final String[] xlsx_prot = new String[]{"protected_passtika.xlsx", "tika"};
+ private static final String[] xls_protected = new String[] {"password.xls", "password"};
+ private static final String[] xlsx_protected = new String[]{"protected_passtika.xlsx", "tika"};
private static final String txt = "SampleSS.txt";
private static final POILogger LOGGER = POILogFactory.getLogger(TestWorkbookFactory.class);
@@ -199,7 +199,6 @@ public final class TestWorkbookFactory {
public void testCreateWithPasswordFromStream() throws Exception {
Workbook wb;
-
// Unprotected, no password given, opens normally
wb = WorkbookFactory.create(
HSSFTestDataSamples.openSampleFileStream(xls), null
@@ -234,26 +233,26 @@ public final class TestWorkbookFactory {
// Protected, correct password, opens fine
wb = WorkbookFactory.create(
- HSSFTestDataSamples.openSampleFileStream(xls_prot[0]), xls_prot[1]
+ HSSFTestDataSamples.openSampleFileStream(xls_protected[0]), xls_protected[1]
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
- assertCloseDoesNotModifyFile(xls_prot[0], wb);
+ assertCloseDoesNotModifyFile(xls_protected[0], wb);
wb = WorkbookFactory.create(
- HSSFTestDataSamples.openSampleFileStream(xlsx_prot[0]), xlsx_prot[1]
+ HSSFTestDataSamples.openSampleFileStream(xlsx_protected[0]), xlsx_protected[1]
);
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
- assertCloseDoesNotModifyFile(xlsx_prot[0], wb);
+ assertCloseDoesNotModifyFile(xlsx_protected[0], wb);
// Protected, wrong password, throws Exception
try {
wb = WorkbookFactory.create(
- HSSFTestDataSamples.openSampleFileStream(xls_prot[0]), "wrong"
+ HSSFTestDataSamples.openSampleFileStream(xls_protected[0]), "wrong"
);
- assertCloseDoesNotModifyFile(xls_prot[0], wb);
+ assertCloseDoesNotModifyFile(xls_protected[0], wb);
fail("Shouldn't be able to open with the wrong password");
} catch (EncryptedDocumentException e) {
// expected here
@@ -261,9 +260,9 @@ public final class TestWorkbookFactory {
try {
wb = WorkbookFactory.create(
- HSSFTestDataSamples.openSampleFileStream(xlsx_prot[0]), "wrong"
+ HSSFTestDataSamples.openSampleFileStream(xlsx_protected[0]), "wrong"
);
- assertCloseDoesNotModifyFile(xlsx_prot[0], wb);
+ assertCloseDoesNotModifyFile(xlsx_protected[0], wb);
fail("Shouldn't be able to open with the wrong password");
} catch (EncryptedDocumentException e) {
// expected here
@@ -309,28 +308,28 @@ public final class TestWorkbookFactory {
// Protected, correct password, opens fine
wb = WorkbookFactory.create(
- HSSFTestDataSamples.getSampleFile(xls_prot[0]), xls_prot[1]
+ HSSFTestDataSamples.getSampleFile(xls_protected[0]), xls_protected[1]
);
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
- assertCloseDoesNotModifyFile(xls_prot[0], wb);
+ assertCloseDoesNotModifyFile(xls_protected[0], wb);
wb = WorkbookFactory.create(
- HSSFTestDataSamples.getSampleFile(xlsx_prot[0]), xlsx_prot[1]
+ HSSFTestDataSamples.getSampleFile(xlsx_protected[0]), xlsx_protected[1]
);
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertTrue(wb.getNumberOfSheets() > 0);
assertNotNull(wb.getSheetAt(0));
assertNotNull(wb.getSheetAt(0).getRow(0));
- assertCloseDoesNotModifyFile(xlsx_prot[0], wb);
+ assertCloseDoesNotModifyFile(xlsx_protected[0], wb);
// Protected, wrong password, throws Exception
try {
wb = WorkbookFactory.create(
- HSSFTestDataSamples.getSampleFile(xls_prot[0]), "wrong"
+ HSSFTestDataSamples.getSampleFile(xls_protected[0]), "wrong"
);
- assertCloseDoesNotModifyFile(xls_prot[0], wb);
+ assertCloseDoesNotModifyFile(xls_protected[0], wb);
fail("Shouldn't be able to open with the wrong password");
} catch (EncryptedDocumentException e) {
// expected here
@@ -338,9 +337,9 @@ public final class TestWorkbookFactory {
try {
wb = WorkbookFactory.create(
- HSSFTestDataSamples.getSampleFile(xlsx_prot[0]), "wrong"
+ HSSFTestDataSamples.getSampleFile(xlsx_protected[0]), "wrong"
);
- assertCloseDoesNotModifyFile(xlsx_prot[0], wb);
+ assertCloseDoesNotModifyFile(xlsx_protected[0], wb);
fail("Shouldn't be able to open with the wrong password");
} catch (EncryptedDocumentException e) {
// expected here
@@ -397,22 +396,22 @@ public final class TestWorkbookFactory {
*/
@Test
public void testFileSubclass() throws Exception {
- Workbook wb;
-
File normalXLS = HSSFTestDataSamples.getSampleFile(xls);
File normalXLSX = HSSFTestDataSamples.getSampleFile(xlsx);
File altXLS = new TestFile(normalXLS.getAbsolutePath());
File altXLSX = new TestFile(normalXLSX.getAbsolutePath());
assertTrue(altXLS.exists());
assertTrue(altXLSX.exists());
-
- wb = WorkbookFactory.create(altXLS);
- assertNotNull(wb);
- assertTrue(wb instanceof HSSFWorkbook);
-
- wb = WorkbookFactory.create(altXLSX);
- assertNotNull(wb);
- assertTrue(wb instanceof XSSFWorkbook);
+
+ try (Workbook wb = WorkbookFactory.create(altXLS)) {
+ assertNotNull(wb);
+ assertTrue(wb instanceof HSSFWorkbook);
+ }
+
+ try (Workbook wb = WorkbookFactory.create(altXLSX)) {
+ assertNotNull(wb);
+ assertTrue(wb instanceof XSSFWorkbook);
+ }
}
private static class TestFile extends File {
@@ -420,4 +419,18 @@ public final class TestWorkbookFactory {
super(file);
}
}
+
+ /**
+ * Check that the overloaded file methods which take passwords work properly
+ */
+ @Test
+ public void testCreateEmpty() throws Exception {
+ try (Workbook wb = WorkbookFactory.create(false)) {
+ assertTrue(wb instanceof HSSFWorkbook);
+ }
+
+ try (Workbook wb = WorkbookFactory.create(true)) {
+ assertTrue(wb instanceof XSSFWorkbook);
+ }
+ }
}
--
cgit v1.2.3
From af9142e4b744638fa448f81081a7cda1bc376576 Mon Sep 17 00:00:00 2001
From: Tim Allison
Date: Fri, 26 Oct 2018 19:06:18 +0000
Subject: bug 62859 -- fix two potential NPEs when initializing XWPFSDTContent
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1844920 13f79535-47bb-0310-9956-ffa450edef68
---
.../org/apache/poi/xwpf/usermodel/XWPFSDTContent.java | 6 ++++++
src/ooxml/testcases/org/apache/poi/sl/TestFonts.java | 2 +-
.../org/apache/poi/xwpf/usermodel/TestXWPFSDT.java | 13 +++++++++++++
test-data/document/Bug62859.docx | Bin 0 -> 17326 bytes
4 files changed, 20 insertions(+), 1 deletion(-)
create mode 100644 test-data/document/Bug62859.docx
(limited to 'src/ooxml/java')
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java
index 99ab66a7ee..f39c5cf482 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java
@@ -47,6 +47,9 @@ public class XWPFSDTContent implements ISDTContent {
private List bodyElements = new ArrayList<>();
public XWPFSDTContent(CTSdtContentRun sdtRun, IBody part, IRunBody parent) {
+ if (sdtRun == null) {
+ return;
+ }
for (CTR ctr : sdtRun.getRArray()) {
XWPFRun run = new XWPFRun(ctr, parent);
// runs.add(run);
@@ -55,6 +58,9 @@ public class XWPFSDTContent implements ISDTContent {
}
public XWPFSDTContent(CTSdtContentBlock block, IBody part, IRunBody parent) {
+ if (block == null) {
+ return;
+ }
XmlCursor cursor = block.newCursor();
cursor.selectPath("./*");
while (cursor.toNextSelection()) {
diff --git a/src/ooxml/testcases/org/apache/poi/sl/TestFonts.java b/src/ooxml/testcases/org/apache/poi/sl/TestFonts.java
index b7a6d16a54..f35065de75 100644
--- a/src/ooxml/testcases/org/apache/poi/sl/TestFonts.java
+++ b/src/ooxml/testcases/org/apache/poi/sl/TestFonts.java
@@ -74,7 +74,7 @@ public class TestFonts {
// currently linux and mac return quite different values
private static final int[] expected_sizes = {
304, // windows 10, 1080p, MS Office 2016, system text scaling 100% instead of default 125%
- 306, // Windows 10, 15.6" 3840x2160
+ 306, 308,// Windows 10, 15.6" 3840x2160
311, 312, 313, 318,
348, // Windows 10, 15.6" 3840x2160
362, // Windows 10, 13.3" 1080p high-dpi
diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java
index deac5c09ae..9388e08710 100644
--- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java
+++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java
@@ -148,6 +148,19 @@ public final class TestXWPFSDT {
assertEquals("", sdts.get(0).getTitle());
}
+ @Test
+ public void test62859() throws IOException {
+ //this doesn't test the exact code path for this issue, but
+ //it does test for a related issue, and the fix fixes both.
+ //We should try to add the actual triggering document
+ //to our test suite.
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug62859.docx");
+ List sdts = extractAllSDTs(doc);
+ assertEquals(1, sdts.size());
+ assertEquals("", sdts.get(0).getTag());
+ assertEquals("", sdts.get(0).getTitle());
+ }
+
private List extractAllSDTs(XWPFDocument doc) {
List sdts = new ArrayList<>();
diff --git a/test-data/document/Bug62859.docx b/test-data/document/Bug62859.docx
new file mode 100644
index 0000000000..e0ede4a83d
Binary files /dev/null and b/test-data/document/Bug62859.docx differ
--
cgit v1.2.3
From d7649a2831b5507edf3c94c55c2a7a8878bccfad Mon Sep 17 00:00:00 2001
From: Dominik Stadler
Date: Thu, 1 Nov 2018 10:29:54 +0000
Subject: IDE warnings, tried to reproduce Bug 58927, but could not
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1845434 13f79535-47bb-0310-9956-ffa450edef68
---
src/java/org/apache/poi/ss/util/CellReference.java | 14 +--
.../org/apache/poi/xssf/usermodel/XSSFSheet.java | 121 +++++++++------------
.../poi/xssf/usermodel/helpers/ColumnHelper.java | 4 +-
.../xssf/usermodel/helpers/TestColumnHelper.java | 49 +++++++--
4 files changed, 101 insertions(+), 87 deletions(-)
(limited to 'src/ooxml/java')
diff --git a/src/java/org/apache/poi/ss/util/CellReference.java b/src/java/org/apache/poi/ss/util/CellReference.java
index d14670221f..3ef32e30f6 100644
--- a/src/java/org/apache/poi/ss/util/CellReference.java
+++ b/src/java/org/apache/poi/ss/util/CellReference.java
@@ -132,7 +132,7 @@ public class CellReference {
if (rowRef.length() == 0) {
_rowIndex = -1;
} else {
- // throws NumberFormatException if rowRef is not convertable to an int
+ // throws NumberFormatException if rowRef is not convertible to an int
_rowIndex = Integer.parseInt(rowRef)-1; // -1 to convert 1-based to zero-based
}
}
@@ -336,10 +336,10 @@ public class CellReference {
if(colStr.toUpperCase(Locale.ROOT).compareTo(lastCol) > 0) {
return false;
}
- } else {
+ } /*else {
// apparent column name has less chars than max
// no need to check range
- }
+ }*/
return true;
}
@@ -426,7 +426,7 @@ public class CellReference {
// AreaReference.separateAreaRefs()
// SheetNameFormatter.format() (inverse)
- StringBuffer sb = new StringBuffer(indexOfSheetNameDelimiter);
+ StringBuilder sb = new StringBuilder(indexOfSheetNameDelimiter);
for(int i=1; i
*/
+@SuppressWarnings("deprecation")
public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
private static final POILogger logger = POILogFactory.getLogger(XSSFSheet.class);
@@ -472,7 +473,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
/**
* Verify that candidate region does not intersect with an existing merged region in this sheet
*
- * @param candidateRegion
+ * @param candidateRegion the range of cells to verify
* @throws IllegalStateException if candidate region intersects an existing merged region in this sheet (or candidateRegion is already merged in this sheet)
*/
private void validateMergedRegions(CellRangeAddress candidateRegion) {
@@ -855,8 +856,8 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
/**
* Get a Hyperlink in this sheet anchored at row, column
*
- * @param row
- * @param column
+ * @param row The row where the hyperlink is anchored
+ * @param column The column where the hyperlinkn is anchored
* @return hyperlink if there is a hyperlink anchored at row, column; otherwise returns null
*/
@Override
@@ -1480,8 +1481,9 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*
* @param startRowNum the first row number in this sheet to return
* @param endRowNum the last row number in this sheet to return
- * @param createRowIfMissing
- * @return All rows between startRow and endRow, inclusive
+ * @param createRowIfMissing If missing rows should be created.
+ * @return All rows between startRow and endRow, inclusive. If createRowIfMissing is false,
+ * only previously existing rows are returned, otherwise empty rows are added as necessary
* @throws IllegalArgumentException if startRowNum and endRowNum are not in ascending order
*/
private List getRows(int startRowNum, int endRowNum, boolean createRowIfMissing) {
@@ -2472,7 +2474,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* 'Collapsed' state is stored in a single column col info record
* immediately after the outline group
*
- * @param idx
+ * @param idx The column-index to check
* @return a boolean represented if the column is collapsed
*/
private boolean isColumnGroupCollapsed(int idx) {
@@ -3052,7 +3054,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
rebuildRows();
}
- private final void rebuildRows() {
+ private void rebuildRows() {
//rebuild the _rows map
List rowList = new ArrayList<>(_rows.values());
_rows.clear();
@@ -3114,25 +3116,22 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
// then do the actual moving and also adjust comments/rowHeight
// we need to sort it in a way so the shifting does not mess up the structures,
// i.e. when shifting down, start from down and go up, when shifting up, vice-versa
- SortedMap commentsToShift = new TreeMap<>(new Comparator() {
- @Override
- public int compare(XSSFComment o1, XSSFComment o2) {
- int row1 = o1.getRow();
- int row2 = o2.getRow();
-
- if (row1 == row2) {
- // ordering is not important when row is equal, but don't return zero to still
- // get multiple comments per row into the map
- return o1.hashCode() - o2.hashCode();
- }
+ SortedMap commentsToShift = new TreeMap<>((o1, o2) -> {
+ int row1 = o1.getRow();
+ int row2 = o2.getRow();
+
+ if (row1 == row2) {
+ // ordering is not important when row is equal, but don't return zero to still
+ // get multiple comments per row into the map
+ return o1.hashCode() - o2.hashCode();
+ }
- // when shifting down, sort higher row-values first
- if (n > 0) {
- return row1 < row2 ? 1 : -1;
- } else {
- // sort lower-row values first when shifting up
- return row1 > row2 ? 1 : -1;
- }
+ // when shifting down, sort higher row-values first
+ if (n > 0) {
+ return row1 < row2 ? 1 : -1;
+ } else {
+ // sort lower-row values first when shifting up
+ return row1 > row2 ? 1 : -1;
}
});
@@ -3211,25 +3210,22 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
// then do the actual moving and also adjust comments/rowHeight
// we need to sort it in a way so the shifting does not mess up the structures,
// i.e. when shifting down, start from down and go up, when shifting up, vice-versa
- SortedMap commentsToShift = new TreeMap<>(new Comparator() {
- @Override
- public int compare(XSSFComment o1, XSSFComment o2) {
- int column1 = o1.getColumn();
- int column2 = o2.getColumn();
-
- if (column1 == column2) {
- // ordering is not important when row is equal, but don't return zero to still
- // get multiple comments per row into the map
- return o1.hashCode() - o2.hashCode();
- }
+ SortedMap commentsToShift = new TreeMap<>((o1, o2) -> {
+ int column1 = o1.getColumn();
+ int column2 = o2.getColumn();
+
+ if (column1 == column2) {
+ // ordering is not important when row is equal, but don't return zero to still
+ // get multiple comments per row into the map
+ return o1.hashCode() - o2.hashCode();
+ }
- // when shifting down, sort higher row-values first
- if (n > 0) {
- return column1 < column2 ? 1 : -1;
- } else {
- // sort lower-row values first when shifting up
- return column1 > column2 ? 1 : -1;
- }
+ // when shifting down, sort higher row-values first
+ if (n > 0) {
+ return column1 < column2 ? 1 : -1;
+ } else {
+ // sort lower-row values first when shifting up
+ return column1 > column2 ? 1 : -1;
}
});
@@ -4096,7 +4092,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* Creates a new Table, and associates it with this Sheet.
*
* @param tableArea
- * the area that the table should cover, should not be {@null}
+ * the area that the table should cover, should not be null
* @return the created table
* @since 4.0.0
*/
@@ -4421,18 +4417,15 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
+ "defined source sheet " + sourceSheet.getSheetName() + ".");
}
- return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() {
- @Override
- public void configureReference(CTWorksheetSource wsSource) {
- final String[] firstCell = source.getFirstCell().getCellRefParts();
- final String firstRow = firstCell[1];
- final String firstCol = firstCell[2];
- final String[] lastCell = source.getLastCell().getCellRefParts();
- final String lastRow = lastCell[1];
- final String lastCol = lastCell[2];
- final String ref = firstCol+firstRow+':'+lastCol+lastRow; //or just source.formatAsString()
- wsSource.setRef(ref);
- }
+ return createPivotTable(position, sourceSheet, wsSource -> {
+ final String[] firstCell = source.getFirstCell().getCellRefParts();
+ final String firstRow = firstCell[1];
+ final String firstCol = firstCell[2];
+ final String[] lastCell = source.getLastCell().getCellRefParts();
+ final String lastRow = lastCell[1];
+ final String lastCol = lastCell[2];
+ final String ref = firstCol+firstRow+':'+lastCol+lastRow; //or just source.formatAsString()
+ wsSource.setRef(ref);
});
}
@@ -4494,12 +4487,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
+ "defined source sheet " + sourceSheet.getSheetName() + ".");
}
- return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() {
- @Override
- public void configureReference(CTWorksheetSource wsSource) {
- wsSource.setName(source.getNameName());
- }
- });
+ return createPivotTable(position, sourceSheet, wsSource -> wsSource.setName(source.getNameName()));
}
/**
@@ -4523,12 +4511,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/
@Beta
public XSSFPivotTable createPivotTable(final Table source, CellReference position) {
- return createPivotTable(position, getWorkbook().getSheet(source.getSheetName()), new PivotTableReferenceConfigurator() {
- @Override
- public void configureReference(CTWorksheetSource wsSource) {
- wsSource.setName(source.getName());
- }
- });
+ return createPivotTable(position, getWorkbook().getSheet(source.getSheetName()), wsSource -> wsSource.setName(source.getName()));
}
/**
@@ -4621,7 +4604,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
/**
* when a cell with a 'master' shared formula is removed, the next cell in the range becomes the master
- * @param cell
+ * @param cell The cell that is removed
* @param evalWb BaseXSSFEvaluationWorkbook in use, if one exists
*/
protected void onDeleteFormula(XSSFCell cell, BaseXSSFEvaluationWorkbook evalWb){
diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java
index 0aa7720867..f65856ea69 100644
--- a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java
+++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java
@@ -50,7 +50,7 @@ public class ColumnHelper {
TreeSet trackedCols = new TreeSet<>(CTColComparator.BY_MIN_MAX);
CTCols newCols = CTCols.Factory.newInstance();
CTCols[] colsArray = worksheet.getColsArray();
- int i = 0;
+ int i;
for (i = 0; i < colsArray.length; i++) {
CTCols cols = colsArray[i];
for (CTCol col : cols.getColList()) {
@@ -61,7 +61,7 @@ public class ColumnHelper {
worksheet.removeCols(y);
}
- newCols.setColArray(trackedCols.toArray(new CTCol[trackedCols.size()]));
+ newCols.setColArray(trackedCols.toArray(new CTCol[0]));
worksheet.addNewCols();
worksheet.setColsArray(0, newCols);
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java
index 5ba7ad1d03..9686dcf6a1 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java
@@ -25,6 +25,9 @@ import static org.junit.Assert.assertTrue;
import java.io.IOException;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
@@ -192,14 +195,14 @@ public final class TestColumnHelper {
}
@Test
- public void testAddCleanColIntoColsExactOverlap() throws Exception {
+ public void testAddCleanColIntoColsExactOverlap() {
CTCols cols = createHiddenAndBestFitColsWithHelper(1, 1, 1, 1);
assertEquals(1, cols.sizeOfColArray());
assertMinMaxHiddenBestFit(cols, 0, 1, 1, true, true);
}
@Test
- public void testAddCleanColIntoColsOverlapsOverhangingBothSides() throws Exception {
+ public void testAddCleanColIntoColsOverlapsOverhangingBothSides() {
CTCols cols = createHiddenAndBestFitColsWithHelper(2, 2, 1, 3);
assertEquals(3, cols.sizeOfColArray());
assertMinMaxHiddenBestFit(cols, 0, 1, 1, false, true);
@@ -208,7 +211,7 @@ public final class TestColumnHelper {
}
@Test
- public void testAddCleanColIntoColsOverlapsCompletelyNested() throws Exception {
+ public void testAddCleanColIntoColsOverlapsCompletelyNested() {
CTCols cols = createHiddenAndBestFitColsWithHelper(1, 3, 2, 2);
assertEquals(3, cols.sizeOfColArray());
assertMinMaxHiddenBestFit(cols, 0, 1, 1, true, false);
@@ -217,7 +220,7 @@ public final class TestColumnHelper {
}
@Test
- public void testAddCleanColIntoColsNewOverlapsOverhangingLeftNotRightExactRight() throws Exception {
+ public void testAddCleanColIntoColsNewOverlapsOverhangingLeftNotRightExactRight() {
CTCols cols = createHiddenAndBestFitColsWithHelper(2, 3, 1, 3);
assertEquals(2, cols.sizeOfColArray());
assertMinMaxHiddenBestFit(cols, 0, 1, 1, false, true);
@@ -225,7 +228,7 @@ public final class TestColumnHelper {
}
@Test
- public void testAddCleanColIntoColsNewOverlapsOverhangingRightNotLeftExactLeft() throws Exception {
+ public void testAddCleanColIntoColsNewOverlapsOverhangingRightNotLeftExactLeft() {
CTCols cols = createHiddenAndBestFitColsWithHelper(1, 2, 1, 3);
assertEquals(2, cols.sizeOfColArray());
assertMinMaxHiddenBestFit(cols, 0, 1, 2, true, true);
@@ -233,7 +236,7 @@ public final class TestColumnHelper {
}
@Test
- public void testAddCleanColIntoColsNewOverlapsOverhangingLeftNotRight() throws Exception {
+ public void testAddCleanColIntoColsNewOverlapsOverhangingLeftNotRight() {
CTCols cols = createHiddenAndBestFitColsWithHelper(2, 3, 1, 2);
assertEquals(3, cols.sizeOfColArray());
assertMinMaxHiddenBestFit(cols, 0, 1, 1, false, true);
@@ -242,7 +245,7 @@ public final class TestColumnHelper {
}
@Test
- public void testAddCleanColIntoColsNewOverlapsOverhangingRightNotLeft() throws Exception {
+ public void testAddCleanColIntoColsNewOverlapsOverhangingRightNotLeft() {
CTCols cols = createHiddenAndBestFitColsWithHelper(1, 2, 2, 3);
assertEquals(3, cols.sizeOfColArray());
assertMinMaxHiddenBestFit(cols, 0, 1, 1, true, false);
@@ -402,4 +405,36 @@ public final class TestColumnHelper {
}
return count;
}
+
+ @SuppressWarnings("deprecation")
+ @Test
+ public void testColumnsCollapsed() {
+ Workbook wb = new XSSFWorkbook();
+ Sheet sheet = wb.createSheet("test");
+ Row row = sheet.createRow(0);
+ row.createCell(0);
+ row.createCell(1);
+ row.createCell(2);
+
+ sheet.setColumnWidth(0, 10);
+ sheet.setColumnWidth(1, 10);
+ sheet.setColumnWidth(2, 10);
+
+ sheet.groupColumn(0, 1);
+ sheet.setColumnGroupCollapsed(0, true);
+
+ CTCols ctCols = ((XSSFSheet) sheet).getCTWorksheet().getColsArray()[0];
+ assertEquals(3, ctCols.sizeOfColArray());
+ assertTrue(ctCols.getColArray(0).isSetCollapsed());
+ assertTrue(ctCols.getColArray(1).isSetCollapsed());
+ assertTrue(ctCols.getColArray(2).isSetCollapsed());
+
+ ColumnHelper helper = new ColumnHelper(CTWorksheet.Factory.newInstance());
+ helper.setColumnAttributes(ctCols.getColArray(1), ctCols.getColArray(2));
+
+ ctCols = ((XSSFSheet) sheet).getCTWorksheet().getColsArray()[0];
+ assertTrue(ctCols.getColArray(0).isSetCollapsed());
+ assertTrue(ctCols.getColArray(1).isSetCollapsed());
+ assertTrue(ctCols.getColArray(2).isSetCollapsed());
+ }
}
--
cgit v1.2.3
From 341f456ef7868db6c518cdcb0570dd9c43b41472 Mon Sep 17 00:00:00 2001
From: Tim Allison
Date: Thu, 1 Nov 2018 21:14:03 +0000
Subject: bug 60316 -- until we can implement it properly, gracefully skip the
glossary document in XWPF.
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1845517 13f79535-47bb-0310-9956-ffa450edef68
---
.../java/org/apache/poi/ooxml/POIXMLDocumentPart.java | 9 +++++++++
.../poi/xwpf/extractor/TestXWPFWordExtractor.java | 11 +++++++++++
test-data/document/60316.dotx | Bin 0 -> 59583 bytes
3 files changed, 20 insertions(+)
create mode 100644 test-data/document/60316.dotx
(limited to 'src/ooxml/java')
diff --git a/src/ooxml/java/org/apache/poi/ooxml/POIXMLDocumentPart.java b/src/ooxml/java/org/apache/poi/ooxml/POIXMLDocumentPart.java
index 5a368c576a..54fa790eca 100644
--- a/src/ooxml/java/org/apache/poi/ooxml/POIXMLDocumentPart.java
+++ b/src/ooxml/java/org/apache/poi/ooxml/POIXMLDocumentPart.java
@@ -42,6 +42,7 @@ import org.apache.poi.util.POILogger;
import org.apache.poi.xddf.usermodel.chart.XDDFChart;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.apache.poi.xwpf.usermodel.XWPFRelation;
/**
* Represents an entry of a OOXML package.
@@ -613,6 +614,14 @@ public class POIXMLDocumentPart {
*/
protected void read(POIXMLFactory factory, Map context) throws OpenXML4JException {
PackagePart pp = getPackagePart();
+
+ if (pp.getContentType().equals(XWPFRelation.TEMPLATE.getContentType())) {
+ logger.log(POILogger.WARN,
+ "POI does not currently support template.main+xml (glossary) parts. " +
+ "Skipping this part for now.");
+ return;
+ }
+
// add mapping a second time, in case of initial caller hasn't done so
POIXMLDocumentPart otherChild = context.put(pp, this);
if (otherChild != null && otherChild != this) {
diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java
index d51750e922..0fcccd1838 100644
--- a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java
+++ b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java
@@ -29,6 +29,7 @@ import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import static org.apache.poi.POITestCase.assertContains;
import static org.apache.poi.POITestCase.assertEndsWith;
+import static org.apache.poi.POITestCase.assertNotContained;
import static org.apache.poi.POITestCase.assertStartsWith;
/**
@@ -441,4 +442,14 @@ public class TestXWPFWordExtractor extends TestCase {
assertContains(txt, "Sequencing data");
extractor.close();
}
+
+ public void testGlossary() throws IOException {
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("60316.dotx");
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ String txt = extractor.getText();
+ assertContains(txt, "Getting the perfect");
+ //this content appears only in the glossary document
+ //once we add processing for this, we can change this to contains
+ assertNotContained(txt, "table rows");
+ }
}
diff --git a/test-data/document/60316.dotx b/test-data/document/60316.dotx
new file mode 100644
index 0000000000..5d24a7848c
Binary files /dev/null and b/test-data/document/60316.dotx differ
--
cgit v1.2.3