From d3899d47447f60bf589c8812371a9d38097cb278 Mon Sep 17 00:00:00 2001 From: PJ Fanning Date: Sat, 22 May 2021 20:22:16 +0000 Subject: [PATCH] convert tabs to spaces git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1890119 13f79535-47bb-0310-9956-ffa450edef68 --- .../ooxml/extractor/POIXMLTextExtractor.java | 118 +- .../poi/ooxml/util/IdentifierManager.java | 8 +- .../exceptions/InvalidFormatException.java | 6 +- .../exceptions/InvalidOperationException.java | 10 +- .../exceptions/OpenXML4JException.java | 6 +- .../exceptions/OpenXML4JRuntimeException.java | 6 +- .../PartAlreadyExistsException.java | 6 +- .../opc/CertificateEmbeddingOption.java | 12 +- .../poi/openxml4j/opc/ContentTypes.java | 162 +- .../apache/poi/openxml4j/opc/OPCPackage.java | 2512 ++++++++--------- .../poi/openxml4j/opc/PackageNamespaces.java | 40 +- .../openxml4j/opc/PackagePartCollection.java | 102 +- .../poi/openxml4j/opc/PackagePartName.java | 732 ++--- .../openxml4j/opc/PackageRelationship.java | 296 +- .../poi/openxml4j/opc/RelationshipSource.java | 244 +- .../poi/openxml4j/opc/StreamHelper.java | 122 +- .../apache/poi/openxml4j/opc/TargetMode.java | 4 +- .../apache/poi/openxml4j/opc/ZipPackage.java | 204 +- .../poi/openxml4j/opc/ZipPackagePart.java | 194 +- .../openxml4j/opc/internal/ContentType.java | 354 +-- .../opc/internal/MemoryPackagePart.java | 168 +- .../MemoryPackagePartOutputStream.java | 108 +- .../opc/internal/PartMarshaller.java | 28 +- .../opc/internal/PartUnmarshaller.java | 20 +- .../opc/internal/ZipContentTypeManager.java | 64 +- .../marshallers/DefaultMarshaller.java | 28 +- .../ZipPackagePropertiesMarshaller.java | 50 +- .../marshallers/ZipPartMarshaller.java | 238 +- .../PackagePropertiesUnmarshaller.java | 288 +- .../unmarshallers/UnmarshallContext.java | 108 +- .../poi/openxml4j/util/ZipEntrySource.java | 58 +- .../util/ZipInputStreamZipEntrySource.java | 102 +- .../usermodel/chart/XDDFManualLayout.java | 4 +- .../poi/xslf/usermodel/XSLFComment.java | 2 +- .../poi/xslf/usermodel/XSLFGraphicFrame.java | 24 +- .../apache/poi/xslf/usermodel/XSLFNotes.java | 2 +- .../poi/xslf/usermodel/XSLFNotesMaster.java | 2 +- .../poi/xslf/usermodel/XSLFSlideMaster.java | 8 +- .../poi/xslf/usermodel/XSLFSlideShow.java | 354 +-- .../apache/poi/xslf/usermodel/XSLFTable.java | 72 +- .../poi/xslf/usermodel/XSLFTextParagraph.java | 14 +- .../apache/poi/xslf/usermodel/XSLFTheme.java | 2 +- .../poi/xssf/XLSBUnsupportedException.java | 4 +- .../poi/xssf/extractor/XSSFExportToXml.java | 10 +- .../org/apache/poi/xssf/model/MapInfo.java | 150 +- .../apache/poi/xssf/model/SingleXmlCells.java | 98 +- .../xssf/streaming/GZIPSheetDataWriter.java | 6 +- .../xssf/streaming/SXSSFFormulaEvaluator.java | 4 +- .../poi/xssf/streaming/SXSSFPicture.java | 2 +- .../poi/xssf/usermodel/TextFontAlign.java | 8 +- .../XSSFDataValidationConstraint.java | 386 +-- .../usermodel/XSSFDataValidationHelper.java | 234 +- .../xssf/usermodel/XSSFEvaluationCell.java | 142 +- .../poi/xssf/usermodel/XSSFEvenFooter.java | 16 +- .../poi/xssf/usermodel/XSSFFirstFooter.java | 16 +- .../poi/xssf/usermodel/XSSFFirstHeader.java | 16 +- .../poi/xssf/usermodel/XSSFGraphicFrame.java | 246 +- .../usermodel/XSSFHeaderFooterProperties.java | 108 +- .../poi/xssf/usermodel/XSSFHyperlink.java | 2 +- .../poi/xssf/usermodel/XSSFOddFooter.java | 10 +- .../poi/xssf/usermodel/XSSFOddHeader.java | 10 +- .../poi/xssf/usermodel/XSSFPivotCache.java | 2 +- .../usermodel/XSSFPivotCacheDefinition.java | 2 +- .../xssf/usermodel/XSSFPivotCacheRecords.java | 2 +- .../poi/xssf/usermodel/XSSFPivotTable.java | 2 +- .../XSSFSheetConditionalFormatting.java | 20 +- .../poi/xssf/usermodel/XSSFTextRun.java | 2 +- .../extensions/XSSFCellAlignment.java | 4 +- .../extensions/XSSFHeaderFooter.java | 196 +- .../usermodel/helpers/HeaderFooterHelper.java | 118 +- .../usermodel/helpers/XSSFSingleXmlCell.java | 70 +- .../xwpf/model/XWPFHeaderFooterPolicy.java | 4 +- .../poi/xwpf/usermodel/XWPFSettings.java | 4 +- .../apache/poi/ooxml/TestDetectAsOOXML.java | 36 +- .../org/apache/poi/ooxml/TestEmbedded.java | 52 +- .../ooxml/TestXMLPropertiesTextExtractor.java | 114 +- .../openxml4j/OpenXML4JTestDataSamples.java | 30 +- .../poi/openxml4j/opc/TestFileHelper.java | 40 +- .../poi/openxml4j/opc/TestListParts.java | 120 +- .../apache/poi/openxml4j/opc/TestPackage.java | 1410 ++++----- .../opc/TestPackageCoreProperties.java | 150 +- .../openxml4j/opc/TestPackagePartName.java | 20 +- .../openxml4j/opc/TestPackageThumbnail.java | 46 +- .../poi/openxml4j/opc/TestRelationships.java | 116 +- .../poifs/crypt/dsig/TestSignatureInfo.java | 24 +- .../eval/TestXSSFCircularReferences.java | 2 +- .../apache/poi/xslf/TestXSLFSlideShow.java | 128 +- .../TestXSLFPowerPointExtractor.java | 18 +- .../poi/xslf/usermodel/TestXSLFChart.java | 188 +- .../apache/poi/xssf/TestSheetProtection.java | 424 +-- .../TestReadOnlySharedStringsTable.java | 8 +- .../xssf/eventusermodel/TestXSSFReader.java | 34 +- .../TestXSSFBEventBasedExcelExtractor.java | 8 +- .../TestXSSFEventBasedExcelExtractor.java | 250 +- ...FEventBasedExcelExtractorUsingFactory.java | 18 +- .../extractor/TestXSSFExcelExtractor.java | 288 +- .../TestXSSFExcelExtractorUsingFactory.java | 20 +- .../poi/xssf/streaming/TestOutlining.java | 80 +- .../poi/xssf/streaming/TestSXSSFWorkbook.java | 148 +- .../xssf/streaming/TestSheetDataWriter.java | 4 +- .../usermodel/TestFormulaEvaluatorOnXSSF.java | 180 +- .../TestMultiSheetFormulaEvaluatorOnXSSF.java | 154 +- .../poi/xssf/usermodel/TestXSSFBugs.java | 2 +- .../poi/xssf/usermodel/TestXSSFCell.java | 46 +- .../poi/xssf/usermodel/TestXSSFCellStyle.java | 272 +- .../poi/xssf/usermodel/TestXSSFChart.java | 6 +- .../xssf/usermodel/TestXSSFColGrouping.java | 28 +- .../poi/xssf/usermodel/TestXSSFComment.java | 2 +- .../xssf/usermodel/TestXSSFDataFormat.java | 8 +- .../usermodel/TestXSSFDataValidation.java | 6 +- .../xssf/usermodel/TestXSSFDialogSheet.java | 8 +- .../poi/xssf/usermodel/TestXSSFDrawing.java | 26 +- .../usermodel/TestXSSFExternalFunctions.java | 6 +- .../poi/xssf/usermodel/TestXSSFFont.java | 672 ++--- .../usermodel/charts/TestXDDFChartLegend.java | 46 +- .../charts/TestXDDFManualLayout.java | 64 +- .../charts/TestXSSFCategoryAxis.java | 26 +- .../usermodel/charts/TestXSSFChartAxis.java | 196 +- .../usermodel/charts/TestXSSFChartTitle.java | 4 +- .../usermodel/charts/TestXSSFDateAxis.java | 26 +- .../charts/TestXSSFScatterChartData.java | 4 +- .../usermodel/charts/TestXSSFValueAxis.java | 30 +- .../usermodel/extensions/TestXSSFBorder.java | 34 +- .../poi/xwpf/TestDocumentProtection.java | 2 +- .../poi/xwpf/usermodel/TestXWPFDocument.java | 20 +- .../poi/xwpf/usermodel/TestXWPFHeadings.java | 24 +- 126 files changed, 7222 insertions(+), 7222 deletions(-) diff --git a/poi-ooxml/src/main/java/org/apache/poi/ooxml/extractor/POIXMLTextExtractor.java b/poi-ooxml/src/main/java/org/apache/poi/ooxml/extractor/POIXMLTextExtractor.java index eb235fa6aa..6b9106dc60 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/ooxml/extractor/POIXMLTextExtractor.java +++ b/poi-ooxml/src/main/java/org/apache/poi/ooxml/extractor/POIXMLTextExtractor.java @@ -28,72 +28,72 @@ import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.util.ZipSecureFile; public interface POIXMLTextExtractor extends POITextExtractor { - /** - * Returns the core document properties - * - * @return the core document properties - */ - default CoreProperties getCoreProperties() { - return getDocument().getProperties().getCoreProperties(); - } - /** - * Returns the extended document properties - * - * @return the extended document properties - */ - default ExtendedProperties getExtendedProperties() { - return getDocument().getProperties().getExtendedProperties(); - } - /** - * Returns the custom document properties - * - * @return the custom document properties - */ - default CustomProperties getCustomProperties() { - return getDocument().getProperties().getCustomProperties(); - } + /** + * Returns the core document properties + * + * @return the core document properties + */ + default CoreProperties getCoreProperties() { + return getDocument().getProperties().getCoreProperties(); + } + /** + * Returns the extended document properties + * + * @return the extended document properties + */ + default ExtendedProperties getExtendedProperties() { + return getDocument().getProperties().getExtendedProperties(); + } + /** + * Returns the custom document properties + * + * @return the custom document properties + */ + default CustomProperties getCustomProperties() { + return getDocument().getProperties().getCustomProperties(); + } - /** - * Returns opened document - * - * @return the opened document - */ - @Override - POIXMLDocument getDocument(); + /** + * Returns opened document + * + * @return the opened document + */ + @Override + POIXMLDocument getDocument(); - /** - * Returns the opened OPCPackage that contains the document - * - * @return the opened OPCPackage - */ - default OPCPackage getPackage() { - POIXMLDocument doc = getDocument(); - return doc != null ? doc.getPackage() : null; - } + /** + * Returns the opened OPCPackage that contains the document + * + * @return the opened OPCPackage + */ + default OPCPackage getPackage() { + POIXMLDocument doc = getDocument(); + return doc != null ? doc.getPackage() : null; + } - /** - * Returns an OOXML properties text extractor for the - * document properties metadata, such as title and author. - */ - @Override + /** + * Returns an OOXML properties text extractor for the + * document properties metadata, such as title and author. + */ + @Override default POIXMLPropertiesTextExtractor getMetadataTextExtractor() { - return new POIXMLPropertiesTextExtractor(getDocument()); - } + return new POIXMLPropertiesTextExtractor(getDocument()); + } - @Override - default void close() throws IOException { - // e.g. XSSFEventBaseExcelExtractor passes a null-document - if (isCloseFilesystem()) { - @SuppressWarnings("resource") + @Override + default void close() throws IOException { + // e.g. XSSFEventBaseExcelExtractor passes a null-document + if (isCloseFilesystem()) { + @SuppressWarnings("resource") OPCPackage pkg = getPackage(); - if (pkg != null) { - // revert the package to not re-write the file, which is very likely not wanted for a TextExtractor! - pkg.revert(); - } - } - } + if (pkg != null) { + // revert the package to not re-write the file, which is very likely not wanted for a TextExtractor! + pkg.revert(); + } + } + } - default void checkMaxTextSize(CharSequence text, String string) { + default void checkMaxTextSize(CharSequence text, String string) { if(string == null) { return; } diff --git a/poi-ooxml/src/main/java/org/apache/poi/ooxml/util/IdentifierManager.java b/poi-ooxml/src/main/java/org/apache/poi/ooxml/util/IdentifierManager.java index 8634862bb7..981727aba4 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/ooxml/util/IdentifierManager.java +++ b/poi-ooxml/src/main/java/org/apache/poi/ooxml/util/IdentifierManager.java @@ -28,8 +28,8 @@ public class IdentifierManager { private final long lowerbound; /** - * List of segments of available identifiers - */ + * List of segments of available identifiers + */ private LinkedList segments; /** @@ -220,8 +220,8 @@ public class IdentifierManager { } /** - * - */ + * + */ private void verifyIdentifiersLeft() { if (segments.isEmpty()) { throw new IllegalStateException("No identifiers left"); diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java index 0cf0cfbc19..66436b1c5e 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java @@ -20,9 +20,9 @@ package org.apache.poi.openxml4j.exceptions; @SuppressWarnings("serial") public final class InvalidFormatException extends OpenXML4JException { - public InvalidFormatException(String message){ - super(message); - } + public InvalidFormatException(String message){ + super(message); + } public InvalidFormatException(String message, Throwable cause){ super(message,cause); diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/InvalidOperationException.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/InvalidOperationException.java index 7a8338ed81..9e390f3c1e 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/InvalidOperationException.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/InvalidOperationException.java @@ -22,11 +22,11 @@ package org.apache.poi.openxml4j.exceptions; */ @SuppressWarnings("serial") public class InvalidOperationException extends OpenXML4JRuntimeException{ - public InvalidOperationException(String message){ - super(message); - } + public InvalidOperationException(String message){ + super(message); + } public InvalidOperationException(String message, Throwable reason){ - super(message, reason); - } + super(message, reason); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/OpenXML4JException.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/OpenXML4JException.java index 4c7430df5b..a21e677e4b 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/OpenXML4JException.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/OpenXML4JException.java @@ -25,9 +25,9 @@ package org.apache.poi.openxml4j.exceptions; @SuppressWarnings("serial") public class OpenXML4JException extends Exception { - public OpenXML4JException(String msg) { - super(msg); - } + public OpenXML4JException(String msg) { + super(msg); + } public OpenXML4JException(String msg, Throwable cause) { super(msg, cause); diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/OpenXML4JRuntimeException.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/OpenXML4JRuntimeException.java index d8031b87a1..674ce1b94d 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/OpenXML4JRuntimeException.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/OpenXML4JRuntimeException.java @@ -27,9 +27,9 @@ package org.apache.poi.openxml4j.exceptions; @SuppressWarnings("serial") public class OpenXML4JRuntimeException extends RuntimeException { - public OpenXML4JRuntimeException(String msg) { - super(msg); - } + public OpenXML4JRuntimeException(String msg) { + super(msg); + } public OpenXML4JRuntimeException(String msg, Throwable reason) { super(msg, reason); diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/PartAlreadyExistsException.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/PartAlreadyExistsException.java index e469ace568..220d2c1a36 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/PartAlreadyExistsException.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/exceptions/PartAlreadyExistsException.java @@ -25,7 +25,7 @@ import org.apache.poi.openxml4j.opc.PackagePart; */ @SuppressWarnings("serial") public final class PartAlreadyExistsException extends InvalidOperationException { - public PartAlreadyExistsException(String message){ - super(message); - } + public PartAlreadyExistsException(String message){ + super(message); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/CertificateEmbeddingOption.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/CertificateEmbeddingOption.java index 9c95693d8e..5af3b20f3b 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/CertificateEmbeddingOption.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/CertificateEmbeddingOption.java @@ -21,10 +21,10 @@ package org.apache.poi.openxml4j.opc; * Specifies the location where the X.509 certificate that is used in signing is stored. */ public enum CertificateEmbeddingOption { - /** The certificate is embedded in its own PackagePart. */ - IN_CERTIFICATE_PART, - /** The certificate is embedded in the SignaturePart that is created for the signature being added. */ - IN_SIGNATURE_PART, - /** The certificate in not embedded in the package. */ - NOT_EMBEDDED + /** The certificate is embedded in its own PackagePart. */ + IN_CERTIFICATE_PART, + /** The certificate is embedded in the SignaturePart that is created for the signature being added. */ + IN_SIGNATURE_PART, + /** The certificate in not embedded in the package. */ + NOT_EMBEDDED } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ContentTypes.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ContentTypes.java index 5442a5fb05..1b90361d8c 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ContentTypes.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ContentTypes.java @@ -25,106 +25,106 @@ import java.util.Locale; */ public final class ContentTypes { - /* - * Open Packaging Convention (Annex F : Standard Namespaces and Content - * Types) - */ + /* + * Open Packaging Convention (Annex F : Standard Namespaces and Content + * Types) + */ - /** - * Core Properties part. - */ - public static final String CORE_PROPERTIES_PART = "application/vnd.openxmlformats-package.core-properties+xml"; + /** + * Core Properties part. + */ + public static final String CORE_PROPERTIES_PART = "application/vnd.openxmlformats-package.core-properties+xml"; - /** - * Digital Signature Certificate part. - */ - public static final String DIGITAL_SIGNATURE_CERTIFICATE_PART = "application/vnd.openxmlformats-package.digital-signature-certificate"; + /** + * Digital Signature Certificate part. + */ + public static final String DIGITAL_SIGNATURE_CERTIFICATE_PART = "application/vnd.openxmlformats-package.digital-signature-certificate"; - /** - * Digital Signature Origin part. - */ - public static final String DIGITAL_SIGNATURE_ORIGIN_PART = "application/vnd.openxmlformats-package.digital-signature-origin"; + /** + * Digital Signature Origin part. + */ + public static final String DIGITAL_SIGNATURE_ORIGIN_PART = "application/vnd.openxmlformats-package.digital-signature-origin"; - /** - * Digital Signature XML Signature part. - */ - public static final String DIGITAL_SIGNATURE_XML_SIGNATURE_PART = "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"; + /** + * Digital Signature XML Signature part. + */ + public static final String DIGITAL_SIGNATURE_XML_SIGNATURE_PART = "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"; - /** - * Relationships part. - */ - public static final String RELATIONSHIPS_PART = "application/vnd.openxmlformats-package.relationships+xml"; + /** + * Relationships part. + */ + public static final String RELATIONSHIPS_PART = "application/vnd.openxmlformats-package.relationships+xml"; - /** - * Custom XML part. - */ - public static final String CUSTOM_XML_PART = "application/vnd.openxmlformats-officedocument.customXmlProperties+xml"; + /** + * Custom XML part. + */ + public static final String CUSTOM_XML_PART = "application/vnd.openxmlformats-officedocument.customXmlProperties+xml"; - /** - * Plain old xml. Note - OOXML uses application/xml, and not text/xml! - */ - public static final String PLAIN_OLD_XML = "application/xml"; + /** + * Plain old xml. Note - OOXML uses application/xml, and not text/xml! + */ + public static final String PLAIN_OLD_XML = "application/xml"; - public static final String IMAGE_JPEG = "image/jpeg"; + public static final String IMAGE_JPEG = "image/jpeg"; - public static final String EXTENSION_JPG_1 = "jpg"; + public static final String EXTENSION_JPG_1 = "jpg"; - public static final String EXTENSION_JPG_2 = "jpeg"; + public static final String EXTENSION_JPG_2 = "jpeg"; - // image/png ISO/IEC 15948:2003 http://www.libpng.org/pub/png/spec/ - public static final String IMAGE_PNG = "image/png"; + // image/png ISO/IEC 15948:2003 http://www.libpng.org/pub/png/spec/ + public static final String IMAGE_PNG = "image/png"; - public static final String EXTENSION_PNG = "png"; + public static final String EXTENSION_PNG = "png"; - // image/gif http://www.w3.org/Graphics/GIF/spec-gif89a.txt - public static final String IMAGE_GIF = "image/gif"; + // image/gif http://www.w3.org/Graphics/GIF/spec-gif89a.txt + public static final String IMAGE_GIF = "image/gif"; - public static final String EXTENSION_GIF = "gif"; + public static final String EXTENSION_GIF = "gif"; - /** - * TIFF image format. - * - * @see - * http://partners.adobe.com/public/developer/tiff/index.html#spec - */ - public static final String IMAGE_TIFF = "image/tiff"; + /** + * TIFF image format. + * + * @see + * http://partners.adobe.com/public/developer/tiff/index.html#spec + */ + public static final String IMAGE_TIFF = "image/tiff"; - public static final String EXTENSION_TIFF = "tiff"; + public static final String EXTENSION_TIFF = "tiff"; - /** - * Pict image format. - * - * @see - * http://developer.apple.com/documentation/mac/QuickDraw/QuickDraw-2.html - */ - public static final String IMAGE_PICT = "image/pict"; + /** + * Pict image format. + * + * @see + * http://developer.apple.com/documentation/mac/QuickDraw/QuickDraw-2.html + */ + public static final String IMAGE_PICT = "image/pict"; - public static final String EXTENSION_PICT = "pict"; + public static final String EXTENSION_PICT = "pict"; - /** - * XML file. - */ - public static final String XML = "text/xml"; + /** + * XML file. + */ + public static final String XML = "text/xml"; - public static final String EXTENSION_XML = "xml"; + public static final String EXTENSION_XML = "xml"; - public static String getContentTypeFromFileExtension(String filename) { - String extension = filename.substring(filename.lastIndexOf('.') + 1) - .toLowerCase(Locale.ROOT); - if (extension.equals(EXTENSION_JPG_1) - || extension.equals(EXTENSION_JPG_2)) - return IMAGE_JPEG; - else if (extension.equals(EXTENSION_GIF)) - return IMAGE_GIF; - else if (extension.equals(EXTENSION_PICT)) - return IMAGE_PICT; - else if (extension.equals(EXTENSION_PNG)) - return IMAGE_PNG; - else if (extension.equals(EXTENSION_TIFF)) - return IMAGE_TIFF; - else if (extension.equals(EXTENSION_XML)) - return XML; - else - return null; - } + public static String getContentTypeFromFileExtension(String filename) { + String extension = filename.substring(filename.lastIndexOf('.') + 1) + .toLowerCase(Locale.ROOT); + if (extension.equals(EXTENSION_JPG_1) + || extension.equals(EXTENSION_JPG_2)) + return IMAGE_JPEG; + else if (extension.equals(EXTENSION_GIF)) + return IMAGE_GIF; + else if (extension.equals(EXTENSION_PICT)) + return IMAGE_PICT; + else if (extension.equals(EXTENSION_PNG)) + return IMAGE_PNG; + else if (extension.equals(EXTENSION_TIFF)) + return IMAGE_TIFF; + else if (extension.equals(EXTENSION_XML)) + return XML; + else + return null; + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java index 70b50e4d63..1285d6916c 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java @@ -67,115 +67,115 @@ import org.apache.poi.util.NotImplemented; */ public abstract class OPCPackage implements RelationshipSource, Closeable { - /** - * Logger. - */ + /** + * Logger. + */ private static final Logger LOG = LogManager.getLogger(OPCPackage.class); - /** - * Default package access. - */ - protected static final PackageAccess defaultPackageAccess = PackageAccess.READ_WRITE; + /** + * Default package access. + */ + protected static final PackageAccess defaultPackageAccess = PackageAccess.READ_WRITE; - /** - * Package access. - */ - private final PackageAccess packageAccess; + /** + * Package access. + */ + private final PackageAccess packageAccess; - /** - * Package parts collection. - */ - private PackagePartCollection partList; + /** + * Package parts collection. + */ + private PackagePartCollection partList; - /** - * Package relationships. - */ - protected PackageRelationshipCollection relationships; + /** + * Package relationships. + */ + protected PackageRelationshipCollection relationships; - /** - * Part marshallers by content type. - */ - protected final Map partMarshallers = new HashMap<>(5); + /** + * Part marshallers by content type. + */ + protected final Map partMarshallers = new HashMap<>(5); - /** - * Default part marshaller. - */ - protected final PartMarshaller defaultPartMarshaller = new DefaultMarshaller(); + /** + * Default part marshaller. + */ + protected final PartMarshaller defaultPartMarshaller = new DefaultMarshaller(); - /** - * Part unmarshallers by content type. - */ - protected final Map partUnmarshallers = new HashMap<>(2); + /** + * Part unmarshallers by content type. + */ + protected final Map partUnmarshallers = new HashMap<>(2); - /** - * Core package properties. - */ - protected PackagePropertiesPart packageProperties; + /** + * Core package properties. + */ + protected PackagePropertiesPart packageProperties; - /** - * Manage parts content types of this package. - */ - protected ContentTypeManager contentTypeManager; + /** + * Manage parts content types of this package. + */ + protected ContentTypeManager contentTypeManager; - /** - * Flag if a modification is done to the document. - */ - protected boolean isDirty; + /** + * Flag if a modification is done to the document. + */ + protected boolean isDirty; - /** - * File path of this package. - */ - protected String originalPackagePath; + /** + * File path of this package. + */ + protected String originalPackagePath; - /** - * Output stream for writing this package. - */ - protected OutputStream output; + /** + * Output stream for writing this package. + */ + protected OutputStream output; - /** - * Constructor. - * - * @param access - * Package access. - */ - OPCPackage(PackageAccess access) { - if (getClass() != ZipPackage.class) { - throw new IllegalArgumentException("PackageBase may not be subclassed"); - } - this.packageAccess = access; + /** + * Constructor. + * + * @param access + * Package access. + */ + OPCPackage(PackageAccess access) { + if (getClass() != ZipPackage.class) { + throw new IllegalArgumentException("PackageBase may not be subclassed"); + } + this.packageAccess = access; - final ContentType contentType = newCorePropertiesPart(); - // TODO Delocalize specialized marshallers - this.partUnmarshallers.put(contentType, new PackagePropertiesUnmarshaller()); - this.partMarshallers.put(contentType, new ZipPackagePropertiesMarshaller()); - } + final ContentType contentType = newCorePropertiesPart(); + // TODO Delocalize specialized marshallers + this.partUnmarshallers.put(contentType, new PackagePropertiesUnmarshaller()); + this.partMarshallers.put(contentType, new ZipPackagePropertiesMarshaller()); + } - private static ContentType newCorePropertiesPart() { - try { - return new ContentType(ContentTypes.CORE_PROPERTIES_PART); - } catch (InvalidFormatException e) { - // Should never happen - throw new OpenXML4JRuntimeException( - "Package.init() : this exception should never happen, " + - "if you read this message please send a mail to the developers team. : " + - e.getMessage(), e - ); - } - } + private static ContentType newCorePropertiesPart() { + try { + return new ContentType(ContentTypes.CORE_PROPERTIES_PART); + } catch (InvalidFormatException e) { + // Should never happen + throw new OpenXML4JRuntimeException( + "Package.init() : this exception should never happen, " + + "if you read this message please send a mail to the developers team. : " + + e.getMessage(), e + ); + } + } - /** - * Open a package with read/write permission. - * - * @param path - * The document path. - * @return A Package object, else null. - * @throws InvalidFormatException - * If the specified file doesn't exist, and a parsing error - * occur. - */ - public static OPCPackage open(String path) throws InvalidFormatException { - return open(path, defaultPackageAccess); - } + /** + * Open a package with read/write permission. + * + * @param path + * The document path. + * @return A Package object, else null. + * @throws InvalidFormatException + * If the specified file doesn't exist, and a parsing error + * occur. + */ + public static OPCPackage open(String path) throws InvalidFormatException { + return open(path, defaultPackageAccess); + } /** * Open a package with read/write permission. @@ -211,52 +211,52 @@ public abstract class OPCPackage implements RelationshipSource, Closeable { // pack.originalPackagePath = file.getAbsolutePath(); return pack; } catch (InvalidFormatException | RuntimeException e) { - IOUtils.closeQuietly(pack); + IOUtils.closeQuietly(pack); throw e; } } - /** - * Open a package. - * - * @param path - * The document path. - * @param access - * PackageBase access. - * @return A PackageBase object, else null. - * @throws InvalidFormatException - * If the specified file doesn't exist, and a parsing error - * occur. - * @throws InvalidOperationException If the zip file cannot be opened. - * @throws InvalidFormatException if the package is not valid. - */ - public static OPCPackage open(String path, PackageAccess access) - throws InvalidFormatException, InvalidOperationException { - if (path == null || path.trim().isEmpty()) { - throw new IllegalArgumentException("'path' must be given"); - } + /** + * Open a package. + * + * @param path + * The document path. + * @param access + * PackageBase access. + * @return A PackageBase object, else null. + * @throws InvalidFormatException + * If the specified file doesn't exist, and a parsing error + * occur. + * @throws InvalidOperationException If the zip file cannot be opened. + * @throws InvalidFormatException if the package is not valid. + */ + public static OPCPackage open(String path, PackageAccess access) + throws InvalidFormatException, InvalidOperationException { + if (path == null || path.trim().isEmpty()) { + throw new IllegalArgumentException("'path' must be given"); + } - File file = new File(path); - if (file.exists() && file.isDirectory()) { - throw new IllegalArgumentException("path must not be a directory"); - } + File file = new File(path); + if (file.exists() && file.isDirectory()) { + throw new IllegalArgumentException("path must not be a directory"); + } - OPCPackage pack = new ZipPackage(path, access); // NOSONAR - boolean success = false; - if (pack.partList == null && access != PackageAccess.WRITE) { - try { - pack.getParts(); - success = true; - } finally { - if (! success) { - IOUtils.closeQuietly(pack); - } - } - } + OPCPackage pack = new ZipPackage(path, access); // NOSONAR + boolean success = false; + if (pack.partList == null && access != PackageAccess.WRITE) { + try { + pack.getParts(); + success = true; + } finally { + if (! success) { + IOUtils.closeQuietly(pack); + } + } + } - pack.originalPackagePath = new File(path).getAbsolutePath(); - return pack; - } + pack.originalPackagePath = new File(path).getAbsolutePath(); + return pack; + } /** * Open a package. @@ -280,200 +280,200 @@ public abstract class OPCPackage implements RelationshipSource, Closeable { } OPCPackage pack = new ZipPackage(file, access); - try { - if (pack.partList == null && access != PackageAccess.WRITE) { - pack.getParts(); - } - pack.originalPackagePath = file.getAbsolutePath(); - return pack; - } catch (InvalidFormatException | RuntimeException e) { - IOUtils.closeQuietly(pack); - throw e; - } + try { + if (pack.partList == null && access != PackageAccess.WRITE) { + pack.getParts(); + } + pack.originalPackagePath = file.getAbsolutePath(); + return pack; + } catch (InvalidFormatException | RuntimeException e) { + IOUtils.closeQuietly(pack); + throw e; + } } - /** - * Open a package. - * - * Note - uses quite a bit more memory than {@link #open(String)}, which - * doesn't need to hold the whole zip file in memory, and can take advantage - * of native methods - * - * @param in - * The InputStream to read the package from - * @return A PackageBase object - * - * @throws InvalidFormatException - * Throws if the specified file exist and is not valid. - * @throws IOException If reading the stream fails - */ - public static OPCPackage open(InputStream in) throws InvalidFormatException, - IOException { - OPCPackage pack = new ZipPackage(in, PackageAccess.READ_WRITE); - try { - if (pack.partList == null) { - pack.getParts(); - } - } catch (InvalidFormatException | RuntimeException e) { - IOUtils.closeQuietly(pack); - throw e; - } - return pack; - } + /** + * Open a package. + * + * Note - uses quite a bit more memory than {@link #open(String)}, which + * doesn't need to hold the whole zip file in memory, and can take advantage + * of native methods + * + * @param in + * The InputStream to read the package from + * @return A PackageBase object + * + * @throws InvalidFormatException + * Throws if the specified file exist and is not valid. + * @throws IOException If reading the stream fails + */ + public static OPCPackage open(InputStream in) throws InvalidFormatException, + IOException { + OPCPackage pack = new ZipPackage(in, PackageAccess.READ_WRITE); + try { + if (pack.partList == null) { + pack.getParts(); + } + } catch (InvalidFormatException | RuntimeException e) { + IOUtils.closeQuietly(pack); + throw e; + } + return pack; + } - /** - * Opens a package if it exists, else it creates one. - * - * @param file - * The file to open or to create. - * @return A newly created package if the specified file does not exist, - * else the package extract from the file. - * @throws InvalidFormatException - * Throws if the specified file exist and is not valid. - */ - public static OPCPackage openOrCreate(File file) throws InvalidFormatException { - if (file.exists()) { - return open(file.getAbsolutePath()); - } else { - return create(file); - } - } + /** + * Opens a package if it exists, else it creates one. + * + * @param file + * The file to open or to create. + * @return A newly created package if the specified file does not exist, + * else the package extract from the file. + * @throws InvalidFormatException + * Throws if the specified file exist and is not valid. + */ + public static OPCPackage openOrCreate(File file) throws InvalidFormatException { + if (file.exists()) { + return open(file.getAbsolutePath()); + } else { + return create(file); + } + } - /** - * Creates a new package. - * - * @param path - * Path of the document. - * @return A newly created PackageBase ready to use. - */ - public static OPCPackage create(String path) { - return create(new File(path)); - } + /** + * Creates a new package. + * + * @param path + * Path of the document. + * @return A newly created PackageBase ready to use. + */ + public static OPCPackage create(String path) { + return create(new File(path)); + } - /** - * Creates a new package. - * - * @param file - * Path of the document. - * @return A newly created PackageBase ready to use. - */ - public static OPCPackage create(File file) { - if (file == null || (file.exists() && file.isDirectory())) { - throw new IllegalArgumentException("file"); - } + /** + * Creates a new package. + * + * @param file + * Path of the document. + * @return A newly created PackageBase ready to use. + */ + public static OPCPackage create(File file) { + if (file == null || (file.exists() && file.isDirectory())) { + throw new IllegalArgumentException("file"); + } - if (file.exists()) { - throw new InvalidOperationException( - "This package (or file) already exists : use the open() method or delete the file."); - } + if (file.exists()) { + throw new InvalidOperationException( + "This package (or file) already exists : use the open() method or delete the file."); + } - // Creates a new package - OPCPackage pkg = new ZipPackage(); - pkg.originalPackagePath = file.getAbsolutePath(); + // Creates a new package + OPCPackage pkg = new ZipPackage(); + pkg.originalPackagePath = file.getAbsolutePath(); - configurePackage(pkg); - return pkg; - } + configurePackage(pkg); + return pkg; + } - public static OPCPackage create(OutputStream output) { - OPCPackage pkg = new ZipPackage(); - pkg.originalPackagePath = null; - pkg.output = output; + public static OPCPackage create(OutputStream output) { + OPCPackage pkg = new ZipPackage(); + pkg.originalPackagePath = null; + pkg.output = output; - configurePackage(pkg); - return pkg; - } + configurePackage(pkg); + return pkg; + } - private static void configurePackage(OPCPackage pkg) { - try { - // Content type manager - pkg.contentTypeManager = new ZipContentTypeManager(null, pkg); + private static void configurePackage(OPCPackage pkg) { + try { + // Content type manager + pkg.contentTypeManager = new ZipContentTypeManager(null, pkg); - // Add default content types for .xml and .rels - pkg.contentTypeManager.addContentType( - PackagingURIHelper.createPartName( - PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI), - RELATIONSHIPS_PART); - pkg.contentTypeManager.addContentType( - PackagingURIHelper.createPartName("/default.xml"), - PLAIN_OLD_XML); + // Add default content types for .xml and .rels + pkg.contentTypeManager.addContentType( + PackagingURIHelper.createPartName( + PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI), + RELATIONSHIPS_PART); + pkg.contentTypeManager.addContentType( + PackagingURIHelper.createPartName("/default.xml"), + PLAIN_OLD_XML); - // Initialise some PackageBase properties - pkg.packageProperties = new PackagePropertiesPart(pkg, - PackagingURIHelper.CORE_PROPERTIES_PART_NAME); - pkg.packageProperties.setCreatorProperty("Generated by Apache POI OpenXML4J"); - pkg.packageProperties.setCreatedProperty(Optional.of(new Date())); - } catch (InvalidFormatException e) { - // Should never happen - throw new IllegalStateException(e); - } - } + // Initialise some PackageBase properties + pkg.packageProperties = new PackagePropertiesPart(pkg, + PackagingURIHelper.CORE_PROPERTIES_PART_NAME); + pkg.packageProperties.setCreatorProperty("Generated by Apache POI OpenXML4J"); + pkg.packageProperties.setCreatedProperty(Optional.of(new Date())); + } catch (InvalidFormatException e) { + // Should never happen + throw new IllegalStateException(e); + } + } - /** - * Flush the package : save all. - * - * @see #close() - */ - public void flush() { - throwExceptionIfReadOnly(); + /** + * Flush the package : save all. + * + * @see #close() + */ + public void flush() { + throwExceptionIfReadOnly(); - if (this.packageProperties != null) { - this.packageProperties.flush(); - } + if (this.packageProperties != null) { + this.packageProperties.flush(); + } - this.flushImpl(); - } + this.flushImpl(); + } - /** - * Close the open, writable package and save its content. - * - * If your package is open read only, then you should call {@link #revert()} - * when finished with the package. - * - * This method is not thread-safe. - * - * @throws IOException - * If an IO exception occur during the saving process. - */ - @Override + /** + * Close the open, writable package and save its content. + * + * If your package is open read only, then you should call {@link #revert()} + * when finished with the package. + * + * This method is not thread-safe. + * + * @throws IOException + * If an IO exception occur during the saving process. + */ + @Override public void close() throws IOException { - if (isClosed()) { - return; - } + if (isClosed()) { + return; + } - if (this.packageAccess == PackageAccess.READ) { - LOG.atWarn().log("The close() method is intended to SAVE a package. This package is open in READ ONLY mode, use the revert() method instead!"); - revert(); - return; - } - if (this.contentTypeManager == null) { - LOG.atWarn().log("Unable to call close() on a package that hasn't been fully opened yet"); - revert(); - return; - } + if (this.packageAccess == PackageAccess.READ) { + LOG.atWarn().log("The close() method is intended to SAVE a package. This package is open in READ ONLY mode, use the revert() method instead!"); + revert(); + return; + } + if (this.contentTypeManager == null) { + LOG.atWarn().log("Unable to call close() on a package that hasn't been fully opened yet"); + revert(); + return; + } - if (this.originalPackagePath != null - && !this.originalPackagePath.trim().isEmpty()) { - File targetFile = new File(this.originalPackagePath); - if (!targetFile.exists() - || !(this.originalPackagePath - .equalsIgnoreCase(targetFile.getAbsolutePath()))) { - // Case of a package created from scratch - save(targetFile); - } else { - closeImpl(); - } - } else if (this.output != null) { - save(this.output); - output.close(); - } + if (this.originalPackagePath != null + && !this.originalPackagePath.trim().isEmpty()) { + File targetFile = new File(this.originalPackagePath); + if (!targetFile.exists() + || !(this.originalPackagePath + .equalsIgnoreCase(targetFile.getAbsolutePath()))) { + // Case of a package created from scratch + save(targetFile); + } else { + closeImpl(); + } + } else if (this.output != null) { + save(this.output); + output.close(); + } - // ensure all held resources are freed + // ensure all held resources are freed revert(); - // Clear - this.contentTypeManager.clearAll(); - } + // Clear + this.contentTypeManager.clearAll(); + } /** * Close the package WITHOUT saving its content. Reinitialize this package @@ -497,9 +497,9 @@ public abstract class OPCPackage implements RelationshipSource, Closeable { } String name = path.substring(path.lastIndexOf(File.separatorChar) + 1); - try (FileInputStream is = new FileInputStream(path)) { - addThumbnail(name, is); - } + try (FileInputStream is = new FileInputStream(path)) { + addThumbnail(name, is); + } } /** * Add a thumbnail to the package. This method is provided to make easier @@ -566,792 +566,792 @@ public abstract class OPCPackage implements RelationshipSource, Closeable { } } - /** - * Throws an exception if the package access mode is in write only mode - * (PackageAccess.Write). This method is call when other methods need write - * right. - * - * @throws InvalidOperationException if a read operation is done on a write only package. - * @see PackageAccess - */ - void throwExceptionIfWriteOnly() throws InvalidOperationException { - if (packageAccess == PackageAccess.WRITE) { - throw new InvalidOperationException( - "Operation not allowed, document open in write only mode!"); - } - } - - /** - * Retrieves or creates if none exists, core package property part. - * - * @return The PackageProperties part of this package. - */ - public PackageProperties getPackageProperties() - throws InvalidFormatException { - this.throwExceptionIfWriteOnly(); - // If no properties part has been found then we create one - if (this.packageProperties == null) { - this.packageProperties = new PackagePropertiesPart(this, - PackagingURIHelper.CORE_PROPERTIES_PART_NAME); - } - return this.packageProperties; - } - - /** - * Retrieve a part identified by its name. - * - * @param partName - * Part name of the part to retrieve. - * @return The part with the specified name, else {@code null}. - */ - public PackagePart getPart(PackagePartName partName) { - throwExceptionIfWriteOnly(); - - if (partName == null) { - throw new IllegalArgumentException("partName"); - } - - // If the partlist is null, then we parse the package. - if (partList == null) { - try { - getParts(); - } catch (InvalidFormatException e) { - return null; - } - } - - return partList.get(partName); - } - - /** - * Retrieve parts by content type. - * - * @param contentType - * The content type criteria. - * @return All part associated to the specified content type. - */ - public ArrayList getPartsByContentType(String contentType) { - ArrayList retArr = new ArrayList<>(); - for (PackagePart part : partList.sortedValues()) { - if (part.getContentType().equals(contentType)) { - retArr.add(part); - } - } - return retArr; - } - - /** - * Retrieve parts by relationship type. - * - * @param relationshipType - * Relationship type. Must not be {@code null}. - * @return All parts which are the target of a relationship with the - * specified type. If no such parts are found, the list is empty. - * @throws InvalidOperationException If called on a write-only package. - * @throws IllegalArgumentException if relationshipType input param is null. - */ - public ArrayList getPartsByRelationshipType( - String relationshipType) { - if (relationshipType == null) { - throw new IllegalArgumentException("relationshipType"); - } - ArrayList retArr = new ArrayList<>(); - for (PackageRelationship rel : getRelationshipsByType(relationshipType)) { - PackagePart part = getPart(rel); - if (part != null) { - retArr.add(part); - } - } - Collections.sort(retArr); - return retArr; - } - - /** - * Retrieve parts by name - * - * @param namePattern - * The pattern for matching the names - * @return All parts associated to the specified content type, sorted - * in alphanumerically by the part-name - */ - public List getPartsByName(final Pattern namePattern) { - if (namePattern == null) { - throw new IllegalArgumentException("name pattern must not be null"); - } - Matcher matcher = namePattern.matcher(""); - ArrayList result = new ArrayList<>(); - for (PackagePart part : partList.sortedValues()) { - PackagePartName partName = part.getPartName(); - if (matcher.reset(partName.getName()).matches()) { - result.add(part); - } - } - return result; - } - - /** - * Get the target part from the specified relationship. - * - * @param partRel - * The part relationship uses to retrieve the part. - */ - public PackagePart getPart(PackageRelationship partRel) { - PackagePart retPart = null; - ensureRelationships(); - for (PackageRelationship rel : relationships) { - if (rel.getRelationshipType().equals(partRel.getRelationshipType())) { - try { - retPart = getPart(PackagingURIHelper.createPartName(rel - .getTargetURI())); - } catch (InvalidFormatException e) { - continue; - } - break; - } - } - return retPart; - } - - /** - * Load the parts of the archive if it has not been done yet. The - * relationships of each part are not loaded. - * - * Note - Rule M4.1 states that there may only ever be one Core - * Properties Part, but Office produced files will sometimes - * have multiple! As Office ignores all but the first, we relax - * Compliance with Rule M4.1, and ignore all others silently too. - * - * @return All this package's parts. - * @throws InvalidFormatException if the package is not valid. - */ - public ArrayList getParts() throws InvalidFormatException { - throwExceptionIfWriteOnly(); - - // If the part list is null, we parse the package to retrieve all parts. - if (partList == null) { - /* Variables use to validate OPC Compliance */ - - // Check rule M4.1 -> A format consumer shall consider more than - // one core properties relationship for a package to be an error - // (We just log it and move on, as real files break this!) - boolean hasCorePropertiesPart = false; - boolean needCorePropertiesPart = true; - - partList = getPartsImpl(); - for (PackagePart part : new ArrayList<>(partList.sortedValues())) { - part.loadRelationships(); - - // Check OPC compliance rule M4.1 - if (ContentTypes.CORE_PROPERTIES_PART.equals(part.getContentType())) { - if (!hasCorePropertiesPart) { - hasCorePropertiesPart = true; - } else { - LOG.atWarn().log("OPC Compliance error [M4.1]: " + - "there is more than one core properties relationship in the package! " + - "POI will use only the first, but other software may reject this file."); - } - } - - PartUnmarshaller partUnmarshaller = partUnmarshallers.get(part._contentType); - - if (partUnmarshaller != null) { - UnmarshallContext context = new UnmarshallContext(this, part._partName); - try { - PackagePart unmarshallPart = partUnmarshaller.unmarshall(context, part.getInputStream()); - partList.remove(part.getPartName()); - partList.put(unmarshallPart._partName, unmarshallPart); - - // Core properties case-- use first CoreProperties part we come across - // and ignore any subsequent ones - if (unmarshallPart instanceof PackagePropertiesPart && - hasCorePropertiesPart && - needCorePropertiesPart) { - this.packageProperties = (PackagePropertiesPart) unmarshallPart; - needCorePropertiesPart = false; - } - } catch (IOException ioe) { - LOG.atWarn().log("Unmarshall operation : IOException for {}", part._partName); - } catch (InvalidOperationException invoe) { - throw new InvalidFormatException(invoe.getMessage(), invoe); - } - } - } - } - return new ArrayList<>(partList.sortedValues()); - } - - /** - * Create and add a part, with the specified name and content type, to the - * package. - * - * @param partName - * Part name. - * @param contentType - * Part content type. - * @return The newly created part. - * @throws PartAlreadyExistsException - * If rule M1.12 is not verified : Packages shall not contain - * equivalent part names and package implementers shall neither - * create nor recognize packages with equivalent part names. - * @see #createPartImpl(PackagePartName, String, boolean) - */ - public PackagePart createPart(PackagePartName partName, String contentType) { - return this.createPart(partName, contentType, true); - } - - /** - * Create and add a part, with the specified name and content type, to the - * package. For general purpose, prefer the overload version of this method - * without the 'loadRelationships' parameter. - * - * @param partName - * Part name. - * @param contentType - * Part content type. - * @param loadRelationships - * Specify if the existing relationship part, if any, logically - * associated to the newly created part will be loaded. - * @return The newly created part. - * @throws PartAlreadyExistsException - * If rule M1.12 is not verified : Packages shall not contain - * equivalent part names and package implementers shall neither - * create nor recognize packages with equivalent part names. - * @see #createPartImpl(PackagePartName, String, boolean) - */ - PackagePart createPart(PackagePartName partName, String contentType, - boolean loadRelationships) { - throwExceptionIfReadOnly(); - if (partName == null) { - throw new IllegalArgumentException("partName"); - } - - if (contentType == null || contentType.isEmpty()) { - throw new IllegalArgumentException("contentType"); - } - - // Check if the specified part name already exists - if (partList.containsKey(partName) - && !partList.get(partName).isDeleted()) { - throw new PartAlreadyExistsException( - "A part with the name '" + partName.getName() + "'" + - " already exists : Packages shall not contain equivalent part names and package" + - " implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); - } - - /* Check OPC compliance */ - - // Rule [M4.1]: The format designer shall specify and the format producer - // shall create at most one core properties relationship for a package. - // A format consumer shall consider more than one core properties - // relationship for a package to be an error. If present, the - // relationship shall target the Core Properties part. - // Note - POI will read files with more than one Core Properties, which - // Office sometimes produces, but is strict on generation - if (contentType.equals(ContentTypes.CORE_PROPERTIES_PART)) { - if (this.packageProperties != null) { - throw new InvalidOperationException( - "OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !"); - } - } - - /* End check OPC compliance */ - - PackagePart part = this.createPartImpl(partName, contentType, - loadRelationships); - - /* check/create default entries - for bug54803 */ - try { - PackagePartName ppn = PackagingURIHelper.createPartName("/."+EXTENSION_XML); - contentTypeManager.addContentType(ppn, PLAIN_OLD_XML); - ppn = PackagingURIHelper.createPartName("/"+RELATIONSHIP_PART_EXTENSION_NAME); - contentTypeManager.addContentType(ppn, RELATIONSHIPS_PART); - } catch (InvalidFormatException e) { - throw new InvalidOperationException("unable to create default content-type entries.", e); - } - - this.contentTypeManager.addContentType(partName, contentType); - this.partList.put(partName, part); - this.isDirty = true; - return part; - } - - /** - * Add a part to the package. - * - * @param partName - * Part name of the part to create. - * @param contentType - * type associated with the file - * @param content - * the contents to add. In order to have faster operation in - * document merge, the data are stored in memory not on a hard - * disk - * - * @return The new part. - * @see #createPart(PackagePartName, String) - */ - public PackagePart createPart(PackagePartName partName, String contentType, - ByteArrayOutputStream content) { - PackagePart addedPart = this.createPart(partName, contentType); - if (addedPart == null) { - return null; - } - // Extract the zip entry content to put it in the part content - if (content != null) { - try (OutputStream partOutput = addedPart.getOutputStream()) { - if (partOutput == null) { - return null; - } - content.writeTo(partOutput); - } catch (IOException ignored) { - return null; - } - } else { - return null; - } - return addedPart; - } - - /** - * Add the specified part to the package. If a part already exists in the - * package with the same name as the one specified, then we replace the old - * part by the specified part. - * - * @param part - * The part to add (or replace). - * @return The part added to the package, the same as the one specified. - * @throws InvalidOperationException - * If rule M1.12 is not verified : Packages shall not contain - * equivalent part names and package implementers shall neither - * create nor recognize packages with equivalent part names. - */ - protected PackagePart addPackagePart(PackagePart part) { - throwExceptionIfReadOnly(); - if (part == null) { - throw new IllegalArgumentException("part"); - } - - if (partList.containsKey(part._partName)) { - if (!partList.get(part._partName).isDeleted()) { - throw new InvalidOperationException( - "A part with the name '" - + part._partName.getName() - + "' already exists : Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); - } - // If the specified partis flagged as deleted, we make it - // available - part.setDeleted(false); - // and delete the old part to replace it thereafeter - this.partList.remove(part._partName); - } - this.partList.put(part._partName, part); - this.isDirty = true; - return part; - } - - /** - * Remove the specified part in this package. If this part is relationship - * part, then delete all relationships in the source part. - * - * @param part - * The part to remove. If {@code null}, skip the action. - * @see #removePart(PackagePartName) - */ - public void removePart(PackagePart part) { - if (part != null) { - removePart(part.getPartName()); - } - } - - /** - * Remove a part in this package. If this part is relationship part, then - * delete all relationships in the source part. - * - * @param partName - * The part name of the part to remove. - */ - public void removePart(PackagePartName partName) { - throwExceptionIfReadOnly(); - if (partName == null || !this.containPart(partName)) { - throw new IllegalArgumentException("partName"); - } - - // Delete the specified part from the package. - if (this.partList.containsKey(partName)) { - this.partList.get(partName).setDeleted(true); - this.removePartImpl(partName); - this.partList.remove(partName); - } else { - this.removePartImpl(partName); - } - - // Delete content type - this.contentTypeManager.removeContentType(partName); - - // If this part is a relationship part, then delete all relationships of - // the source part. - if (partName.isRelationshipPartURI()) { - URI sourceURI = PackagingURIHelper - .getSourcePartUriFromRelationshipPartUri(partName.getURI()); - PackagePartName sourcePartName; - try { - sourcePartName = PackagingURIHelper.createPartName(sourceURI); - } catch (InvalidFormatException e) { - LOG.atError().log("Part name URI '{}' is not valid! This message is not intended to be displayed!", sourceURI); - return; - } - if (sourcePartName.getURI().equals( - PackagingURIHelper.PACKAGE_ROOT_URI)) { - clearRelationships(); - } else if (containPart(sourcePartName)) { - PackagePart part = getPart(sourcePartName); - if (part != null) { - part.clearRelationships(); - } - } - } - - this.isDirty = true; - } - - /** - * Remove a part from this package as well as its relationship part, if one - * exists, and all parts listed in the relationship part. Be aware that this - * do not delete relationships which target the specified part. - * - * @param partName - * The name of the part to delete. - * @throws InvalidFormatException - * Throws if the associated relationship part of the specified - * part is not valid. - */ - public void removePartRecursive(PackagePartName partName) - throws InvalidFormatException { - // Retrieves relationship part, if one exists - PackagePart relPart = this.partList.get(PackagingURIHelper - .getRelationshipPartName(partName)); - // Retrieves PackagePart object from the package - PackagePart partToRemove = this.partList.get(partName); - - if (relPart != null) { - PackageRelationshipCollection partRels = new PackageRelationshipCollection( - partToRemove); - for (PackageRelationship rel : partRels) { - PackagePartName partNameToRemove = PackagingURIHelper - .createPartName(PackagingURIHelper.resolvePartUri(rel - .getSourceURI(), rel.getTargetURI())); - removePart(partNameToRemove); - } - - // Finally delete its relationship part if one exists - this.removePart(relPart._partName); - } - - // Delete the specified part - this.removePart(partToRemove._partName); - } - - /** - * Delete the part with the specified name and its associated relationships - * part if one exists. Prefer the use of this method to delete a part in the - * package, compare to the remove() methods that don't remove associated - * relationships part. - * - * @param partName - * Name of the part to delete - */ - public void deletePart(PackagePartName partName) { - if (partName == null) { - throw new IllegalArgumentException("partName"); - } - - // Remove the part - this.removePart(partName); - // Remove the relationships part - this.removePart(PackagingURIHelper.getRelationshipPartName(partName)); - } - - /** - * Delete the part with the specified name and all part listed in its - * associated relationships part if one exists. This process is recursively - * apply to all parts in the relationships part of the specified part. - * Prefer the use of this method to delete a part in the package, compare to - * the remove() methods that don't remove associated relationships part. - * - * @param partName - * Name of the part to delete - */ - public void deletePartRecursive(PackagePartName partName) { - if (partName == null || !this.containPart(partName)) { - throw new IllegalArgumentException("partName"); - } - - PackagePart partToDelete = this.getPart(partName); - // Remove the part - this.removePart(partName); - // Remove all relationship parts associated - try { - for (PackageRelationship relationship : partToDelete - .getRelationships()) { - PackagePartName targetPartName = PackagingURIHelper - .createPartName(PackagingURIHelper.resolvePartUri( - partName.getURI(), relationship.getTargetURI())); - this.deletePartRecursive(targetPartName); - } - } catch (InvalidFormatException e) { - LOG.atWarn().withThrowable(e).log("An exception occurs while deleting part '{}'. Some parts may remain in the package.", partName.getName()); - return; - } - // Remove the relationships part - PackagePartName relationshipPartName = PackagingURIHelper - .getRelationshipPartName(partName); - if (relationshipPartName != null && containPart(relationshipPartName)) { - this.removePart(relationshipPartName); - } - } - - /** - * Check if a part already exists in this package from its name. - * - * @param partName - * Part name to check. - * @return true if the part is logically added to this package, else - * false. - */ - public boolean containPart(PackagePartName partName) { - return (this.getPart(partName) != null); - } - - /** - * Add a relationship to the package (except relationships part). - * - * Check rule M4.1 : The format designer shall specify and the format - * producer shall create at most one core properties relationship for a - * package. A format consumer shall consider more than one core properties - * relationship for a package to be an error. If present, the relationship - * shall target the Core Properties part. - * - * Check rule M1.25: The Relationships part shall not have relationships to - * any other part. Package implementers shall enforce this requirement upon - * the attempt to create such a relationship and shall treat any such - * relationship as invalid. - * - * @param targetPartName - * Target part name. - * @param targetMode - * Target mode, either Internal or External. - * @param relationshipType - * Relationship type. - * @param relID - * ID of the relationship. - * @see PackageRelationshipTypes - */ - @Override - public PackageRelationship addRelationship(PackagePartName targetPartName, - TargetMode targetMode, String relationshipType, String relID) { - /* Check OPC compliance */ - - // Check rule M4.1 : The format designer shall specify and the format - // producer - // shall create at most one core properties relationship for a package. - // A format consumer shall consider more than one core properties - // relationship for a package to be an error. If present, the - // relationship shall target the Core Properties part. - if (relationshipType.equals(PackageRelationshipTypes.CORE_PROPERTIES) - && this.packageProperties != null) { - throw new InvalidOperationException( - "OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead."); - } - - /* - * Check rule M1.25: The Relationships part shall not have relationships - * to any other part. Package implementers shall enforce this - * requirement upon the attempt to create such a relationship and shall - * treat any such relationship as invalid. - */ - if (targetPartName.isRelationshipPartURI()) { - throw new InvalidOperationException( - "Rule M1.25: The Relationships part shall not have relationships to any other part."); - } - - /* End OPC compliance */ - - ensureRelationships(); - PackageRelationship retRel = relationships.addRelationship( - targetPartName.getURI(), targetMode, relationshipType, relID); - this.isDirty = true; - return retRel; - } - - /** - * Add a package relationship. - * - * @param targetPartName - * Target part name. - * @param targetMode - * Target mode, either Internal or External. - * @param relationshipType - * Relationship type. - * @see PackageRelationshipTypes - */ - @Override - public PackageRelationship addRelationship(PackagePartName targetPartName, - TargetMode targetMode, String relationshipType) { - return this.addRelationship(targetPartName, targetMode, - relationshipType, null); - } - - /** - * Adds an external relationship to a part (except relationships part). - * - * The targets of external relationships are not subject to the same - * validity checks that internal ones are, as the contents is potentially - * any file, URL or similar. - * - * @param target - * External target of the relationship - * @param relationshipType - * Type of relationship. - * @return The newly created and added relationship - */ - @Override - public PackageRelationship addExternalRelationship(String target, - String relationshipType) { - return addExternalRelationship(target, relationshipType, null); - } - - /** - * Adds an external relationship to a part (except relationships part). - * - * The targets of external relationships are not subject to the same - * validity checks that internal ones are, as the contents is potentially - * any file, URL or similar. - * - * @param target - * External target of the relationship - * @param relationshipType - * Type of relationship. - * @param id - * Relationship unique id. - * @return The newly created and added relationship - * @see RelationshipSource#addExternalRelationship(String, - * String) - */ - @Override - public PackageRelationship addExternalRelationship(String target, - String relationshipType, String id) { - if (target == null) { - throw new IllegalArgumentException("target"); - } - if (relationshipType == null) { - throw new IllegalArgumentException("relationshipType"); - } - - URI targetURI; - try { - targetURI = new URI(target); - } catch (URISyntaxException e) { - throw new IllegalArgumentException("Invalid target - " + e); - } - - ensureRelationships(); - PackageRelationship retRel = relationships.addRelationship(targetURI, - TargetMode.EXTERNAL, relationshipType, id); - this.isDirty = true; - return retRel; - } - - /** - * Delete a relationship from this package. - * - * @param id - * Id of the relationship to delete. - */ - @Override - public void removeRelationship(String id) { - if (relationships != null) { - relationships.removeRelationship(id); - this.isDirty = true; - } - } - - /** - * Retrieves all package relationships. - * - * @return All package relationships of this package. + /** + * Throws an exception if the package access mode is in write only mode + * (PackageAccess.Write). This method is call when other methods need write + * right. + * * @throws InvalidOperationException if a read operation is done on a write only package. - * @see #getRelationshipsHelper(String) - */ - @Override + * @see PackageAccess + */ + void throwExceptionIfWriteOnly() throws InvalidOperationException { + if (packageAccess == PackageAccess.WRITE) { + throw new InvalidOperationException( + "Operation not allowed, document open in write only mode!"); + } + } + + /** + * Retrieves or creates if none exists, core package property part. + * + * @return The PackageProperties part of this package. + */ + public PackageProperties getPackageProperties() + throws InvalidFormatException { + this.throwExceptionIfWriteOnly(); + // If no properties part has been found then we create one + if (this.packageProperties == null) { + this.packageProperties = new PackagePropertiesPart(this, + PackagingURIHelper.CORE_PROPERTIES_PART_NAME); + } + return this.packageProperties; + } + + /** + * Retrieve a part identified by its name. + * + * @param partName + * Part name of the part to retrieve. + * @return The part with the specified name, else {@code null}. + */ + public PackagePart getPart(PackagePartName partName) { + throwExceptionIfWriteOnly(); + + if (partName == null) { + throw new IllegalArgumentException("partName"); + } + + // If the partlist is null, then we parse the package. + if (partList == null) { + try { + getParts(); + } catch (InvalidFormatException e) { + return null; + } + } + + return partList.get(partName); + } + + /** + * Retrieve parts by content type. + * + * @param contentType + * The content type criteria. + * @return All part associated to the specified content type. + */ + public ArrayList getPartsByContentType(String contentType) { + ArrayList retArr = new ArrayList<>(); + for (PackagePart part : partList.sortedValues()) { + if (part.getContentType().equals(contentType)) { + retArr.add(part); + } + } + return retArr; + } + + /** + * Retrieve parts by relationship type. + * + * @param relationshipType + * Relationship type. Must not be {@code null}. + * @return All parts which are the target of a relationship with the + * specified type. If no such parts are found, the list is empty. + * @throws InvalidOperationException If called on a write-only package. + * @throws IllegalArgumentException if relationshipType input param is null. + */ + public ArrayList getPartsByRelationshipType( + String relationshipType) { + if (relationshipType == null) { + throw new IllegalArgumentException("relationshipType"); + } + ArrayList retArr = new ArrayList<>(); + for (PackageRelationship rel : getRelationshipsByType(relationshipType)) { + PackagePart part = getPart(rel); + if (part != null) { + retArr.add(part); + } + } + Collections.sort(retArr); + return retArr; + } + + /** + * Retrieve parts by name + * + * @param namePattern + * The pattern for matching the names + * @return All parts associated to the specified content type, sorted + * in alphanumerically by the part-name + */ + public List getPartsByName(final Pattern namePattern) { + if (namePattern == null) { + throw new IllegalArgumentException("name pattern must not be null"); + } + Matcher matcher = namePattern.matcher(""); + ArrayList result = new ArrayList<>(); + for (PackagePart part : partList.sortedValues()) { + PackagePartName partName = part.getPartName(); + if (matcher.reset(partName.getName()).matches()) { + result.add(part); + } + } + return result; + } + + /** + * Get the target part from the specified relationship. + * + * @param partRel + * The part relationship uses to retrieve the part. + */ + public PackagePart getPart(PackageRelationship partRel) { + PackagePart retPart = null; + ensureRelationships(); + for (PackageRelationship rel : relationships) { + if (rel.getRelationshipType().equals(partRel.getRelationshipType())) { + try { + retPart = getPart(PackagingURIHelper.createPartName(rel + .getTargetURI())); + } catch (InvalidFormatException e) { + continue; + } + break; + } + } + return retPart; + } + + /** + * Load the parts of the archive if it has not been done yet. The + * relationships of each part are not loaded. + * + * Note - Rule M4.1 states that there may only ever be one Core + * Properties Part, but Office produced files will sometimes + * have multiple! As Office ignores all but the first, we relax + * Compliance with Rule M4.1, and ignore all others silently too. + * + * @return All this package's parts. + * @throws InvalidFormatException if the package is not valid. + */ + public ArrayList getParts() throws InvalidFormatException { + throwExceptionIfWriteOnly(); + + // If the part list is null, we parse the package to retrieve all parts. + if (partList == null) { + /* Variables use to validate OPC Compliance */ + + // Check rule M4.1 -> A format consumer shall consider more than + // one core properties relationship for a package to be an error + // (We just log it and move on, as real files break this!) + boolean hasCorePropertiesPart = false; + boolean needCorePropertiesPart = true; + + partList = getPartsImpl(); + for (PackagePart part : new ArrayList<>(partList.sortedValues())) { + part.loadRelationships(); + + // Check OPC compliance rule M4.1 + if (ContentTypes.CORE_PROPERTIES_PART.equals(part.getContentType())) { + if (!hasCorePropertiesPart) { + hasCorePropertiesPart = true; + } else { + LOG.atWarn().log("OPC Compliance error [M4.1]: " + + "there is more than one core properties relationship in the package! " + + "POI will use only the first, but other software may reject this file."); + } + } + + PartUnmarshaller partUnmarshaller = partUnmarshallers.get(part._contentType); + + if (partUnmarshaller != null) { + UnmarshallContext context = new UnmarshallContext(this, part._partName); + try { + PackagePart unmarshallPart = partUnmarshaller.unmarshall(context, part.getInputStream()); + partList.remove(part.getPartName()); + partList.put(unmarshallPart._partName, unmarshallPart); + + // Core properties case-- use first CoreProperties part we come across + // and ignore any subsequent ones + if (unmarshallPart instanceof PackagePropertiesPart && + hasCorePropertiesPart && + needCorePropertiesPart) { + this.packageProperties = (PackagePropertiesPart) unmarshallPart; + needCorePropertiesPart = false; + } + } catch (IOException ioe) { + LOG.atWarn().log("Unmarshall operation : IOException for {}", part._partName); + } catch (InvalidOperationException invoe) { + throw new InvalidFormatException(invoe.getMessage(), invoe); + } + } + } + } + return new ArrayList<>(partList.sortedValues()); + } + + /** + * Create and add a part, with the specified name and content type, to the + * package. + * + * @param partName + * Part name. + * @param contentType + * Part content type. + * @return The newly created part. + * @throws PartAlreadyExistsException + * If rule M1.12 is not verified : Packages shall not contain + * equivalent part names and package implementers shall neither + * create nor recognize packages with equivalent part names. + * @see #createPartImpl(PackagePartName, String, boolean) + */ + public PackagePart createPart(PackagePartName partName, String contentType) { + return this.createPart(partName, contentType, true); + } + + /** + * Create and add a part, with the specified name and content type, to the + * package. For general purpose, prefer the overload version of this method + * without the 'loadRelationships' parameter. + * + * @param partName + * Part name. + * @param contentType + * Part content type. + * @param loadRelationships + * Specify if the existing relationship part, if any, logically + * associated to the newly created part will be loaded. + * @return The newly created part. + * @throws PartAlreadyExistsException + * If rule M1.12 is not verified : Packages shall not contain + * equivalent part names and package implementers shall neither + * create nor recognize packages with equivalent part names. + * @see #createPartImpl(PackagePartName, String, boolean) + */ + PackagePart createPart(PackagePartName partName, String contentType, + boolean loadRelationships) { + throwExceptionIfReadOnly(); + if (partName == null) { + throw new IllegalArgumentException("partName"); + } + + if (contentType == null || contentType.isEmpty()) { + throw new IllegalArgumentException("contentType"); + } + + // Check if the specified part name already exists + if (partList.containsKey(partName) + && !partList.get(partName).isDeleted()) { + throw new PartAlreadyExistsException( + "A part with the name '" + partName.getName() + "'" + + " already exists : Packages shall not contain equivalent part names and package" + + " implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); + } + + /* Check OPC compliance */ + + // Rule [M4.1]: The format designer shall specify and the format producer + // shall create at most one core properties relationship for a package. + // A format consumer shall consider more than one core properties + // relationship for a package to be an error. If present, the + // relationship shall target the Core Properties part. + // Note - POI will read files with more than one Core Properties, which + // Office sometimes produces, but is strict on generation + if (contentType.equals(ContentTypes.CORE_PROPERTIES_PART)) { + if (this.packageProperties != null) { + throw new InvalidOperationException( + "OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !"); + } + } + + /* End check OPC compliance */ + + PackagePart part = this.createPartImpl(partName, contentType, + loadRelationships); + + /* check/create default entries - for bug54803 */ + try { + PackagePartName ppn = PackagingURIHelper.createPartName("/."+EXTENSION_XML); + contentTypeManager.addContentType(ppn, PLAIN_OLD_XML); + ppn = PackagingURIHelper.createPartName("/"+RELATIONSHIP_PART_EXTENSION_NAME); + contentTypeManager.addContentType(ppn, RELATIONSHIPS_PART); + } catch (InvalidFormatException e) { + throw new InvalidOperationException("unable to create default content-type entries.", e); + } + + this.contentTypeManager.addContentType(partName, contentType); + this.partList.put(partName, part); + this.isDirty = true; + return part; + } + + /** + * Add a part to the package. + * + * @param partName + * Part name of the part to create. + * @param contentType + * type associated with the file + * @param content + * the contents to add. In order to have faster operation in + * document merge, the data are stored in memory not on a hard + * disk + * + * @return The new part. + * @see #createPart(PackagePartName, String) + */ + public PackagePart createPart(PackagePartName partName, String contentType, + ByteArrayOutputStream content) { + PackagePart addedPart = this.createPart(partName, contentType); + if (addedPart == null) { + return null; + } + // Extract the zip entry content to put it in the part content + if (content != null) { + try (OutputStream partOutput = addedPart.getOutputStream()) { + if (partOutput == null) { + return null; + } + content.writeTo(partOutput); + } catch (IOException ignored) { + return null; + } + } else { + return null; + } + return addedPart; + } + + /** + * Add the specified part to the package. If a part already exists in the + * package with the same name as the one specified, then we replace the old + * part by the specified part. + * + * @param part + * The part to add (or replace). + * @return The part added to the package, the same as the one specified. + * @throws InvalidOperationException + * If rule M1.12 is not verified : Packages shall not contain + * equivalent part names and package implementers shall neither + * create nor recognize packages with equivalent part names. + */ + protected PackagePart addPackagePart(PackagePart part) { + throwExceptionIfReadOnly(); + if (part == null) { + throw new IllegalArgumentException("part"); + } + + if (partList.containsKey(part._partName)) { + if (!partList.get(part._partName).isDeleted()) { + throw new InvalidOperationException( + "A part with the name '" + + part._partName.getName() + + "' already exists : Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); + } + // If the specified partis flagged as deleted, we make it + // available + part.setDeleted(false); + // and delete the old part to replace it thereafeter + this.partList.remove(part._partName); + } + this.partList.put(part._partName, part); + this.isDirty = true; + return part; + } + + /** + * Remove the specified part in this package. If this part is relationship + * part, then delete all relationships in the source part. + * + * @param part + * The part to remove. If {@code null}, skip the action. + * @see #removePart(PackagePartName) + */ + public void removePart(PackagePart part) { + if (part != null) { + removePart(part.getPartName()); + } + } + + /** + * Remove a part in this package. If this part is relationship part, then + * delete all relationships in the source part. + * + * @param partName + * The part name of the part to remove. + */ + public void removePart(PackagePartName partName) { + throwExceptionIfReadOnly(); + if (partName == null || !this.containPart(partName)) { + throw new IllegalArgumentException("partName"); + } + + // Delete the specified part from the package. + if (this.partList.containsKey(partName)) { + this.partList.get(partName).setDeleted(true); + this.removePartImpl(partName); + this.partList.remove(partName); + } else { + this.removePartImpl(partName); + } + + // Delete content type + this.contentTypeManager.removeContentType(partName); + + // If this part is a relationship part, then delete all relationships of + // the source part. + if (partName.isRelationshipPartURI()) { + URI sourceURI = PackagingURIHelper + .getSourcePartUriFromRelationshipPartUri(partName.getURI()); + PackagePartName sourcePartName; + try { + sourcePartName = PackagingURIHelper.createPartName(sourceURI); + } catch (InvalidFormatException e) { + LOG.atError().log("Part name URI '{}' is not valid! This message is not intended to be displayed!", sourceURI); + return; + } + if (sourcePartName.getURI().equals( + PackagingURIHelper.PACKAGE_ROOT_URI)) { + clearRelationships(); + } else if (containPart(sourcePartName)) { + PackagePart part = getPart(sourcePartName); + if (part != null) { + part.clearRelationships(); + } + } + } + + this.isDirty = true; + } + + /** + * Remove a part from this package as well as its relationship part, if one + * exists, and all parts listed in the relationship part. Be aware that this + * do not delete relationships which target the specified part. + * + * @param partName + * The name of the part to delete. + * @throws InvalidFormatException + * Throws if the associated relationship part of the specified + * part is not valid. + */ + public void removePartRecursive(PackagePartName partName) + throws InvalidFormatException { + // Retrieves relationship part, if one exists + PackagePart relPart = this.partList.get(PackagingURIHelper + .getRelationshipPartName(partName)); + // Retrieves PackagePart object from the package + PackagePart partToRemove = this.partList.get(partName); + + if (relPart != null) { + PackageRelationshipCollection partRels = new PackageRelationshipCollection( + partToRemove); + for (PackageRelationship rel : partRels) { + PackagePartName partNameToRemove = PackagingURIHelper + .createPartName(PackagingURIHelper.resolvePartUri(rel + .getSourceURI(), rel.getTargetURI())); + removePart(partNameToRemove); + } + + // Finally delete its relationship part if one exists + this.removePart(relPart._partName); + } + + // Delete the specified part + this.removePart(partToRemove._partName); + } + + /** + * Delete the part with the specified name and its associated relationships + * part if one exists. Prefer the use of this method to delete a part in the + * package, compare to the remove() methods that don't remove associated + * relationships part. + * + * @param partName + * Name of the part to delete + */ + public void deletePart(PackagePartName partName) { + if (partName == null) { + throw new IllegalArgumentException("partName"); + } + + // Remove the part + this.removePart(partName); + // Remove the relationships part + this.removePart(PackagingURIHelper.getRelationshipPartName(partName)); + } + + /** + * Delete the part with the specified name and all part listed in its + * associated relationships part if one exists. This process is recursively + * apply to all parts in the relationships part of the specified part. + * Prefer the use of this method to delete a part in the package, compare to + * the remove() methods that don't remove associated relationships part. + * + * @param partName + * Name of the part to delete + */ + public void deletePartRecursive(PackagePartName partName) { + if (partName == null || !this.containPart(partName)) { + throw new IllegalArgumentException("partName"); + } + + PackagePart partToDelete = this.getPart(partName); + // Remove the part + this.removePart(partName); + // Remove all relationship parts associated + try { + for (PackageRelationship relationship : partToDelete + .getRelationships()) { + PackagePartName targetPartName = PackagingURIHelper + .createPartName(PackagingURIHelper.resolvePartUri( + partName.getURI(), relationship.getTargetURI())); + this.deletePartRecursive(targetPartName); + } + } catch (InvalidFormatException e) { + LOG.atWarn().withThrowable(e).log("An exception occurs while deleting part '{}'. Some parts may remain in the package.", partName.getName()); + return; + } + // Remove the relationships part + PackagePartName relationshipPartName = PackagingURIHelper + .getRelationshipPartName(partName); + if (relationshipPartName != null && containPart(relationshipPartName)) { + this.removePart(relationshipPartName); + } + } + + /** + * Check if a part already exists in this package from its name. + * + * @param partName + * Part name to check. + * @return true if the part is logically added to this package, else + * false. + */ + public boolean containPart(PackagePartName partName) { + return (this.getPart(partName) != null); + } + + /** + * Add a relationship to the package (except relationships part). + * + * Check rule M4.1 : The format designer shall specify and the format + * producer shall create at most one core properties relationship for a + * package. A format consumer shall consider more than one core properties + * relationship for a package to be an error. If present, the relationship + * shall target the Core Properties part. + * + * Check rule M1.25: The Relationships part shall not have relationships to + * any other part. Package implementers shall enforce this requirement upon + * the attempt to create such a relationship and shall treat any such + * relationship as invalid. + * + * @param targetPartName + * Target part name. + * @param targetMode + * Target mode, either Internal or External. + * @param relationshipType + * Relationship type. + * @param relID + * ID of the relationship. + * @see PackageRelationshipTypes + */ + @Override + public PackageRelationship addRelationship(PackagePartName targetPartName, + TargetMode targetMode, String relationshipType, String relID) { + /* Check OPC compliance */ + + // Check rule M4.1 : The format designer shall specify and the format + // producer + // shall create at most one core properties relationship for a package. + // A format consumer shall consider more than one core properties + // relationship for a package to be an error. If present, the + // relationship shall target the Core Properties part. + if (relationshipType.equals(PackageRelationshipTypes.CORE_PROPERTIES) + && this.packageProperties != null) { + throw new InvalidOperationException( + "OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead."); + } + + /* + * Check rule M1.25: The Relationships part shall not have relationships + * to any other part. Package implementers shall enforce this + * requirement upon the attempt to create such a relationship and shall + * treat any such relationship as invalid. + */ + if (targetPartName.isRelationshipPartURI()) { + throw new InvalidOperationException( + "Rule M1.25: The Relationships part shall not have relationships to any other part."); + } + + /* End OPC compliance */ + + ensureRelationships(); + PackageRelationship retRel = relationships.addRelationship( + targetPartName.getURI(), targetMode, relationshipType, relID); + this.isDirty = true; + return retRel; + } + + /** + * Add a package relationship. + * + * @param targetPartName + * Target part name. + * @param targetMode + * Target mode, either Internal or External. + * @param relationshipType + * Relationship type. + * @see PackageRelationshipTypes + */ + @Override + public PackageRelationship addRelationship(PackagePartName targetPartName, + TargetMode targetMode, String relationshipType) { + return this.addRelationship(targetPartName, targetMode, + relationshipType, null); + } + + /** + * Adds an external relationship to a part (except relationships part). + * + * The targets of external relationships are not subject to the same + * validity checks that internal ones are, as the contents is potentially + * any file, URL or similar. + * + * @param target + * External target of the relationship + * @param relationshipType + * Type of relationship. + * @return The newly created and added relationship + */ + @Override + public PackageRelationship addExternalRelationship(String target, + String relationshipType) { + return addExternalRelationship(target, relationshipType, null); + } + + /** + * Adds an external relationship to a part (except relationships part). + * + * The targets of external relationships are not subject to the same + * validity checks that internal ones are, as the contents is potentially + * any file, URL or similar. + * + * @param target + * External target of the relationship + * @param relationshipType + * Type of relationship. + * @param id + * Relationship unique id. + * @return The newly created and added relationship + * @see RelationshipSource#addExternalRelationship(String, + * String) + */ + @Override + public PackageRelationship addExternalRelationship(String target, + String relationshipType, String id) { + if (target == null) { + throw new IllegalArgumentException("target"); + } + if (relationshipType == null) { + throw new IllegalArgumentException("relationshipType"); + } + + URI targetURI; + try { + targetURI = new URI(target); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid target - " + e); + } + + ensureRelationships(); + PackageRelationship retRel = relationships.addRelationship(targetURI, + TargetMode.EXTERNAL, relationshipType, id); + this.isDirty = true; + return retRel; + } + + /** + * Delete a relationship from this package. + * + * @param id + * Id of the relationship to delete. + */ + @Override + public void removeRelationship(String id) { + if (relationships != null) { + relationships.removeRelationship(id); + this.isDirty = true; + } + } + + /** + * Retrieves all package relationships. + * + * @return All package relationships of this package. + * @throws InvalidOperationException if a read operation is done on a write only package. + * @see #getRelationshipsHelper(String) + */ + @Override public PackageRelationshipCollection getRelationships() { - return getRelationshipsHelper(null); - } + return getRelationshipsHelper(null); + } - /** - * Retrieves all relationships with the specified type. - * - * @param relationshipType - * The filter specifying the relationship type. - * @return All relationships with the specified relationship type. - */ - @Override + /** + * Retrieves all relationships with the specified type. + * + * @param relationshipType + * The filter specifying the relationship type. + * @return All relationships with the specified relationship type. + */ + @Override public PackageRelationshipCollection getRelationshipsByType( - String relationshipType) { - throwExceptionIfWriteOnly(); - if (relationshipType == null) { - throw new IllegalArgumentException("relationshipType"); - } - return getRelationshipsHelper(relationshipType); - } + String relationshipType) { + throwExceptionIfWriteOnly(); + if (relationshipType == null) { + throw new IllegalArgumentException("relationshipType"); + } + return getRelationshipsHelper(relationshipType); + } - /** - * Retrieves all relationships with specified id (normally just ine because - * a relationship id is supposed to be unique). - * - * @param id - * Id of the wanted relationship. - */ - private PackageRelationshipCollection getRelationshipsHelper(String id) { - throwExceptionIfWriteOnly(); - ensureRelationships(); - return this.relationships.getRelationships(id); - } + /** + * Retrieves all relationships with specified id (normally just ine because + * a relationship id is supposed to be unique). + * + * @param id + * Id of the wanted relationship. + */ + private PackageRelationshipCollection getRelationshipsHelper(String id) { + throwExceptionIfWriteOnly(); + ensureRelationships(); + return this.relationships.getRelationships(id); + } - /** - * Clear package relationships. - */ - @Override + /** + * Clear package relationships. + */ + @Override public void clearRelationships() { - if (relationships != null) { - relationships.clear(); - this.isDirty = true; - } - } + if (relationships != null) { + relationships.clear(); + this.isDirty = true; + } + } - /** - * Ensure that the relationships collection is not null. - */ - public void ensureRelationships() { - if (this.relationships == null) { - try { - this.relationships = new PackageRelationshipCollection(this); - } catch (InvalidFormatException e) { - this.relationships = new PackageRelationshipCollection(); - } - } - } + /** + * Ensure that the relationships collection is not null. + */ + public void ensureRelationships() { + if (this.relationships == null) { + try { + this.relationships = new PackageRelationshipCollection(this); + } catch (InvalidFormatException e) { + this.relationships = new PackageRelationshipCollection(); + } + } + } - @Override + @Override public PackageRelationship getRelationship(String id) { - return this.relationships.getRelationshipByID(id); - } + return this.relationships.getRelationshipByID(id); + } - @Override + @Override public boolean hasRelationships() { - return (relationships.size() > 0); - } + return (relationships.size() > 0); + } - @Override + @Override public boolean isRelationshipExists(PackageRelationship rel) { for (PackageRelationship r : relationships) { if (r == rel) { @@ -1359,201 +1359,201 @@ public abstract class OPCPackage implements RelationshipSource, Closeable { } } return false; - } + } - /** - * Add a marshaller. - * - * @param contentType - * The content type to bind to the specified marshaller. - * @param marshaller - * The marshaller to register with the specified content type. - */ - public void addMarshaller(String contentType, PartMarshaller marshaller) { - try { - partMarshallers.put(new ContentType(contentType), marshaller); - } catch (InvalidFormatException e) { - LOG.atWarn().log("The specified content type is not valid: '{}'. The marshaller will not be added !", e.getMessage()); - } - } + /** + * Add a marshaller. + * + * @param contentType + * The content type to bind to the specified marshaller. + * @param marshaller + * The marshaller to register with the specified content type. + */ + public void addMarshaller(String contentType, PartMarshaller marshaller) { + try { + partMarshallers.put(new ContentType(contentType), marshaller); + } catch (InvalidFormatException e) { + LOG.atWarn().log("The specified content type is not valid: '{}'. The marshaller will not be added !", e.getMessage()); + } + } - /** - * Add an unmarshaller. - * - * @param contentType - * The content type to bind to the specified unmarshaller. - * @param unmarshaller - * The unmarshaller to register with the specified content type. - */ - public void addUnmarshaller(String contentType, - PartUnmarshaller unmarshaller) { - try { - partUnmarshallers.put(new ContentType(contentType), unmarshaller); - } catch (InvalidFormatException e) { - LOG.atWarn().log("The specified content type is not valid: '{}'. The unmarshaller will not be added !", e.getMessage()); - } - } + /** + * Add an unmarshaller. + * + * @param contentType + * The content type to bind to the specified unmarshaller. + * @param unmarshaller + * The unmarshaller to register with the specified content type. + */ + public void addUnmarshaller(String contentType, + PartUnmarshaller unmarshaller) { + try { + partUnmarshallers.put(new ContentType(contentType), unmarshaller); + } catch (InvalidFormatException e) { + LOG.atWarn().log("The specified content type is not valid: '{}'. The unmarshaller will not be added !", e.getMessage()); + } + } - /** - * Remove a marshaller by its content type. - * - * @param contentType - * The content type associated with the marshaller to remove. - */ - public void removeMarshaller(String contentType) { - try { + /** + * Remove a marshaller by its content type. + * + * @param contentType + * The content type associated with the marshaller to remove. + */ + public void removeMarshaller(String contentType) { + try { partMarshallers.remove(new ContentType(contentType)); } catch (InvalidFormatException e) { throw new RuntimeException(e); } - } + } - /** - * Remove an unmarshaller by its content type. - * - * @param contentType - * The content type associated with the unmarshaller to remove. - */ - public void removeUnmarshaller(String contentType) { + /** + * Remove an unmarshaller by its content type. + * + * @param contentType + * The content type associated with the unmarshaller to remove. + */ + public void removeUnmarshaller(String contentType) { try { partUnmarshallers.remove(new ContentType(contentType)); } catch (InvalidFormatException e) { throw new RuntimeException(e); } - } + } - /* Accesseurs */ + /* Accesseurs */ - /** - * Get the package access mode. - * - * @return the packageAccess The current package access. - */ - public PackageAccess getPackageAccess() { - return packageAccess; - } + /** + * Get the package access mode. + * + * @return the packageAccess The current package access. + */ + public PackageAccess getPackageAccess() { + return packageAccess; + } - /** - * Validates the package compliance with the OPC specifications. - * - * @return true if the package is valid else false - */ - @NotImplemented - public boolean validatePackage(OPCPackage pkg) throws InvalidFormatException { - throw new InvalidOperationException("Not implemented yet !!!"); - } + /** + * Validates the package compliance with the OPC specifications. + * + * @return true if the package is valid else false + */ + @NotImplemented + public boolean validatePackage(OPCPackage pkg) throws InvalidFormatException { + throw new InvalidOperationException("Not implemented yet !!!"); + } - /** - * Save the document in the specified file. - * - * @param targetFile - * Destination file. - * @throws IOException - * Throws if an IO exception occur. - * @see #save(OutputStream) - */ - public void save(File targetFile) throws IOException { - if (targetFile == null) { - throw new IllegalArgumentException("targetFile"); - } + /** + * Save the document in the specified file. + * + * @param targetFile + * Destination file. + * @throws IOException + * Throws if an IO exception occur. + * @see #save(OutputStream) + */ + public void save(File targetFile) throws IOException { + if (targetFile == null) { + throw new IllegalArgumentException("targetFile"); + } - this.throwExceptionIfReadOnly(); + this.throwExceptionIfReadOnly(); - // You shouldn't save the the same file, do a close instead - if(targetFile.exists() && - targetFile.getAbsolutePath().equals(this.originalPackagePath)) { - throw new InvalidOperationException( - "You can't call save(File) to save to the currently open " + - "file. To save to the current file, please just call close()" - ); - } + // You shouldn't save the the same file, do a close instead + if(targetFile.exists() && + targetFile.getAbsolutePath().equals(this.originalPackagePath)) { + throw new InvalidOperationException( + "You can't call save(File) to save to the currently open " + + "file. To save to the current file, please just call close()" + ); + } - // Do the save - try (FileOutputStream fos = new FileOutputStream(targetFile)) { - this.save(fos); - } - } + // Do the save + try (FileOutputStream fos = new FileOutputStream(targetFile)) { + this.save(fos); + } + } - /** - * Save the document in the specified output stream. - * - * @param outputStream - * The stream to save the package. - * @see #saveImpl(OutputStream) - */ - public void save(OutputStream outputStream) throws IOException { - throwExceptionIfReadOnly(); - this.saveImpl(outputStream); - } + /** + * Save the document in the specified output stream. + * + * @param outputStream + * The stream to save the package. + * @see #saveImpl(OutputStream) + */ + public void save(OutputStream outputStream) throws IOException { + throwExceptionIfReadOnly(); + this.saveImpl(outputStream); + } - /** - * Core method to create a package part. This method must be implemented by - * the subclass. - * - * @param partName - * URI of the part to create. - * @param contentType - * Content type of the part to create. - * @return The newly created package part. - */ - protected abstract PackagePart createPartImpl(PackagePartName partName, - String contentType, boolean loadRelationships); + /** + * Core method to create a package part. This method must be implemented by + * the subclass. + * + * @param partName + * URI of the part to create. + * @param contentType + * Content type of the part to create. + * @return The newly created package part. + */ + protected abstract PackagePart createPartImpl(PackagePartName partName, + String contentType, boolean loadRelationships); - /** - * Core method to delete a package part. This method must be implemented by - * the subclass. - * - * @param partName - * The URI of the part to delete. - */ - protected abstract void removePartImpl(PackagePartName partName); + /** + * Core method to delete a package part. This method must be implemented by + * the subclass. + * + * @param partName + * The URI of the part to delete. + */ + protected abstract void removePartImpl(PackagePartName partName); - /** - * Flush the package but not save. - */ - protected abstract void flushImpl(); + /** + * Flush the package but not save. + */ + protected abstract void flushImpl(); - /** - * Close the package and cause a save of the package. - * - */ - protected abstract void closeImpl() throws IOException; + /** + * Close the package and cause a save of the package. + * + */ + protected abstract void closeImpl() throws IOException; - /** - * Close the package without saving the document. Discard all changes made - * to this package. - */ - protected abstract void revertImpl(); + /** + * Close the package without saving the document. Discard all changes made + * to this package. + */ + protected abstract void revertImpl(); - /** - * Save the package into the specified output stream. - * - * @param outputStream - * The output stream use to save this package. - */ - protected abstract void saveImpl(OutputStream outputStream) - throws IOException; + /** + * Save the package into the specified output stream. + * + * @param outputStream + * The output stream use to save this package. + */ + protected abstract void saveImpl(OutputStream outputStream) + throws IOException; - /** - * Get all parts link to the package. - * - * @return A list of the part owned by the package. - */ - protected abstract PackagePartCollection getPartsImpl() - throws InvalidFormatException; + /** + * Get all parts link to the package. + * + * @return A list of the part owned by the package. + */ + protected abstract PackagePartCollection getPartsImpl() + throws InvalidFormatException; /** * Replace a content type in this package.

* A typical scneario to call this method is to rename a template file to the main format, e.g. - *

    + *
      *
    • ".dotx" to ".docx"
    • *
    • ".dotm" to ".docm"
    • *
    • ".xltx" to ".xlsx"
    • *
    • ".xltm" to ".xlsm"
    • *
    • ".potx" to ".pptx"
    • *
    • ".potm" to ".pptm"
    • - *
    + *
* For example, a code converting a .xlsm macro workbook to .xlsx would look as follows: *
{@code
      *
@@ -1634,29 +1634,29 @@ public abstract class OPCPackage implements RelationshipSource, Closeable {
         return partList.getUnusedPartIndex(nameTemplate);
     }
 
-	/**
-	 * @return true if the package is in Strict OOXML format
-	 * @since POI 5.0.1
-	 */
+    /**
+     * @return true if the package is in Strict OOXML format
+     * @since POI 5.0.1
+     */
     public boolean isStrictOoxmlFormat() {
-		PackageRelationshipCollection coreDocRelationships = getRelationshipsByType(
-				PackageRelationshipTypes.STRICT_CORE_DOCUMENT);
-		return coreDocRelationships.size() > 0;
-	}
+        PackageRelationshipCollection coreDocRelationships = getRelationshipsByType(
+                PackageRelationshipTypes.STRICT_CORE_DOCUMENT);
+        return coreDocRelationships.size() > 0;
+    }
 
-	/**
-	 * Has close been called already?
-	 */
-	public abstract boolean isClosed();
+    /**
+     * Has close been called already?
+     */
+    public abstract boolean isClosed();
 
-	@Override
-	public String toString() {
-		return "OPCPackage{" +
-				"packageAccess=" + packageAccess +
-				", relationships=" + relationships +
-				", packageProperties=" + packageProperties +
-				", isDirty=" + isDirty +
-				//", originalPackagePath='" + originalPackagePath + '\'' +
-				'}';
-	}
+    @Override
+    public String toString() {
+        return "OPCPackage{" +
+                "packageAccess=" + packageAccess +
+                ", relationships=" + relationships +
+                ", packageProperties=" + packageProperties +
+                ", isDirty=" + isDirty +
+                //", originalPackagePath='" + originalPackagePath + '\'' +
+                '}';
+    }
 }
diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackageNamespaces.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackageNamespaces.java
index a4e06abecd..d231bf7fe8 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackageNamespaces.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackageNamespaces.java
@@ -24,28 +24,28 @@ package org.apache.poi.openxml4j.opc;
  */
 public interface PackageNamespaces {
 
-	/**
-	 * Content Types.
-	 */
-	public static final String CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
+    /**
+     * Content Types.
+     */
+    public static final String CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
 
-	/**
-	 * Core Properties.
-	 */
-	public static final String CORE_PROPERTIES = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
+    /**
+     * Core Properties.
+     */
+    public static final String CORE_PROPERTIES = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
 
-	/**
-	 * Digital Signatures.
-	 */
-	public static final String DIGITAL_SIGNATURE = "http://schemas.openxmlformats.org/package/2006/digital-signature";
+    /**
+     * Digital Signatures.
+     */
+    public static final String DIGITAL_SIGNATURE = "http://schemas.openxmlformats.org/package/2006/digital-signature";
 
-	/**
-	 * Relationships.
-	 */
-	public static final String RELATIONSHIPS = "http://schemas.openxmlformats.org/package/2006/relationships";
+    /**
+     * Relationships.
+     */
+    public static final String RELATIONSHIPS = "http://schemas.openxmlformats.org/package/2006/relationships";
 
-	/**
-	 * Markup Compatibility.
-	 */
-	public static final String MARKUP_COMPATIBILITY = "http://schemas.openxmlformats.org/markup-compatibility/2006";
+    /**
+     * Markup Compatibility.
+     */
+    public static final String MARKUP_COMPATIBILITY = "http://schemas.openxmlformats.org/markup-compatibility/2006";
 }
diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackagePartCollection.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackagePartCollection.java
index a9d7b4589c..a5f3dfc258 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackagePartCollection.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackagePartCollection.java
@@ -36,7 +36,7 @@ import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
  */
 public final class PackagePartCollection implements Serializable {
 
-	private static final long serialVersionUID = 2515031135957635517L;
+    private static final long serialVersionUID = 2515031135957635517L;
 
     /**
      * HashSet use to store this collection part names as string for rule
@@ -44,73 +44,73 @@ public final class PackagePartCollection implements Serializable {
      */
     private final Set registerPartNameStr = new HashSet<>();
 
-	private final TreeMap packagePartLookup =
+    private final TreeMap packagePartLookup =
         new TreeMap<>(PackagePartName::compare);
 
 
-	/**
-	 * Check rule [M1.11]: a package implementer shall neither create nor
-	 * recognize a part with a part name derived from another part name by
-	 * appending segments to it.
-	 *
-	 * @param partName name of part
-	 * @param part part to put
+    /**
+     * Check rule [M1.11]: a package implementer shall neither create nor
+     * recognize a part with a part name derived from another part name by
+     * appending segments to it.
+     *
+     * @param partName name of part
+     * @param part part to put
      * @return the previous value associated with {@code partName}, or
      *         {@code null} if there was no mapping for {@code partName}.
-	 * @exception InvalidOperationException
-	 *                Throws if you try to add a part with a name derived from
-	 *                another part name.
-	 */
-	public PackagePart put(final PackagePartName partName, final PackagePart part) {
-	    final String ppName = partName.getName();
+     * @exception InvalidOperationException
+     *                Throws if you try to add a part with a name derived from
+     *                another part name.
+     */
+    public PackagePart put(final PackagePartName partName, final PackagePart part) {
+        final String ppName = partName.getName();
         final StringBuilder concatSeg = new StringBuilder();
         // split at slash, but keep leading slash
         final String delim = "(?=["+PackagingURIHelper.FORWARD_SLASH_STRING+".])";
-		for (String seg : ppName.split(delim)) {
-			concatSeg.append(seg);
-			if (registerPartNameStr.contains(concatSeg.toString())) {
-				throw new InvalidOperationException(
-					"You can't add a part with a part name derived from another part ! [M1.11]");
-			}
-		}
-		registerPartNameStr.add(ppName);
-		return packagePartLookup.put(ppName, part);
-	}
+        for (String seg : ppName.split(delim)) {
+            concatSeg.append(seg);
+            if (registerPartNameStr.contains(concatSeg.toString())) {
+                throw new InvalidOperationException(
+                    "You can't add a part with a part name derived from another part ! [M1.11]");
+            }
+        }
+        registerPartNameStr.add(ppName);
+        return packagePartLookup.put(ppName, part);
+    }
 
-	public PackagePart remove(PackagePartName key) {
-	    if (key == null) {
-	        return null;
-	    }
+    public PackagePart remove(PackagePartName key) {
+        if (key == null) {
+            return null;
+        }
         final String ppName = key.getName();
-	    PackagePart pp = packagePartLookup.remove(ppName);
-	    if (pp != null) {
-	        this.registerPartNameStr.remove(ppName);
-	    }
-		return pp;
-	}
+        PackagePart pp = packagePartLookup.remove(ppName);
+        if (pp != null) {
+            this.registerPartNameStr.remove(ppName);
+        }
+        return pp;
+    }
 
 
-	/**
-	 * The values themselves should be returned in sorted order. Doing it here
-	 * avoids paying the high cost of Natural Ordering per insertion.
+    /**
+     * The values themselves should be returned in sorted order. Doing it here
+     * avoids paying the high cost of Natural Ordering per insertion.
      * @return unmodifiable collection of parts
-	 */
-	public Collection sortedValues() {
-	    return Collections.unmodifiableCollection(packagePartLookup.values());
+     */
+    public Collection sortedValues() {
+        return Collections.unmodifiableCollection(packagePartLookup.values());
 
-	}
+    }
 
-	public boolean containsKey(PackagePartName partName) {
-		return partName != null && packagePartLookup.containsKey(partName.getName());
-	}
+    public boolean containsKey(PackagePartName partName) {
+        return partName != null && packagePartLookup.containsKey(partName.getName());
+    }
 
-	public PackagePart get(PackagePartName partName) {
-		return partName == null ? null : packagePartLookup.get(partName.getName());
-	}
+    public PackagePart get(PackagePartName partName) {
+        return partName == null ? null : packagePartLookup.get(partName.getName());
+    }
 
-	public int size() {
-		return packagePartLookup.size();
-	}
+    public int size() {
+        return packagePartLookup.size();
+    }
 
 
 
diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackagePartName.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackagePartName.java
index a5270c069d..9041e0b0eb 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackagePartName.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackagePartName.java
@@ -32,271 +32,271 @@ import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException;
  */
 public final class PackagePartName implements Comparable {
 
-	/**
-	 * Part name stored as an URI.
-	 */
-	private final URI partNameURI;
+    /**
+     * Part name stored as an URI.
+     */
+    private final URI partNameURI;
 
-	/*
-	 * URI Characters definition (RFC 3986)
-	 */
+    /*
+     * URI Characters definition (RFC 3986)
+     */
 
-	/**
-	 * Reserved characters for sub delimiters.
-	 */
-	private static final String RFC3986_PCHAR_SUB_DELIMS = "!$&'()*+,;=";
+    /**
+     * Reserved characters for sub delimiters.
+     */
+    private static final String RFC3986_PCHAR_SUB_DELIMS = "!$&'()*+,;=";
 
-	/**
-	 * Unreserved character (+ ALPHA & DIGIT).
-	 */
-	private static final String RFC3986_PCHAR_UNRESERVED_SUP = "-._~";
+    /**
+     * Unreserved character (+ ALPHA & DIGIT).
+     */
+    private static final String RFC3986_PCHAR_UNRESERVED_SUP = "-._~";
 
-	/**
-	 * Authorized reserved characters for pChar.
-	 */
-	private static final String RFC3986_PCHAR_AUTHORIZED_SUP = ":@";
+    /**
+     * Authorized reserved characters for pChar.
+     */
+    private static final String RFC3986_PCHAR_AUTHORIZED_SUP = ":@";
 
-	/**
-	 * Flag to know if this part name is from a relationship part name.
-	 */
-	private final boolean isRelationship;
+    /**
+     * Flag to know if this part name is from a relationship part name.
+     */
+    private final boolean isRelationship;
 
-	/**
-	 * Constructor. Makes a ValidPartName object from a java.net.URI
-	 *
-	 * @param uri
-	 *            The URI to validate and to transform into ValidPartName.
-	 * @param checkConformance
-	 *            Flag to specify if the constructor have to validate the OPC
-	 *            conformance. Must be always true except for
-	 *            special URI like '/' which is needed for internal use by
-	 *            OpenXML4J but is not valid.
-	 * @throws InvalidFormatException
-	 *             Throw if the specified part name is not conform to Open
-	 *             Packaging Convention specifications.
-	 * @see java.net.URI
-	 */
-	PackagePartName(URI uri, boolean checkConformance)
-			throws InvalidFormatException {
-		if (checkConformance) {
-			throwExceptionIfInvalidPartUri(uri);
-		} else {
-			if (!PackagingURIHelper.PACKAGE_ROOT_URI.equals(uri)) {
-				throw new OpenXML4JRuntimeException(
-						"OCP conformance must be check for ALL part name except special cases : ['/']");
-			}
-		}
-		this.partNameURI = uri;
-		this.isRelationship = isRelationshipPartURI(this.partNameURI);
-	}
+    /**
+     * Constructor. Makes a ValidPartName object from a java.net.URI
+     *
+     * @param uri
+     *            The URI to validate and to transform into ValidPartName.
+     * @param checkConformance
+     *            Flag to specify if the constructor have to validate the OPC
+     *            conformance. Must be always true except for
+     *            special URI like '/' which is needed for internal use by
+     *            OpenXML4J but is not valid.
+     * @throws InvalidFormatException
+     *             Throw if the specified part name is not conform to Open
+     *             Packaging Convention specifications.
+     * @see java.net.URI
+     */
+    PackagePartName(URI uri, boolean checkConformance)
+            throws InvalidFormatException {
+        if (checkConformance) {
+            throwExceptionIfInvalidPartUri(uri);
+        } else {
+            if (!PackagingURIHelper.PACKAGE_ROOT_URI.equals(uri)) {
+                throw new OpenXML4JRuntimeException(
+                        "OCP conformance must be check for ALL part name except special cases : ['/']");
+            }
+        }
+        this.partNameURI = uri;
+        this.isRelationship = isRelationshipPartURI(this.partNameURI);
+    }
 
-	/**
-	 * Constructor. Makes a ValidPartName object from a String part name.
-	 *
-	 * @param partName
-	 *            Part name to valid and to create.
-	 * @param checkConformance
-	 *            Flag to specify if the constructor have to validate the OPC
-	 *            conformance. Must be always true except for
-	 *            special URI like '/' which is needed for internal use by
-	 *            OpenXML4J but is not valid.
-	 * @throws InvalidFormatException
-	 *             Throw if the specified part name is not conform to Open
-	 *             Packaging Convention specifications.
-	 */
-	PackagePartName(String partName, boolean checkConformance)
-			throws InvalidFormatException {
-		URI partURI;
-		try {
-			partURI = new URI(partName);
-		} catch (URISyntaxException e) {
-			throw new IllegalArgumentException(
-					"partName argmument is not a valid OPC part name !");
-		}
+    /**
+     * Constructor. Makes a ValidPartName object from a String part name.
+     *
+     * @param partName
+     *            Part name to valid and to create.
+     * @param checkConformance
+     *            Flag to specify if the constructor have to validate the OPC
+     *            conformance. Must be always true except for
+     *            special URI like '/' which is needed for internal use by
+     *            OpenXML4J but is not valid.
+     * @throws InvalidFormatException
+     *             Throw if the specified part name is not conform to Open
+     *             Packaging Convention specifications.
+     */
+    PackagePartName(String partName, boolean checkConformance)
+            throws InvalidFormatException {
+        URI partURI;
+        try {
+            partURI = new URI(partName);
+        } catch (URISyntaxException e) {
+            throw new IllegalArgumentException(
+                    "partName argmument is not a valid OPC part name !");
+        }
 
-		if (checkConformance) {
-			throwExceptionIfInvalidPartUri(partURI);
-		} else {
-			if (!PackagingURIHelper.PACKAGE_ROOT_URI.equals(partURI)) {
-				throw new OpenXML4JRuntimeException(
-						"OCP conformance must be check for ALL part name except special cases : ['/']");
-			}
-		}
-		this.partNameURI = partURI;
-		this.isRelationship = isRelationshipPartURI(this.partNameURI);
-	}
+        if (checkConformance) {
+            throwExceptionIfInvalidPartUri(partURI);
+        } else {
+            if (!PackagingURIHelper.PACKAGE_ROOT_URI.equals(partURI)) {
+                throw new OpenXML4JRuntimeException(
+                        "OCP conformance must be check for ALL part name except special cases : ['/']");
+            }
+        }
+        this.partNameURI = partURI;
+        this.isRelationship = isRelationshipPartURI(this.partNameURI);
+    }
 
-	/**
-	 * Check if the specified part name is a relationship part name.
-	 *
-	 * @param partUri
-	 *            The URI to check.
-	 * @return true if this part name respect the relationship
-	 *         part naming convention else false.
-	 */
-	private boolean isRelationshipPartURI(URI partUri) {
-		if (partUri == null) {
+    /**
+     * Check if the specified part name is a relationship part name.
+     *
+     * @param partUri
+     *            The URI to check.
+     * @return true if this part name respect the relationship
+     *         part naming convention else false.
+     */
+    private boolean isRelationshipPartURI(URI partUri) {
+        if (partUri == null) {
             throw new IllegalArgumentException("partUri");
         }
 
-		return partUri.getPath().matches(
-				"^.*/" + PackagingURIHelper.RELATIONSHIP_PART_SEGMENT_NAME + "/.*\\"
-						+ PackagingURIHelper.RELATIONSHIP_PART_EXTENSION_NAME
-						+ "$");
-	}
+        return partUri.getPath().matches(
+                "^.*/" + PackagingURIHelper.RELATIONSHIP_PART_SEGMENT_NAME + "/.*\\"
+                        + PackagingURIHelper.RELATIONSHIP_PART_EXTENSION_NAME
+                        + "$");
+    }
 
-	/**
-	 * Know if this part name is a relationship part name.
-	 *
-	 * @return true if this part name respect the relationship
-	 *         part naming convention else false.
-	 */
-	public boolean isRelationshipPartURI() {
-		return this.isRelationship;
-	}
+    /**
+     * Know if this part name is a relationship part name.
+     *
+     * @return true if this part name respect the relationship
+     *         part naming convention else false.
+     */
+    public boolean isRelationshipPartURI() {
+        return this.isRelationship;
+    }
 
-	/**
-	 * Throws an exception (of any kind) if the specified part name does not
-	 * follow the Open Packaging Convention specifications naming rules.
-	 *
-	 * @param partUri
-	 *            The part name to check.
-	 * @throws InvalidFormatException
-	 *             Throws if the part name is invalid.
-	 */
-	private static void throwExceptionIfInvalidPartUri(URI partUri)
-			throws InvalidFormatException {
-		if (partUri == null) {
+    /**
+     * Throws an exception (of any kind) if the specified part name does not
+     * follow the Open Packaging Convention specifications naming rules.
+     *
+     * @param partUri
+     *            The part name to check.
+     * @throws InvalidFormatException
+     *             Throws if the part name is invalid.
+     */
+    private static void throwExceptionIfInvalidPartUri(URI partUri)
+            throws InvalidFormatException {
+        if (partUri == null) {
             throw new IllegalArgumentException("partUri");
         }
-		// Check if the part name URI is empty [M1.1]
-		throwExceptionIfEmptyURI(partUri);
+        // Check if the part name URI is empty [M1.1]
+        throwExceptionIfEmptyURI(partUri);
 
-		// Check if the part name URI is absolute
-		throwExceptionIfAbsoluteUri(partUri);
+        // Check if the part name URI is absolute
+        throwExceptionIfAbsoluteUri(partUri);
 
-		// Check if the part name URI starts with a forward slash [M1.4]
-		throwExceptionIfPartNameNotStartsWithForwardSlashChar(partUri);
+        // Check if the part name URI starts with a forward slash [M1.4]
+        throwExceptionIfPartNameNotStartsWithForwardSlashChar(partUri);
 
-		// Check if the part name URI ends with a forward slash [M1.5]
-		throwExceptionIfPartNameEndsWithForwardSlashChar(partUri);
+        // Check if the part name URI ends with a forward slash [M1.5]
+        throwExceptionIfPartNameEndsWithForwardSlashChar(partUri);
 
-		// Check if the part name does not have empty segments. [M1.3]
-		// Check if a segment ends with a dot ('.') character. [M1.9]
-		throwExceptionIfPartNameHaveInvalidSegments(partUri);
-	}
+        // Check if the part name does not have empty segments. [M1.3]
+        // Check if a segment ends with a dot ('.') character. [M1.9]
+        throwExceptionIfPartNameHaveInvalidSegments(partUri);
+    }
 
-	/**
-	 * Throws an exception if the specified URI is empty. [M1.1]
-	 *
-	 * @param partURI
-	 *            Part URI to check.
-	 * @throws InvalidFormatException
-	 *             If the specified URI is empty.
-	 */
-	private static void throwExceptionIfEmptyURI(URI partURI)
-			throws InvalidFormatException {
-		if (partURI == null) {
+    /**
+     * Throws an exception if the specified URI is empty. [M1.1]
+     *
+     * @param partURI
+     *            Part URI to check.
+     * @throws InvalidFormatException
+     *             If the specified URI is empty.
+     */
+    private static void throwExceptionIfEmptyURI(URI partURI)
+            throws InvalidFormatException {
+        if (partURI == null) {
             throw new IllegalArgumentException("partURI");
         }
 
-		String uriPath = partURI.getPath();
-		if (uriPath.length() == 0
-				|| ((uriPath.length() == 1) && (uriPath.charAt(0) == PackagingURIHelper.FORWARD_SLASH_CHAR))) {
+        String uriPath = partURI.getPath();
+        if (uriPath.length() == 0
+                || ((uriPath.length() == 1) && (uriPath.charAt(0) == PackagingURIHelper.FORWARD_SLASH_CHAR))) {
             throw new InvalidFormatException(
-					"A part name shall not be empty [M1.1]: "
-							+ partURI.getPath());
+                    "A part name shall not be empty [M1.1]: "
+                            + partURI.getPath());
         }
-	}
+    }
 
-	/**
-	 * Throws an exception if the part name has empty segments. [M1.3]
-	 *
-	 * Throws an exception if a segment any characters other than pchar
-	 * characters. [M1.6]
-	 *
-	 * Throws an exception if a segment contain percent-encoded forward slash
-	 * ('/'), or backward slash ('\') characters. [M1.7]
-	 *
-	 * Throws an exception if a segment contain percent-encoded unreserved
-	 * characters. [M1.8]
-	 *
-	 * Throws an exception if the specified part name's segments end with a dot
-	 * ('.') character. [M1.9]
-	 *
-	 * Throws an exception if a segment doesn't include at least one non-dot
-	 * character. [M1.10]
-	 *
-	 * @param partUri
-	 *            The part name to check.
-	 * @throws InvalidFormatException
-	 *             if the specified URI contain an empty segments or if one the
-	 *             segments contained in the part name, ends with a dot ('.')
-	 *             character.
-	 */
-	private static void throwExceptionIfPartNameHaveInvalidSegments(URI partUri)
-			throws InvalidFormatException {
-		if (partUri == null) {
-			throw new IllegalArgumentException("partUri");
-		}
-
-		// Split the URI into several part and analyze each
-		String[] segments = partUri.toASCIIString()
-	        .replaceFirst("^"+PackagingURIHelper.FORWARD_SLASH_CHAR,"")
-	        .split(PackagingURIHelper.FORWARD_SLASH_STRING);
-
-		if (segments.length < 1) {
-            throw new InvalidFormatException(
-				"A part name shall not have empty segments [M1.3]: " + partUri.getPath());
+    /**
+     * Throws an exception if the part name has empty segments. [M1.3]
+     *
+     * Throws an exception if a segment any characters other than pchar
+     * characters. [M1.6]
+     *
+     * Throws an exception if a segment contain percent-encoded forward slash
+     * ('/'), or backward slash ('\') characters. [M1.7]
+     *
+     * Throws an exception if a segment contain percent-encoded unreserved
+     * characters. [M1.8]
+     *
+     * Throws an exception if the specified part name's segments end with a dot
+     * ('.') character. [M1.9]
+     *
+     * Throws an exception if a segment doesn't include at least one non-dot
+     * character. [M1.10]
+     *
+     * @param partUri
+     *            The part name to check.
+     * @throws InvalidFormatException
+     *             if the specified URI contain an empty segments or if one the
+     *             segments contained in the part name, ends with a dot ('.')
+     *             character.
+     */
+    private static void throwExceptionIfPartNameHaveInvalidSegments(URI partUri)
+            throws InvalidFormatException {
+        if (partUri == null) {
+            throw new IllegalArgumentException("partUri");
         }
 
-		for (final String seg : segments) {
-			if (seg == null || seg.isEmpty()) {
-				throw new InvalidFormatException(
-					"A part name shall not have empty segments [M1.3]: " + partUri.getPath());
-			}
+        // Split the URI into several part and analyze each
+        String[] segments = partUri.toASCIIString()
+            .replaceFirst("^"+PackagingURIHelper.FORWARD_SLASH_CHAR,"")
+            .split(PackagingURIHelper.FORWARD_SLASH_STRING);
 
-			if (seg.endsWith(".")) {
-				throw new InvalidFormatException(
-					"A segment shall not end with a dot ('.') character [M1.9]: " + partUri.getPath());
-			}
+        if (segments.length < 1) {
+            throw new InvalidFormatException(
+                "A part name shall not have empty segments [M1.3]: " + partUri.getPath());
+        }
 
-			if (seg.replaceAll("\\\\.", "").isEmpty()) {
-				// Normally will never been invoked with the previous
-				// implementation rule [M1.9]
-				throw new InvalidFormatException(
-					"A segment shall include at least one non-dot character. [M1.10]: " + partUri.getPath());
-			}
+        for (final String seg : segments) {
+            if (seg == null || seg.isEmpty()) {
+                throw new InvalidFormatException(
+                    "A part name shall not have empty segments [M1.3]: " + partUri.getPath());
+            }
 
-			// Check for rule M1.6, M1.7, M1.8
-			checkPCharCompliance(seg);
-		}
-	}
+            if (seg.endsWith(".")) {
+                throw new InvalidFormatException(
+                    "A segment shall not end with a dot ('.') character [M1.9]: " + partUri.getPath());
+            }
 
-	/**
-	 * Throws an exception if a segment any characters other than pchar
-	 * characters. [M1.6]
-	 *
-	 * Throws an exception if a segment contain percent-encoded forward slash
-	 * ('/'), or backward slash ('\') characters. [M1.7]
-	 *
-	 * Throws an exception if a segment contain percent-encoded unreserved
-	 * characters. [M1.8]
-	 *
-	 * @param segment
-	 *            The segment to check
-	 */
-	private static void checkPCharCompliance(String segment)
-			throws InvalidFormatException {
-		final int length = segment.length();
-		for (int i = 0; i < length; ++i) {
-			final char c = segment.charAt(i);
+            if (seg.replaceAll("\\\\.", "").isEmpty()) {
+                // Normally will never been invoked with the previous
+                // implementation rule [M1.9]
+                throw new InvalidFormatException(
+                    "A segment shall include at least one non-dot character. [M1.10]: " + partUri.getPath());
+            }
 
-			/* Check rule M1.6 */
+            // Check for rule M1.6, M1.7, M1.8
+            checkPCharCompliance(seg);
+        }
+    }
 
-			if (
-    			// Check for digit or letter
-		        isDigitOrLetter(c) ||
+    /**
+     * Throws an exception if a segment any characters other than pchar
+     * characters. [M1.6]
+     *
+     * Throws an exception if a segment contain percent-encoded forward slash
+     * ('/'), or backward slash ('\') characters. [M1.7]
+     *
+     * Throws an exception if a segment contain percent-encoded unreserved
+     * characters. [M1.8]
+     *
+     * @param segment
+     *            The segment to check
+     */
+    private static void checkPCharCompliance(String segment)
+            throws InvalidFormatException {
+        final int length = segment.length();
+        for (int i = 0; i < length; ++i) {
+            final char c = segment.charAt(i);
+
+            /* Check rule M1.6 */
+
+            if (
+                // Check for digit or letter
+                isDigitOrLetter(c) ||
                 // Check "-", ".", "_", "~"
                 RFC3986_PCHAR_UNRESERVED_SUP.indexOf(c) > -1 ||
                 // Check ":", "@"
@@ -304,108 +304,108 @@ public final class PackagePartName implements Comparable {
                 // Check "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
                 RFC3986_PCHAR_SUB_DELIMS.indexOf(c) > -1
             ) {
-			    continue;
-			}
+                continue;
+            }
 
 
-			if (c != '%') {
-	            throw new InvalidFormatException(
+            if (c != '%') {
+                throw new InvalidFormatException(
                     "A segment shall not hold any characters other than pchar characters. [M1.6]");
-			}
+            }
 
-			// We certainly found an encoded character, check for length
-			// now ( '%' HEXDIGIT HEXDIGIT)
-			if ((length - i) < 2 || !isHexDigit(segment.charAt(i+1)) || !isHexDigit(segment.charAt(i+2))) {
-				throw new InvalidFormatException("The segment " + segment + " contain invalid encoded character !");
-			}
+            // We certainly found an encoded character, check for length
+            // now ( '%' HEXDIGIT HEXDIGIT)
+            if ((length - i) < 2 || !isHexDigit(segment.charAt(i+1)) || !isHexDigit(segment.charAt(i+2))) {
+                throw new InvalidFormatException("The segment " + segment + " contain invalid encoded character !");
+            }
 
-			// Decode the encoded character
-			final char decodedChar = (char) Integer.parseInt(segment.substring(i + 1, i + 3), 16);
-			i += 2;
+            // Decode the encoded character
+            final char decodedChar = (char) Integer.parseInt(segment.substring(i + 1, i + 3), 16);
+            i += 2;
 
-			/* Check rule M1.7 */
-			if (decodedChar == '/' || decodedChar == '\\') {
-				throw new InvalidFormatException(
-					"A segment shall not contain percent-encoded forward slash ('/'), or backward slash ('\') characters. [M1.7]");
-			}
+            /* Check rule M1.7 */
+            if (decodedChar == '/' || decodedChar == '\\') {
+                throw new InvalidFormatException(
+                    "A segment shall not contain percent-encoded forward slash ('/'), or backward slash ('\') characters. [M1.7]");
+            }
 
-			/* Check rule M1.8 */
-			if (
-			     // Check for unreserved character like define in RFC3986
-		        isDigitOrLetter(decodedChar) ||
-		        // Check for unreserved character "-", ".", "_", "~"
-		        RFC3986_PCHAR_UNRESERVED_SUP.indexOf(decodedChar) > -1
-	        ) {
+            /* Check rule M1.8 */
+            if (
+                 // Check for unreserved character like define in RFC3986
+                isDigitOrLetter(decodedChar) ||
+                // Check for unreserved character "-", ".", "_", "~"
+                RFC3986_PCHAR_UNRESERVED_SUP.indexOf(decodedChar) > -1
+            ) {
                 throw new InvalidFormatException(
                     "A segment shall not contain percent-encoded unreserved characters. [M1.8]");
-			}
-		}
-	}
-
-	/**
-	 * Throws an exception if the specified part name doesn't start with a
-	 * forward slash character '/'. [M1.4]
-	 *
-	 * @param partUri
-	 *            The part name to check.
-	 * @throws InvalidFormatException
-	 *             If the specified part name doesn't start with a forward slash
-	 *             character '/'.
-	 */
-	private static void throwExceptionIfPartNameNotStartsWithForwardSlashChar(
-			URI partUri) throws InvalidFormatException {
-		String uriPath = partUri.getPath();
-		if (uriPath.length() > 0
-				&& uriPath.charAt(0) != PackagingURIHelper.FORWARD_SLASH_CHAR) {
-            throw new InvalidFormatException(
-					"A part name shall start with a forward slash ('/') character [M1.4]: "
-							+ partUri.getPath());
+            }
         }
-	}
+    }
 
-	/**
-	 * Throws an exception if the specified part name ends with a forwar slash
-	 * character '/'. [M1.5]
-	 *
-	 * @param partUri
-	 *            The part name to check.
-	 * @throws InvalidFormatException
-	 *             If the specified part name ends with a forwar slash character
-	 *             '/'.
-	 */
-	private static void throwExceptionIfPartNameEndsWithForwardSlashChar(
-			URI partUri) throws InvalidFormatException {
-		String uriPath = partUri.getPath();
-		if (uriPath.length() > 0
-				&& uriPath.charAt(uriPath.length() - 1) == PackagingURIHelper.FORWARD_SLASH_CHAR) {
+    /**
+     * Throws an exception if the specified part name doesn't start with a
+     * forward slash character '/'. [M1.4]
+     *
+     * @param partUri
+     *            The part name to check.
+     * @throws InvalidFormatException
+     *             If the specified part name doesn't start with a forward slash
+     *             character '/'.
+     */
+    private static void throwExceptionIfPartNameNotStartsWithForwardSlashChar(
+            URI partUri) throws InvalidFormatException {
+        String uriPath = partUri.getPath();
+        if (uriPath.length() > 0
+                && uriPath.charAt(0) != PackagingURIHelper.FORWARD_SLASH_CHAR) {
             throw new InvalidFormatException(
-					"A part name shall not have a forward slash as the last character [M1.5]: "
-							+ partUri.getPath());
+                    "A part name shall start with a forward slash ('/') character [M1.4]: "
+                            + partUri.getPath());
         }
-	}
+    }
 
-	/**
-	 * Throws an exception if the specified URI is absolute.
-	 *
-	 * @param partUri
-	 *            The URI to check.
-	 * @throws InvalidFormatException
-	 *             Throws if the specified URI is absolute.
-	 */
-	private static void throwExceptionIfAbsoluteUri(URI partUri) throws InvalidFormatException {
-		if (partUri.isAbsolute()) {
+    /**
+     * Throws an exception if the specified part name ends with a forwar slash
+     * character '/'. [M1.5]
+     *
+     * @param partUri
+     *            The part name to check.
+     * @throws InvalidFormatException
+     *             If the specified part name ends with a forwar slash character
+     *             '/'.
+     */
+    private static void throwExceptionIfPartNameEndsWithForwardSlashChar(
+            URI partUri) throws InvalidFormatException {
+        String uriPath = partUri.getPath();
+        if (uriPath.length() > 0
+                && uriPath.charAt(uriPath.length() - 1) == PackagingURIHelper.FORWARD_SLASH_CHAR) {
+            throw new InvalidFormatException(
+                    "A part name shall not have a forward slash as the last character [M1.5]: "
+                            + partUri.getPath());
+        }
+    }
+
+    /**
+     * Throws an exception if the specified URI is absolute.
+     *
+     * @param partUri
+     *            The URI to check.
+     * @throws InvalidFormatException
+     *             Throws if the specified URI is absolute.
+     */
+    private static void throwExceptionIfAbsoluteUri(URI partUri) throws InvalidFormatException {
+        if (partUri.isAbsolute()) {
             throw new InvalidFormatException("Absolute URI forbidden: " + partUri);
         }
-	}
+    }
 
-	/**
-	 * Compare two part names following the rule M1.12 :
-	 *
-	 * Part name equivalence is determined by comparing part names as
-	 * case-insensitive ASCII strings. Packages shall not contain equivalent
-	 * part names and package implementers shall neither create nor recognize
-	 * packages with equivalent part names. [M1.12]
-	 */
+    /**
+     * Compare two part names following the rule M1.12 :
+     *
+     * Part name equivalence is determined by comparing part names as
+     * case-insensitive ASCII strings. Packages shall not contain equivalent
+     * part names and package implementers shall neither create nor recognize
+     * packages with equivalent part names. [M1.12]
+     */
     @Override
     public int compareTo(PackagePartName other) {
         // compare with natural sort order
@@ -413,64 +413,64 @@ public final class PackagePartName implements Comparable {
     }
 
 
-	/**
-	 * Retrieves the extension of the part name if any. If there is no extension
-	 * returns an empty String. Example : '/document/content.xml' => 'xml'
-	 *
-	 * @return The extension of the part name.
-	 */
-	public String getExtension() {
-		String fragment = this.partNameURI.getPath();
-		if (fragment.length() > 0) {
-			int i = fragment.lastIndexOf('.');
-			if (i > -1) {
+    /**
+     * Retrieves the extension of the part name if any. If there is no extension
+     * returns an empty String. Example : '/document/content.xml' => 'xml'
+     *
+     * @return The extension of the part name.
+     */
+    public String getExtension() {
+        String fragment = this.partNameURI.getPath();
+        if (fragment.length() > 0) {
+            int i = fragment.lastIndexOf('.');
+            if (i > -1) {
                 return fragment.substring(i + 1);
             }
-		}
-		return "";
-	}
+        }
+        return "";
+    }
 
-	/**
-	 * Get this part name.
-	 *
-	 * @return The name of this part name.
-	 */
-	public String getName() {
-		return getURI().toASCIIString();
-	}
+    /**
+     * Get this part name.
+     *
+     * @return The name of this part name.
+     */
+    public String getName() {
+        return getURI().toASCIIString();
+    }
 
-	/**
-	 * Part name equivalence is determined by comparing part names as
-	 * case-insensitive ASCII strings. Packages shall not contain equivalent
-	 * part names and package implementers shall neither create nor recognize
-	 * packages with equivalent part names. [M1.12]
-	 */
-	@Override
-	public boolean equals(Object other) {
+    /**
+     * Part name equivalence is determined by comparing part names as
+     * case-insensitive ASCII strings. Packages shall not contain equivalent
+     * part names and package implementers shall neither create nor recognize
+     * packages with equivalent part names. [M1.12]
+     */
+    @Override
+    public boolean equals(Object other) {
         return (other instanceof PackagePartName) &&
             compare(this.getName(), ((PackagePartName)other).getName()) == 0;
     }
 
-	@Override
-	public int hashCode() {
-		return getName().toLowerCase(Locale.ROOT).hashCode();
-	}
+    @Override
+    public int hashCode() {
+        return getName().toLowerCase(Locale.ROOT).hashCode();
+    }
 
-	@Override
-	public String toString() {
-		return getName();
-	}
+    @Override
+    public String toString() {
+        return getName();
+    }
 
-	/* Getters and setters */
+    /* Getters and setters */
 
-	/**
-	 * Part name property getter.
-	 *
-	 * @return This part name URI.
-	 */
-	public URI getURI() {
-		return this.partNameURI;
-	}
+    /**
+     * Part name property getter.
+     *
+     * @return This part name URI.
+     */
+    public URI getURI() {
+        return this.partNameURI;
+    }
 
 
     /**
@@ -489,10 +489,10 @@ public final class PackagePartName implements Comparable {
      * case-insensitive ASCII strings. Packages shall not contain equivalent
      * part names and package implementers shall neither create nor recognize
      * packages with equivalent part names. [M1.12]
-	 *
-	 * @param obj1 first {@code PackagePartName} to compare
-	 * @param obj2 second {@code PackagePartName} to compare
-	 * @return a negative integer, zero, or a positive integer as the first argument is less than,
+     *
+     * @param obj1 first {@code PackagePartName} to compare
+     * @param obj2 second {@code PackagePartName} to compare
+     * @return a negative integer, zero, or a positive integer as the first argument is less than,
      *         equal to, or greater than the second.
      */
     public static int compare(PackagePartName obj1, PackagePartName obj2) {
diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackageRelationship.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackageRelationship.java
index 4d68234f7e..bb7717492e 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackageRelationship.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/PackageRelationship.java
@@ -27,182 +27,182 @@ import java.util.Objects;
  */
 public final class PackageRelationship {
 
-	private static URI containerRelationshipPart;
+    private static URI containerRelationshipPart;
 
-	static {
-		try {
-			containerRelationshipPart = new URI("/_rels/.rels");
-		} catch (URISyntaxException e) {
-			// Do nothing
-		}
-	}
+    static {
+        try {
+            containerRelationshipPart = new URI("/_rels/.rels");
+        } catch (URISyntaxException e) {
+            // Do nothing
+        }
+    }
 
-	/* XML markup */
+    /* XML markup */
 
-	public static final String ID_ATTRIBUTE_NAME = "Id";
+    public static final String ID_ATTRIBUTE_NAME = "Id";
 
-	public static final String RELATIONSHIPS_TAG_NAME = "Relationships";
+    public static final String RELATIONSHIPS_TAG_NAME = "Relationships";
 
-	public static final String RELATIONSHIP_TAG_NAME = "Relationship";
+    public static final String RELATIONSHIP_TAG_NAME = "Relationship";
 
-	public static final String TARGET_ATTRIBUTE_NAME = "Target";
+    public static final String TARGET_ATTRIBUTE_NAME = "Target";
 
-	public static final String TARGET_MODE_ATTRIBUTE_NAME = "TargetMode";
+    public static final String TARGET_MODE_ATTRIBUTE_NAME = "TargetMode";
 
-	public static final String TYPE_ATTRIBUTE_NAME = "Type";
+    public static final String TYPE_ATTRIBUTE_NAME = "Type";
 
-	/* End XML markup */
+    /* End XML markup */
 
-	/**
-	 * Relation id.
-	 */
-	private final String id;
+    /**
+     * Relation id.
+     */
+    private final String id;
 
-	/**
-	 * Reference to the package.
-	 */
-	private final OPCPackage container;
+    /**
+     * Reference to the package.
+     */
+    private final OPCPackage container;
 
-	/**
-	 * Relationship type
-	 */
-	private final String relationshipType;
+    /**
+     * Relationship type
+     */
+    private final String relationshipType;
 
-	/**
-	 * Part of this relationship source
-	 */
-	private final PackagePart source;
+    /**
+     * Part of this relationship source
+     */
+    private final PackagePart source;
 
-	/**
-	 * Targeting mode [Internal|External]
-	 */
-	private final TargetMode targetMode;
+    /**
+     * Targeting mode [Internal|External]
+     */
+    private final TargetMode targetMode;
 
-	/**
-	 * Target URI
-	 */
-	private final URI targetUri;
+    /**
+     * Target URI
+     */
+    private final URI targetUri;
 
-	/**
-	 * Constructor.
-	 */
-	public PackageRelationship(OPCPackage pkg, PackagePart sourcePart,
-			URI targetUri, TargetMode targetMode, String relationshipType,
-			String id) {
-		if (pkg == null)
-			throw new IllegalArgumentException("pkg");
-		if (targetUri == null)
-			throw new IllegalArgumentException("targetUri");
-		if (relationshipType == null)
-			throw new IllegalArgumentException("relationshipType");
-		if (id == null)
-			throw new IllegalArgumentException("id");
+    /**
+     * Constructor.
+     */
+    public PackageRelationship(OPCPackage pkg, PackagePart sourcePart,
+            URI targetUri, TargetMode targetMode, String relationshipType,
+            String id) {
+        if (pkg == null)
+            throw new IllegalArgumentException("pkg");
+        if (targetUri == null)
+            throw new IllegalArgumentException("targetUri");
+        if (relationshipType == null)
+            throw new IllegalArgumentException("relationshipType");
+        if (id == null)
+            throw new IllegalArgumentException("id");
 
-		this.container = pkg;
-		this.source = sourcePart;
-		this.targetUri = targetUri;
-		this.targetMode = targetMode;
-		this.relationshipType = relationshipType;
-		this.id = id;
-	}
+        this.container = pkg;
+        this.source = sourcePart;
+        this.targetUri = targetUri;
+        this.targetMode = targetMode;
+        this.relationshipType = relationshipType;
+        this.id = id;
+    }
 
-	@Override
-	public boolean equals(Object obj) {
-		if (!(obj instanceof PackageRelationship)) {
-			return false;
-		}
-		PackageRelationship rel = (PackageRelationship) obj;
-		return (this.id.equals(rel.id)
-				&& this.relationshipType.equals(rel.relationshipType)
-				&& (rel.source == null || rel.source.equals(this.source))
-				&& this.targetMode == rel.targetMode && this.targetUri
-				.equals(rel.targetUri));
-	}
+    @Override
+    public boolean equals(Object obj) {
+        if (!(obj instanceof PackageRelationship)) {
+            return false;
+        }
+        PackageRelationship rel = (PackageRelationship) obj;
+        return (this.id.equals(rel.id)
+                && this.relationshipType.equals(rel.relationshipType)
+                && (rel.source == null || rel.source.equals(this.source))
+                && this.targetMode == rel.targetMode && this.targetUri
+                .equals(rel.targetUri));
+    }
 
-	@Override
-	public int hashCode() {
-		return Objects.hash(id,relationshipType,source,targetMode,targetUri);
-	}
+    @Override
+    public int hashCode() {
+        return Objects.hash(id,relationshipType,source,targetMode,targetUri);
+    }
 
-	/* Getters */
+    /* Getters */
 
-	public static URI getContainerPartRelationship() {
-		return containerRelationshipPart;
-	}
+    public static URI getContainerPartRelationship() {
+        return containerRelationshipPart;
+    }
 
-	/**
-	 * @return the container
-	 */
-	public OPCPackage getPackage() {
-		return container;
-	}
+    /**
+     * @return the container
+     */
+    public OPCPackage getPackage() {
+        return container;
+    }
 
-	/**
-	 * @return the id
-	 */
-	public String getId() {
-		return id;
-	}
+    /**
+     * @return the id
+     */
+    public String getId() {
+        return id;
+    }
 
-	/**
-	 * @return the relationshipType
-	 */
-	public String getRelationshipType() {
-		return relationshipType;
-	}
+    /**
+     * @return the relationshipType
+     */
+    public String getRelationshipType() {
+        return relationshipType;
+    }
 
-	/**
-	 * @return the source
-	 */
-	public PackagePart getSource() {
-		return source;
-	}
+    /**
+     * @return the source
+     */
+    public PackagePart getSource() {
+        return source;
+    }
 
-	/**
-	 *
-	 * @return URL of the source part of this relationship
-	 */
-	public URI getSourceURI() {
-		if (source == null) {
-			return PackagingURIHelper.PACKAGE_ROOT_URI;
-		}
-		return source._partName.getURI();
-	}
+    /**
+     *
+     * @return URL of the source part of this relationship
+     */
+    public URI getSourceURI() {
+        if (source == null) {
+            return PackagingURIHelper.PACKAGE_ROOT_URI;
+        }
+        return source._partName.getURI();
+    }
 
-	/**
-	 * @return the targetMode
-	 */
-	public TargetMode getTargetMode() {
-		return targetMode;
-	}
+    /**
+     * @return the targetMode
+     */
+    public TargetMode getTargetMode() {
+        return targetMode;
+    }
 
-	/**
-	 * @return the targetUri
-	 */
-	public URI getTargetURI() {
-		// If it's an external target, we don't
-		//  need to apply our normal validation rules
-		if(targetMode == TargetMode.EXTERNAL) {
-			return targetUri;
-		}
+    /**
+     * @return the targetUri
+     */
+    public URI getTargetURI() {
+        // If it's an external target, we don't
+        //  need to apply our normal validation rules
+        if(targetMode == TargetMode.EXTERNAL) {
+            return targetUri;
+        }
 
-		// Internal target
-		// If it isn't absolute, resolve it relative
-		//  to ourselves
-		if (!targetUri.toASCIIString().startsWith("/")) {
-			// So it's a relative part name, try to resolve it
-			return PackagingURIHelper.resolvePartUri(getSourceURI(), targetUri);
-		}
-		return targetUri;
-	}
+        // Internal target
+        // If it isn't absolute, resolve it relative
+        //  to ourselves
+        if (!targetUri.toASCIIString().startsWith("/")) {
+            // So it's a relative part name, try to resolve it
+            return PackagingURIHelper.resolvePartUri(getSourceURI(), targetUri);
+        }
+        return targetUri;
+    }
 
-	@Override
-	public String toString() {
-		return "id=" + id +
-				" - container=" + container +
-				" - relationshipType=" + relationshipType +
-				(source == null ? " - source=null" : " - source=" + getSourceURI().toASCIIString()) +
-				" - target=" + getTargetURI().toASCIIString() +
-				(targetMode == null ? ",targetMode=null" : ",targetMode=" + targetMode);
-	}
+    @Override
+    public String toString() {
+        return "id=" + id +
+                " - container=" + container +
+                " - relationshipType=" + relationshipType +
+                (source == null ? " - source=null" : " - source=" + getSourceURI().toASCIIString()) +
+                " - target=" + getTargetURI().toASCIIString() +
+                (targetMode == null ? ",targetMode=null" : ",targetMode=" + targetMode);
+    }
 }
diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/RelationshipSource.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/RelationshipSource.java
index 951128700e..97abcd00fe 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/RelationshipSource.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/RelationshipSource.java
@@ -22,137 +22,137 @@ import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
 
 public interface RelationshipSource {
 
-	/**
-	 * Add a relationship to a part (except relationships part).
-	 *
-	 * @param targetPartName
-	 *            Name of the target part. This one must be relative to the
-	 *            source root directory of the part.
-	 * @param targetMode
-	 *            Mode [Internal|External].
-	 * @param relationshipType
-	 *            Type of relationship.
-	 * @return The newly created and added relationship
-	 */
-	PackageRelationship addRelationship(
-			PackagePartName targetPartName, TargetMode targetMode,
-			String relationshipType);
+    /**
+     * Add a relationship to a part (except relationships part).
+     *
+     * @param targetPartName
+     *            Name of the target part. This one must be relative to the
+     *            source root directory of the part.
+     * @param targetMode
+     *            Mode [Internal|External].
+     * @param relationshipType
+     *            Type of relationship.
+     * @return The newly created and added relationship
+     */
+    PackageRelationship addRelationship(
+            PackagePartName targetPartName, TargetMode targetMode,
+            String relationshipType);
 
-	/**
-	 * Add a relationship to a part (except relationships part).
-	 * 

- * Check rule M1.25: The Relationships part shall not have relationships to - * any other part. Package implementers shall enforce this requirement upon - * the attempt to create such a relationship and shall treat any such - * relationship as invalid. - *

- * @param targetPartName - * Name of the target part. This one must be relative to the - * source root directory of the part. - * @param targetMode - * Mode [Internal|External]. - * @param relationshipType - * Type of relationship. - * @param id - * Relationship unique id. - * @return The newly created and added relationship - */ - PackageRelationship addRelationship( - PackagePartName targetPartName, TargetMode targetMode, - String relationshipType, String id); + /** + * Add a relationship to a part (except relationships part). + *

+ * Check rule M1.25: The Relationships part shall not have relationships to + * any other part. Package implementers shall enforce this requirement upon + * the attempt to create such a relationship and shall treat any such + * relationship as invalid. + *

+ * @param targetPartName + * Name of the target part. This one must be relative to the + * source root directory of the part. + * @param targetMode + * Mode [Internal|External]. + * @param relationshipType + * Type of relationship. + * @param id + * Relationship unique id. + * @return The newly created and added relationship + */ + PackageRelationship addRelationship( + PackagePartName targetPartName, TargetMode targetMode, + String relationshipType, String id); - /** - * Adds an external relationship to a part - * (except relationships part). - * - * The targets of external relationships are not - * subject to the same validity checks that internal - * ones are, as the contents is potentially - * any file, URL or similar. - * - * @param target External target of the relationship - * @param relationshipType Type of relationship. - * @return The newly created and added relationship - */ - PackageRelationship addExternalRelationship(String target, String relationshipType); + /** + * Adds an external relationship to a part + * (except relationships part). + * + * The targets of external relationships are not + * subject to the same validity checks that internal + * ones are, as the contents is potentially + * any file, URL or similar. + * + * @param target External target of the relationship + * @param relationshipType Type of relationship. + * @return The newly created and added relationship + */ + PackageRelationship addExternalRelationship(String target, String relationshipType); - /** - * Adds an external relationship to a part - * (except relationships part). - * - * The targets of external relationships are not - * subject to the same validity checks that internal - * ones are, as the contents is potentially - * any file, URL or similar. - * - * @param target External target of the relationship - * @param relationshipType Type of relationship. - * @param id Relationship unique id. - * @return The newly created and added relationship - * @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String, java.lang.String) - */ - PackageRelationship addExternalRelationship(String target, String relationshipType, String id); + /** + * Adds an external relationship to a part + * (except relationships part). + * + * The targets of external relationships are not + * subject to the same validity checks that internal + * ones are, as the contents is potentially + * any file, URL or similar. + * + * @param target External target of the relationship + * @param relationshipType Type of relationship. + * @param id Relationship unique id. + * @return The newly created and added relationship + * @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String, java.lang.String) + */ + PackageRelationship addExternalRelationship(String target, String relationshipType, String id); - /** - * Delete all the relationships attached to this. - */ - void clearRelationships(); + /** + * Delete all the relationships attached to this. + */ + void clearRelationships(); - /** - * Delete the relationship specified by its id. - * - * @param id - * The ID identified the part to delete. - */ - void removeRelationship(String id); + /** + * Delete the relationship specified by its id. + * + * @param id + * The ID identified the part to delete. + */ + void removeRelationship(String id); - /** - * Retrieve all the relationships attached to this. - * - * @return This part's relationships. - */ - PackageRelationshipCollection getRelationships() throws OpenXML4JException; + /** + * Retrieve all the relationships attached to this. + * + * @return This part's relationships. + */ + PackageRelationshipCollection getRelationships() throws OpenXML4JException; - /** - * Retrieves a package relationship from its id. - * - * @param id - * ID of the package relationship to retrieve. - * @return The package relationship - */ - PackageRelationship getRelationship(String id); + /** + * Retrieves a package relationship from its id. + * + * @param id + * ID of the package relationship to retrieve. + * @return The package relationship + */ + PackageRelationship getRelationship(String id); - /** - * Retrieve all relationships attached to this part which have the specified - * type. - * - * @param relationshipType - * Relationship type filter. - * @return All relationships from this part that have the specified type. - * @throws InvalidFormatException - * If an error occurs while parsing the part. - * @throws InvalidOperationException - * If the package is open in write only mode. - */ - PackageRelationshipCollection getRelationshipsByType(String relationshipType) - throws IllegalArgumentException, OpenXML4JException; + /** + * Retrieve all relationships attached to this part which have the specified + * type. + * + * @param relationshipType + * Relationship type filter. + * @return All relationships from this part that have the specified type. + * @throws InvalidFormatException + * If an error occurs while parsing the part. + * @throws InvalidOperationException + * If the package is open in write only mode. + */ + PackageRelationshipCollection getRelationshipsByType(String relationshipType) + throws IllegalArgumentException, OpenXML4JException; - /** - * Knows if the part have any relationships. - * - * @return true if the part have at least one relationship else - * false. - */ - boolean hasRelationships(); + /** + * Knows if the part have any relationships. + * + * @return true if the part have at least one relationship else + * false. + */ + boolean hasRelationships(); - /** - * Checks if the specified relationship is part of this package part. - * - * @param rel - * The relationship to check. - * @return true if the specified relationship exists in this part, - * else returns false - */ - boolean isRelationshipExists(PackageRelationship rel); + /** + * Checks if the specified relationship is part of this package part. + * + * @param rel + * The relationship to check. + * @return true if the specified relationship exists in this part, + * else returns false + */ + boolean isRelationshipExists(PackageRelationship rel); } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/StreamHelper.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/StreamHelper.java index af31eb3ab3..c40cef3b2f 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/StreamHelper.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/StreamHelper.java @@ -36,68 +36,68 @@ import org.w3c.dom.Document; public final class StreamHelper { - private StreamHelper() { - // Do nothing - } + private StreamHelper() { + // Do nothing + } - /** - * Save the document object in the specified output stream. - * - * @param xmlContent - * The XML document. - * @param outStream - * The OutputStream in which the XML document will be written. - * @return true if the xml is successfully written in the stream, - * else false. - */ - public static boolean saveXmlInStream(Document xmlContent, - OutputStream outStream) { - try { - Transformer trans = XMLHelper.newTransformer(); - Source xmlSource = new DOMSource(xmlContent); - // prevent close of stream by transformer: - Result outputTarget = new StreamResult(new FilterOutputStream( - outStream) { - @Override - public void write(byte[] b, int off, int len) - throws IOException { - out.write(b, off, len); - } + /** + * Save the document object in the specified output stream. + * + * @param xmlContent + * The XML document. + * @param outStream + * The OutputStream in which the XML document will be written. + * @return true if the xml is successfully written in the stream, + * else false. + */ + public static boolean saveXmlInStream(Document xmlContent, + OutputStream outStream) { + try { + Transformer trans = XMLHelper.newTransformer(); + Source xmlSource = new DOMSource(xmlContent); + // prevent close of stream by transformer: + Result outputTarget = new StreamResult(new FilterOutputStream( + outStream) { + @Override + public void write(byte[] b, int off, int len) + throws IOException { + out.write(b, off, len); + } - @Override - public void close() throws IOException { - out.flush(); // only flush, don't close! - } - }); - // xmlContent.setXmlStandalone(true); - trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - // don't indent xml documents, the indent will cause errors in calculating the xml signature - // because of different handling of linebreaks in Windows/Unix - // see https://stackoverflow.com/questions/36063375 - trans.setOutputProperty(OutputKeys.INDENT, "no"); - trans.setOutputProperty(OutputKeys.STANDALONE, "yes"); - trans.transform(xmlSource, outputTarget); - } catch (TransformerException e) { - return false; - } - return true; - } + @Override + public void close() throws IOException { + out.flush(); // only flush, don't close! + } + }); + // xmlContent.setXmlStandalone(true); + trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + // don't indent xml documents, the indent will cause errors in calculating the xml signature + // because of different handling of linebreaks in Windows/Unix + // see https://stackoverflow.com/questions/36063375 + trans.setOutputProperty(OutputKeys.INDENT, "no"); + trans.setOutputProperty(OutputKeys.STANDALONE, "yes"); + trans.transform(xmlSource, outputTarget); + } catch (TransformerException e) { + return false; + } + return true; + } - /** - * Copy the input stream into the output stream. - * - * @param inStream - * The source stream. - * @param outStream - * The destination stream. - * @return true if the operation succeed, else return false. - */ - public static boolean copyStream(InputStream inStream, OutputStream outStream) { - try { - IOUtils.copy(inStream, outStream); - return true; - } catch (Exception e) { - return false; - } - } + /** + * Copy the input stream into the output stream. + * + * @param inStream + * The source stream. + * @param outStream + * The destination stream. + * @return true if the operation succeed, else return false. + */ + public static boolean copyStream(InputStream inStream, OutputStream outStream) { + try { + IOUtils.copy(inStream, outStream); + return true; + } catch (Exception e) { + return false; + } + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/TargetMode.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/TargetMode.java index 99adb023b3..473d8cdd58 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/TargetMode.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/TargetMode.java @@ -24,7 +24,7 @@ package org.apache.poi.openxml4j.opc; */ public enum TargetMode { /** The relationship references a part that is inside the package. */ - INTERNAL, + INTERNAL, /** The relationship references a resource that is external to the package. */ - EXTERNAL + EXTERNAL } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ZipPackage.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ZipPackage.java index 67e7c44567..9c030584b9 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ZipPackage.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ZipPackage.java @@ -407,151 +407,151 @@ public final class ZipPackage extends OPCPackage { // Flush the package flush(); - if (this.originalPackagePath == null || this.originalPackagePath.isEmpty()) { - return; - } + if (this.originalPackagePath == null || this.originalPackagePath.isEmpty()) { + return; + } - // Save the content - File targetFile = new File(this.originalPackagePath); - if (!targetFile.exists()) { + // Save the content + File targetFile = new File(this.originalPackagePath); + if (!targetFile.exists()) { throw new InvalidOperationException( "Can't close a package not previously open with the open() method !"); } - // Case of a package previously open - String tempFileName = generateTempFileName(FileHelper.getDirectory(targetFile)); - File tempFile = TempFile.createTempFile(tempFileName, ".tmp"); + // Case of a package previously open + String tempFileName = generateTempFileName(FileHelper.getDirectory(targetFile)); + File tempFile = TempFile.createTempFile(tempFileName, ".tmp"); - // Save the final package to a temporary file + // Save the final package to a temporary file boolean success = false; - try { - save(tempFile); + try { + save(tempFile); success = true; - } finally { + } finally { // Close the current zip file, so we can overwrite it on all platforms IOUtils.closeQuietly(this.zipArchive); - try { - // Copy the new file over the old one if save() succeed + try { + // Copy the new file over the old one if save() succeed if(success) { - FileHelper.copyFile(tempFile, targetFile); + FileHelper.copyFile(tempFile, targetFile); } - } finally { - // Either the save operation succeed or not, we delete the temporary file - if (!tempFile.delete()) { + } finally { + // Either the save operation succeed or not, we delete the temporary file + if (!tempFile.delete()) { LOG.atWarn().log("The temporary file: '{}' cannot be deleted ! Make sure that no other application use it.", targetFile.getAbsolutePath()); - } - } - } - } + } + } + } + } - /** - * Create a unique identifier to be use as a temp file name. - * - * @return A unique identifier use to be use as a temp file name. - */ - private synchronized String generateTempFileName(File directory) { - File tmpFilename; - do { - tmpFilename = new File(directory.getAbsoluteFile() + File.separator - + "OpenXML4J" + System.nanoTime()); - } while (tmpFilename.exists()); - return FileHelper.getFilename(tmpFilename.getAbsoluteFile()); - } + /** + * Create a unique identifier to be use as a temp file name. + * + * @return A unique identifier use to be use as a temp file name. + */ + private synchronized String generateTempFileName(File directory) { + File tmpFilename; + do { + tmpFilename = new File(directory.getAbsoluteFile() + File.separator + + "OpenXML4J" + System.nanoTime()); + } while (tmpFilename.exists()); + return FileHelper.getFilename(tmpFilename.getAbsoluteFile()); + } - /** - * Close the package without saving the document. Discard all the changes - * made to this package. - */ - @Override - protected void revertImpl() { - try { - if (this.zipArchive != null) { + /** + * Close the package without saving the document. Discard all the changes + * made to this package. + */ + @Override + protected void revertImpl() { + try { + if (this.zipArchive != null) { this.zipArchive.close(); } - } catch (IOException e) { - // Do nothing, user dont have to know - } - } + } catch (IOException e) { + // Do nothing, user dont have to know + } + } - /** - * Save this package into the specified stream - * - * - * @param outputStream - * The stream use to save this package. - * - * @see #save(OutputStream) - */ - @Override - public void saveImpl(OutputStream outputStream) { - // Check that the document was open in write mode - throwExceptionIfReadOnly(); + /** + * Save this package into the specified stream + * + * + * @param outputStream + * The stream use to save this package. + * + * @see #save(OutputStream) + */ + @Override + public void saveImpl(OutputStream outputStream) { + // Check that the document was open in write mode + throwExceptionIfReadOnly(); - final ZipArchiveOutputStream zos = (outputStream instanceof ZipArchiveOutputStream) + final ZipArchiveOutputStream zos = (outputStream instanceof ZipArchiveOutputStream) ? (ZipArchiveOutputStream) outputStream : new ZipArchiveOutputStream(outputStream); - try { - // If the core properties part does not exist in the part list, - // we save it as well - if (this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size() == 0 && + try { + // If the core properties part does not exist in the part list, + // we save it as well + if (this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size() == 0 && this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES_ECMA376).size() == 0 ) { - LOG.atDebug().log("Save core properties part"); + LOG.atDebug().log("Save core properties part"); - // Ensure that core properties are added if missing - getPackageProperties(); - // Add core properties to part list ... - addPackagePart(this.packageProperties); - // ... and to add its relationship ... - this.relationships.addRelationship(this.packageProperties - .getPartName().getURI(), TargetMode.INTERNAL, - PackageRelationshipTypes.CORE_PROPERTIES, null); - // ... and the content if it has not been added yet. - if (!this.contentTypeManager - .isContentTypeRegister(ContentTypes.CORE_PROPERTIES_PART)) { - this.contentTypeManager.addContentType( - this.packageProperties.getPartName(), - ContentTypes.CORE_PROPERTIES_PART); - } - } + // Ensure that core properties are added if missing + getPackageProperties(); + // Add core properties to part list ... + addPackagePart(this.packageProperties); + // ... and to add its relationship ... + this.relationships.addRelationship(this.packageProperties + .getPartName().getURI(), TargetMode.INTERNAL, + PackageRelationshipTypes.CORE_PROPERTIES, null); + // ... and the content if it has not been added yet. + if (!this.contentTypeManager + .isContentTypeRegister(ContentTypes.CORE_PROPERTIES_PART)) { + this.contentTypeManager.addContentType( + this.packageProperties.getPartName(), + ContentTypes.CORE_PROPERTIES_PART); + } + } // Save content type part. LOG.atDebug().log("Save content types part"); this.contentTypeManager.save(zos); - // Save package relationships part. - LOG.atDebug().log("Save package relationships"); - ZipPartMarshaller.marshallRelationshipPart(this.getRelationships(), - PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME, - zos); + // Save package relationships part. + LOG.atDebug().log("Save package relationships"); + ZipPartMarshaller.marshallRelationshipPart(this.getRelationships(), + PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME, + zos); - // Save parts. - for (PackagePart part : getParts()) { - // If the part is a relationship part, we don't save it, it's - // the source part that will do the job. - if (part.isRelationshipPart()) { + // Save parts. + for (PackagePart part : getParts()) { + // If the part is a relationship part, we don't save it, it's + // the source part that will do the job. + if (part.isRelationshipPart()) { continue; } - final PackagePartName ppn = part.getPartName(); + final PackagePartName ppn = part.getPartName(); LOG.atDebug().log(() -> new SimpleMessage("Save part '" + ZipHelper.getZipItemNameFromOPCName(ppn.getName()) + "'")); - final PartMarshaller marshaller = partMarshallers.get(part._contentType); + final PartMarshaller marshaller = partMarshallers.get(part._contentType); - final PartMarshaller pm = (marshaller != null) ? marshaller : defaultPartMarshaller; + final PartMarshaller pm = (marshaller != null) ? marshaller : defaultPartMarshaller; if (!pm.marshall(part, zos)) { String errMsg = "The part " + ppn.getURI() + " failed to be saved in the stream with marshaller " + pm + ". Enable logging via Log4j 2 for more details."; throw new OpenXML4JException(errMsg); } - } + } zos.finish(); - } catch (OpenXML4JRuntimeException e) { - // no need to wrap this type of Exception - throw e; - } catch (Exception e) { + } catch (OpenXML4JRuntimeException e) { + // no need to wrap this type of Exception + throw e; + } catch (Exception e) { throw new OpenXML4JRuntimeException( "Fail to save: an error occurs while saving the package : " - + e.getMessage(), e); + + e.getMessage(), e); } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ZipPackagePart.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ZipPackagePart.java index 354e212aad..fd862a0d7f 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ZipPackagePart.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/ZipPackagePart.java @@ -37,111 +37,111 @@ import org.apache.poi.util.NotImplemented; */ public class ZipPackagePart extends PackagePart { - /** - * The zip entry corresponding to this part. - */ - private ZipArchiveEntry zipEntry; + /** + * The zip entry corresponding to this part. + */ + private ZipArchiveEntry zipEntry; - /** - * Constructor. - * - * @param container - * The container package. - * @param zipEntry - * The zip entry corresponding to this part. - * @param partName - * The part name. - * @param contentType - * Content type. - * @throws InvalidFormatException - * Throws if the content of this part is invalid. - */ - public ZipPackagePart(OPCPackage container, ZipArchiveEntry zipEntry, - PackagePartName partName, String contentType) - throws InvalidFormatException { - this(container, zipEntry, partName, contentType, true); - } + /** + * Constructor. + * + * @param container + * The container package. + * @param zipEntry + * The zip entry corresponding to this part. + * @param partName + * The part name. + * @param contentType + * Content type. + * @throws InvalidFormatException + * Throws if the content of this part is invalid. + */ + public ZipPackagePart(OPCPackage container, ZipArchiveEntry zipEntry, + PackagePartName partName, String contentType) + throws InvalidFormatException { + this(container, zipEntry, partName, contentType, true); + } - /** - * Constructor. - * - * @param container - * The container package. - * @param zipEntry - * The zip entry corresponding to this part. - * @param partName - * The part name. - * @param contentType - * Content type. - * @throws InvalidFormatException - * Throws if the content of this part is invalid. - */ - /* package */ ZipPackagePart(OPCPackage container, ZipArchiveEntry zipEntry, - PackagePartName partName, String contentType, boolean loadRelationships) - throws InvalidFormatException { - super(container, partName, new ContentType(contentType), loadRelationships); - this.zipEntry = zipEntry; - } + /** + * Constructor. + * + * @param container + * The container package. + * @param zipEntry + * The zip entry corresponding to this part. + * @param partName + * The part name. + * @param contentType + * Content type. + * @throws InvalidFormatException + * Throws if the content of this part is invalid. + */ + /* package */ ZipPackagePart(OPCPackage container, ZipArchiveEntry zipEntry, + PackagePartName partName, String contentType, boolean loadRelationships) + throws InvalidFormatException { + super(container, partName, new ContentType(contentType), loadRelationships); + this.zipEntry = zipEntry; + } - /** - * Get the zip entry of this part. - * - * @return The zip entry in the zip structure coresponding to this part. - */ - public ZipArchiveEntry getZipArchive() { - return zipEntry; - } + /** + * Get the zip entry of this part. + * + * @return The zip entry in the zip structure coresponding to this part. + */ + public ZipArchiveEntry getZipArchive() { + return zipEntry; + } - /** - * Implementation of the getInputStream() which return the inputStream of - * this part zip entry. - * - * @return Input stream of this part zip entry. - */ - @Override - protected InputStream getInputStreamImpl() throws IOException { - // We use the getInputStream() method from java.util.zip.ZipFile - // class which return an InputStream to this part zip entry. - return ((ZipPackage) _container).getZipArchive() - .getInputStream(zipEntry); - } + /** + * Implementation of the getInputStream() which return the inputStream of + * this part zip entry. + * + * @return Input stream of this part zip entry. + */ + @Override + protected InputStream getInputStreamImpl() throws IOException { + // We use the getInputStream() method from java.util.zip.ZipFile + // class which return an InputStream to this part zip entry. + return ((ZipPackage) _container).getZipArchive() + .getInputStream(zipEntry); + } - /** - * Implementation of the getOutputStream(). Return null. Normally - * will never be called since the MemoryPackage is use instead. - * - * @return null - */ - @Override - protected OutputStream getOutputStreamImpl() { - return null; - } + /** + * Implementation of the getOutputStream(). Return null. Normally + * will never be called since the MemoryPackage is use instead. + * + * @return null + */ + @Override + protected OutputStream getOutputStreamImpl() { + return null; + } - @Override - public long getSize() { - return zipEntry.getSize(); - } + @Override + public long getSize() { + return zipEntry.getSize(); + } - @Override - public boolean save(OutputStream os) throws OpenXML4JException { - return new ZipPartMarshaller().marshall(this, os); - } + @Override + public boolean save(OutputStream os) throws OpenXML4JException { + return new ZipPartMarshaller().marshall(this, os); + } - @Override - @NotImplemented - public boolean load(InputStream ios) { - throw new InvalidOperationException("Method not implemented !"); - } + @Override + @NotImplemented + public boolean load(InputStream ios) { + throw new InvalidOperationException("Method not implemented !"); + } - @Override - @NotImplemented - public void close() { - throw new InvalidOperationException("Method not implemented !"); - } + @Override + @NotImplemented + public void close() { + throw new InvalidOperationException("Method not implemented !"); + } - @Override - @NotImplemented - public void flush() { - throw new InvalidOperationException("Method not implemented !"); - } + @Override + @NotImplemented + public void flush() { + throw new InvalidOperationException("Method not implemented !"); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/ContentType.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/ContentType.java index 9d2515061f..d418a2dc61 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/ContentType.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/ContentType.java @@ -51,25 +51,25 @@ import org.apache.poi.openxml4j.exceptions.InvalidFormatException; */ public final class ContentType { - /** - * Type in Type/Subtype. - */ - private final String type; + /** + * Type in Type/Subtype. + */ + private final String type; - /** - * Subtype - */ - private final String subType; + /** + * Subtype + */ + private final String subType; - /** - * Parameters - */ - private final Map parameters; + /** + * Parameters + */ + private final Map parameters; - /** - * Media type compiled pattern, without parameters - */ - private static final Pattern patternTypeSubType; + /** + * Media type compiled pattern, without parameters + */ + private static final Pattern patternTypeSubType; /** * Media type compiled pattern, with parameters. */ @@ -80,184 +80,184 @@ public final class ContentType { */ private static final Pattern patternParams; - static { - /* - * token = 1* - * - * separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | - * <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT - * - * CTL = - * - * CHAR = - */ - String token = "[\\x21-\\x7E&&[^()<>@,;:\\\\/\"\\[\\]?={}\\x20\\x09]]"; + static { + /* + * token = 1* + * + * separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | + * <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT + * + * CTL = + * + * CHAR = + */ + String token = "[\\x21-\\x7E&&[^()<>@,;:\\\\/\"\\[\\]?={}\\x20\\x09]]"; - /* - * parameter = attribute "=" value - * - * attribute = token - * - * value = token | quoted-string - */ - String parameter = "(" + token + "+)=(\"?" + token + "+\"?)"; - /* - * Pattern for media type. - * - * Don't allow comment, rule M1.15: The package implementer shall - * require a content type that does not include comments and the format - * designer shall specify such a content type. - * - * comment = "(" *( ctext | quoted-pair | comment ) ")" - * - * ctext = - * - * TEXT = - * - * LWS = [CRLF] 1*( SP | HT ) - * - * CR = - * - * LF = - * - * SP = - * - * HT = - * - * quoted-pair = "\" CHAR - */ + /* + * parameter = attribute "=" value + * + * attribute = token + * + * value = token | quoted-string + */ + String parameter = "(" + token + "+)=(\"?" + token + "+\"?)"; + /* + * Pattern for media type. + * + * Don't allow comment, rule M1.15: The package implementer shall + * require a content type that does not include comments and the format + * designer shall specify such a content type. + * + * comment = "(" *( ctext | quoted-pair | comment ) ")" + * + * ctext = + * + * TEXT = + * + * LWS = [CRLF] 1*( SP | HT ) + * + * CR = + * + * LF = + * + * SP = + * + * HT = + * + * quoted-pair = "\" CHAR + */ - patternTypeSubType = Pattern.compile("^(" + token + "+)/(" + - token + "+)$"); - patternTypeSubTypeParams = Pattern.compile("^(" + token + "+)/(" + - token + "+)(;" + parameter + ")*$"); - patternParams = Pattern.compile(";" + parameter); - } + patternTypeSubType = Pattern.compile("^(" + token + "+)/(" + + token + "+)$"); + patternTypeSubTypeParams = Pattern.compile("^(" + token + "+)/(" + + token + "+)(;" + parameter + ")*$"); + patternParams = Pattern.compile(";" + parameter); + } - /** - * Constructor. Check the input with the RFC 2616 grammar. - * - * @param contentType - * The content type to store. - * @throws InvalidFormatException - * If the specified content type is not valid with RFC 2616. - */ - public ContentType(String contentType) throws InvalidFormatException { - Matcher mMediaType = patternTypeSubType.matcher(contentType); - if (!mMediaType.matches()) { - // How about with parameters? - mMediaType = patternTypeSubTypeParams.matcher(contentType); - } - if (!mMediaType.matches()) { - throw new InvalidFormatException( - "The specified content type '" - + contentType - + "' is not compliant with RFC 2616: malformed content type."); - } + /** + * Constructor. Check the input with the RFC 2616 grammar. + * + * @param contentType + * The content type to store. + * @throws InvalidFormatException + * If the specified content type is not valid with RFC 2616. + */ + public ContentType(String contentType) throws InvalidFormatException { + Matcher mMediaType = patternTypeSubType.matcher(contentType); + if (!mMediaType.matches()) { + // How about with parameters? + mMediaType = patternTypeSubTypeParams.matcher(contentType); + } + if (!mMediaType.matches()) { + throw new InvalidFormatException( + "The specified content type '" + + contentType + + "' is not compliant with RFC 2616: malformed content type."); + } - // Type/subtype - if (mMediaType.groupCount() >= 2) { - this.type = mMediaType.group(1); - this.subType = mMediaType.group(2); + // Type/subtype + if (mMediaType.groupCount() >= 2) { + this.type = mMediaType.group(1); + this.subType = mMediaType.group(2); - // Parameters - this.parameters = new HashMap<>(); - // Java RegExps are unhelpful, and won't do multiple group captures - // See http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#cg - if (mMediaType.groupCount() >= 5) { - Matcher mParams = patternParams.matcher(contentType.substring(mMediaType.end(2))); - while (mParams.find()) { - this.parameters.put(mParams.group(1), mParams.group(2)); - } - } - } else { - // missing media type and subtype - this.type = ""; - this.subType = ""; - this.parameters = Collections.emptyMap(); - } - } + // Parameters + this.parameters = new HashMap<>(); + // Java RegExps are unhelpful, and won't do multiple group captures + // See http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#cg + if (mMediaType.groupCount() >= 5) { + Matcher mParams = patternParams.matcher(contentType.substring(mMediaType.end(2))); + while (mParams.find()) { + this.parameters.put(mParams.group(1), mParams.group(2)); + } + } + } else { + // missing media type and subtype + this.type = ""; + this.subType = ""; + this.parameters = Collections.emptyMap(); + } + } /** * Returns the content type as a string, including parameters */ - @Override - public final String toString() { - return toString(true); - } + @Override + public final String toString() { + return toString(true); + } - public final String toString(boolean withParameters) { - StringBuilder retVal = new StringBuilder(64); - retVal.append(this.getType()); - retVal.append('/'); - retVal.append(this.getSubType()); + public final String toString(boolean withParameters) { + StringBuilder retVal = new StringBuilder(64); + retVal.append(this.getType()); + retVal.append('/'); + retVal.append(this.getSubType()); - if (withParameters) { - for (Entry me : parameters.entrySet()) { - retVal.append(';'); - retVal.append(me.getKey()); - retVal.append('='); - retVal.append(me.getValue()); - } - } - return retVal.toString(); - } + if (withParameters) { + for (Entry me : parameters.entrySet()) { + retVal.append(';'); + retVal.append(me.getKey()); + retVal.append('='); + retVal.append(me.getValue()); + } + } + return retVal.toString(); + } - @Override - public boolean equals(Object obj) { - return (!(obj instanceof ContentType)) - || (this.toString().equalsIgnoreCase(obj.toString())); - } + @Override + public boolean equals(Object obj) { + return (!(obj instanceof ContentType)) + || (this.toString().equalsIgnoreCase(obj.toString())); + } - @Override - public int hashCode() { - return Objects.hash(type,subType,parameters); - } + @Override + public int hashCode() { + return Objects.hash(type,subType,parameters); + } - /* Getters */ + /* Getters */ - /** - * Get the subtype. - * - * @return The subtype of this content type. - */ - public String getSubType() { - return this.subType; - } + /** + * Get the subtype. + * + * @return The subtype of this content type. + */ + public String getSubType() { + return this.subType; + } - /** - * Get the type. - * - * @return The type of this content type. - */ - public String getType() { - return this.type; - } + /** + * Get the type. + * + * @return The type of this content type. + */ + public String getType() { + return this.type; + } - /** - * Does this content type have any parameters associated with it? - */ - public boolean hasParameters() { - return (parameters != null) && !parameters.isEmpty(); - } + /** + * Does this content type have any parameters associated with it? + */ + public boolean hasParameters() { + return (parameters != null) && !parameters.isEmpty(); + } - /** - * Return the parameter keys - */ - public String[] getParameterKeys() { - if (parameters == null) - return new String[0]; - return parameters.keySet().toArray(new String[0]); - } + /** + * Return the parameter keys + */ + public String[] getParameterKeys() { + if (parameters == null) + return new String[0]; + return parameters.keySet().toArray(new String[0]); + } - /** - * Gets the value associated to the specified key. - * - * @param key - * The key of the key/value pair. - * @return The value associated to the specified key. - */ - public String getParameter(String key) { - return parameters.get(key); - } + /** + * Gets the value associated to the specified key. + * + * @param key + * The key of the key/value pair. + * @return The value associated to the specified key. + */ + public String getParameter(String key) { + return parameters.get(key); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java index c4ab456fd8..f614b81212 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java @@ -38,101 +38,101 @@ import org.apache.poi.util.IOUtils; */ public final class MemoryPackagePart extends PackagePart { - /** - * Storage for the part data. - */ - protected byte[] data; + /** + * Storage for the part data. + */ + protected byte[] data; - /** - * Constructor. - * - * @param pack - * The owner package. - * @param partName - * The part name. - * @param contentType - * The content type. - * @throws InvalidFormatException - * If the specified URI is not OPC compliant. - */ - public MemoryPackagePart(OPCPackage pack, PackagePartName partName, - String contentType) throws InvalidFormatException { - super(pack, partName, contentType); - } + /** + * Constructor. + * + * @param pack + * The owner package. + * @param partName + * The part name. + * @param contentType + * The content type. + * @throws InvalidFormatException + * If the specified URI is not OPC compliant. + */ + public MemoryPackagePart(OPCPackage pack, PackagePartName partName, + String contentType) throws InvalidFormatException { + super(pack, partName, contentType); + } - /** - * Constructor. - * - * @param pack - * The owner package. - * @param partName - * The part name. - * @param contentType - * The content type. - * @param loadRelationships - * Specify if the relationships will be loaded. - * @throws InvalidFormatException - * If the specified URI is not OPC compliant. - */ - public MemoryPackagePart(OPCPackage pack, PackagePartName partName, - String contentType, boolean loadRelationships) - throws InvalidFormatException { - super(pack, partName, new ContentType(contentType), loadRelationships); - } + /** + * Constructor. + * + * @param pack + * The owner package. + * @param partName + * The part name. + * @param contentType + * The content type. + * @param loadRelationships + * Specify if the relationships will be loaded. + * @throws InvalidFormatException + * If the specified URI is not OPC compliant. + */ + public MemoryPackagePart(OPCPackage pack, PackagePartName partName, + String contentType, boolean loadRelationships) + throws InvalidFormatException { + super(pack, partName, new ContentType(contentType), loadRelationships); + } - @Override - protected InputStream getInputStreamImpl() { - // If this part has been created from scratch and/or the data buffer is - // not - // initialize, so we do it now. - if (data == null) { - data = new byte[0]; - } - return new ByteArrayInputStream(data); - } + @Override + protected InputStream getInputStreamImpl() { + // If this part has been created from scratch and/or the data buffer is + // not + // initialize, so we do it now. + if (data == null) { + data = new byte[0]; + } + return new ByteArrayInputStream(data); + } - @Override - protected OutputStream getOutputStreamImpl() { - return new MemoryPackagePartOutputStream(this); - } + @Override + protected OutputStream getOutputStreamImpl() { + return new MemoryPackagePartOutputStream(this); + } - @Override - public long getSize() { - return data == null ? 0 : data.length; - } + @Override + public long getSize() { + return data == null ? 0 : data.length; + } @Override public void clear() { - data = null; - } + data = null; + } - @Override - public boolean save(OutputStream os) throws OpenXML4JException { - return new ZipPartMarshaller().marshall(this, os); - } + @Override + public boolean save(OutputStream os) throws OpenXML4JException { + return new ZipPartMarshaller().marshall(this, os); + } - @Override - public boolean load(InputStream ios) throws InvalidFormatException { - try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { - // Grab the data - IOUtils.copy(ios, baos); - // Save it - data = baos.toByteArray(); - } catch(IOException e) { - throw new InvalidFormatException(e.getMessage()); - } + @Override + public boolean load(InputStream ios) throws InvalidFormatException { + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { + // Grab the data + IOUtils.copy(ios, baos); + // Save it + data = baos.toByteArray(); + } catch(IOException e) { + throw new InvalidFormatException(e.getMessage()); + } - // All done - return true; - } + // All done + return true; + } - @Override - public void close() { - // Do nothing - } + @Override + public void close() { + // Do nothing + } - @Override - public void flush() { - // Do nothing - } + @Override + public void flush() { + // Do nothing + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java index 7fce830721..071718021b 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java @@ -27,68 +27,68 @@ import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; */ public final class MemoryPackagePartOutputStream extends OutputStream { - private final MemoryPackagePart _part; + private final MemoryPackagePart _part; - private final UnsynchronizedByteArrayOutputStream _buff; + private final UnsynchronizedByteArrayOutputStream _buff; - public MemoryPackagePartOutputStream(MemoryPackagePart part) { - this._part = part; - _buff = new UnsynchronizedByteArrayOutputStream(); - } + public MemoryPackagePartOutputStream(MemoryPackagePart part) { + this._part = part; + _buff = new UnsynchronizedByteArrayOutputStream(); + } - @Override - public void write(int b) { - _buff.write(b); - } + @Override + public void write(int b) { + _buff.write(b); + } - /** - * Close this stream and flush the content. - * @see #flush() - */ - @Override - public void close() throws IOException { - this.flush(); - } + /** + * Close this stream and flush the content. + * @see #flush() + */ + @Override + public void close() throws IOException { + this.flush(); + } - /** - * Flush this output stream. This method is called by the close() method. - * Warning : don't call this method for output consistency. - * @see #close() - */ - @Override - public void flush() throws IOException { - _buff.flush(); - if (_part.data != null) { - byte[] newArray = new byte[_part.data.length + _buff.size()]; - // copy the previous contents of part.data in newArray - System.arraycopy(_part.data, 0, newArray, 0, _part.data.length); + /** + * Flush this output stream. This method is called by the close() method. + * Warning : don't call this method for output consistency. + * @see #close() + */ + @Override + public void flush() throws IOException { + _buff.flush(); + if (_part.data != null) { + byte[] newArray = new byte[_part.data.length + _buff.size()]; + // copy the previous contents of part.data in newArray + System.arraycopy(_part.data, 0, newArray, 0, _part.data.length); - // append the newly added data - byte[] buffArr = _buff.toByteArray(); - System.arraycopy(buffArr, 0, newArray, _part.data.length, - buffArr.length); + // append the newly added data + byte[] buffArr = _buff.toByteArray(); + System.arraycopy(buffArr, 0, newArray, _part.data.length, + buffArr.length); - // save the result as new data - _part.data = newArray; - } else { - // was empty, just fill it - _part.data = _buff.toByteArray(); - } + // save the result as new data + _part.data = newArray; + } else { + // was empty, just fill it + _part.data = _buff.toByteArray(); + } - /* - * Clear this streams buffer, in case flush() is called a second time - * Fix bug 1921637 - provided by Rainer Schwarze - */ - _buff.reset(); - } + /* + * Clear this streams buffer, in case flush() is called a second time + * Fix bug 1921637 - provided by Rainer Schwarze + */ + _buff.reset(); + } - @Override - public void write(byte[] b, int off, int len) { - _buff.write(b, off, len); - } + @Override + public void write(byte[] b, int off, int len) { + _buff.write(b, off, len); + } - @Override - public void write(byte[] b) throws IOException { - _buff.write(b); - } + @Override + public void write(byte[] b) throws IOException { + _buff.write(b); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PartMarshaller.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PartMarshaller.java index cb2fb8e464..f093b3b0f1 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PartMarshaller.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PartMarshaller.java @@ -31,18 +31,18 @@ import org.apache.poi.openxml4j.opc.PackagePart; */ public interface PartMarshaller { - /** - * Save the content of the package in the stream - * - * @param part - * Part to marshall. - * @param out - * The output stream into which the part will be marshall. - * @return false if any marshall error occurs, else true - * @throws OpenXML4JException - * Throws only if any other exceptions are thrown by inner - * methods. - */ - public boolean marshall(PackagePart part, OutputStream out) - throws OpenXML4JException; + /** + * Save the content of the package in the stream + * + * @param part + * Part to marshall. + * @param out + * The output stream into which the part will be marshall. + * @return false if any marshall error occurs, else true + * @throws OpenXML4JException + * Throws only if any other exceptions are thrown by inner + * methods. + */ + public boolean marshall(PackagePart part, OutputStream out) + throws OpenXML4JException; } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PartUnmarshaller.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PartUnmarshaller.java index 2853172451..8d31319dc2 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PartUnmarshaller.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PartUnmarshaller.java @@ -32,14 +32,14 @@ import org.apache.poi.openxml4j.opc.internal.unmarshallers.UnmarshallContext; */ public interface PartUnmarshaller { - /** - * Save the content of the package in the stream - * - * @param in The input stream from which the part will be read. - * @return The part freshly read from the input stream. - * @throws InvalidFormatException If the data can not be interpreted correctly - * @throws IOException if reading from the stream fails - */ - public PackagePart unmarshall(UnmarshallContext context, InputStream in) - throws InvalidFormatException, IOException; + /** + * Save the content of the package in the stream + * + * @param in The input stream from which the part will be read. + * @return The part freshly read from the input stream. + * @throws InvalidFormatException If the data can not be interpreted correctly + * @throws IOException if reading from the stream fails + */ + public PackagePart unmarshall(UnmarshallContext context, InputStream in) + throws InvalidFormatException, IOException; } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/ZipContentTypeManager.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/ZipContentTypeManager.java index 40e3e256b6..cbdd46efdc 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/ZipContentTypeManager.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/ZipContentTypeManager.java @@ -39,39 +39,39 @@ import org.w3c.dom.Document; public class ZipContentTypeManager extends ContentTypeManager { private static final Logger LOG = LogManager.getLogger(ZipContentTypeManager.class); - /** - * Delegate constructor to the super constructor. - * - * @param in - * The input stream to parse to fill internal content type - * collections. - * @throws InvalidFormatException - * If the content types part content is not valid. - */ - public ZipContentTypeManager(InputStream in, OPCPackage pkg) - throws InvalidFormatException { - super(in, pkg); - } + /** + * Delegate constructor to the super constructor. + * + * @param in + * The input stream to parse to fill internal content type + * collections. + * @throws InvalidFormatException + * If the content types part content is not valid. + */ + public ZipContentTypeManager(InputStream in, OPCPackage pkg) + throws InvalidFormatException { + super(in, pkg); + } - @SuppressWarnings("resource") + @SuppressWarnings("resource") @Override - public boolean saveImpl(Document content, OutputStream out) { - final ZipArchiveOutputStream zos = (out instanceof ZipArchiveOutputStream) - ? (ZipArchiveOutputStream) out : new ZipArchiveOutputStream(out); + public boolean saveImpl(Document content, OutputStream out) { + final ZipArchiveOutputStream zos = (out instanceof ZipArchiveOutputStream) + ? (ZipArchiveOutputStream) out : new ZipArchiveOutputStream(out); - ZipArchiveEntry partEntry = new ZipArchiveEntry(CONTENT_TYPES_PART_NAME); - try { - // Referenced in ZIP - zos.putArchiveEntry(partEntry); - try { - // Saving data in the ZIP file - return StreamHelper.saveXmlInStream(content, zos); - } finally { - zos.closeArchiveEntry(); - } - } catch (IOException ioe) { - LOG.atError().withThrowable(ioe).log("Cannot write: " + CONTENT_TYPES_PART_NAME + " in Zip !"); - return false; - } - } + ZipArchiveEntry partEntry = new ZipArchiveEntry(CONTENT_TYPES_PART_NAME); + try { + // Referenced in ZIP + zos.putArchiveEntry(partEntry); + try { + // Saving data in the ZIP file + return StreamHelper.saveXmlInStream(content, zos); + } finally { + zos.closeArchiveEntry(); + } + } catch (IOException ioe) { + LOG.atError().withThrowable(ioe).log("Cannot write: " + CONTENT_TYPES_PART_NAME + " in Zip !"); + return false; + } + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/DefaultMarshaller.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/DefaultMarshaller.java index 83cf0c4863..f26e13ce75 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/DefaultMarshaller.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/DefaultMarshaller.java @@ -31,18 +31,18 @@ import org.apache.poi.openxml4j.opc.internal.PartMarshaller; */ public final class DefaultMarshaller implements PartMarshaller { - /** - * Save the given part in the output stream by using the save() method of the part. - * - * @param part The {@link PackagePart} to store. - * @param out Output stream to save this part. - * @return true if the content has been successfully stored, false otherwise. - * More information about errors may be logged via Log4j 2. - * @throws OpenXML4JException - * If any error occur. - */ - public boolean marshall(PackagePart part, OutputStream out) - throws OpenXML4JException { - return part.save(out); - } + /** + * Save the given part in the output stream by using the save() method of the part. + * + * @param part The {@link PackagePart} to store. + * @param out Output stream to save this part. + * @return true if the content has been successfully stored, false otherwise. + * More information about errors may be logged via Log4j 2. + * @throws OpenXML4JException + * If any error occur. + */ + public boolean marshall(PackagePart part, OutputStream out) + throws OpenXML4JException { + return part.save(out); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPackagePropertiesMarshaller.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPackagePropertiesMarshaller.java index 21522160f8..f3ad53cda7 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPackagePropertiesMarshaller.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPackagePropertiesMarshaller.java @@ -32,30 +32,30 @@ import org.apache.poi.openxml4j.opc.internal.ZipHelper; */ public final class ZipPackagePropertiesMarshaller extends PackagePropertiesMarshaller { - @Override - public boolean marshall(PackagePart part, OutputStream out) - throws OpenXML4JException { - if (!(out instanceof ZipArchiveOutputStream)) { - throw new IllegalArgumentException("ZipOutputStream expected!"); - } - ZipArchiveOutputStream zos = (ZipArchiveOutputStream) out; + @Override + public boolean marshall(PackagePart part, OutputStream out) + throws OpenXML4JException { + if (!(out instanceof ZipArchiveOutputStream)) { + throw new IllegalArgumentException("ZipOutputStream expected!"); + } + ZipArchiveOutputStream zos = (ZipArchiveOutputStream) out; - // Saving the part in the zip file - ZipArchiveEntry ctEntry = new ZipArchiveEntry(ZipHelper - .getZipItemNameFromOPCName(part.getPartName().getURI() - .toString())); - try { - // Save in ZIP - zos.putArchiveEntry(ctEntry); // Add entry in ZIP - try { - super.marshall(part, out); // Marshall the properties inside a XML - // Document - return StreamHelper.saveXmlInStream(xmlDoc, out); - } finally { - zos.closeArchiveEntry(); - } - } catch (IOException e) { - throw new OpenXML4JException(e.getLocalizedMessage(), e); - } - } + // Saving the part in the zip file + ZipArchiveEntry ctEntry = new ZipArchiveEntry(ZipHelper + .getZipItemNameFromOPCName(part.getPartName().getURI() + .toString())); + try { + // Save in ZIP + zos.putArchiveEntry(ctEntry); // Add entry in ZIP + try { + super.marshall(part, out); // Marshall the properties inside a XML + // Document + return StreamHelper.saveXmlInStream(xmlDoc, out); + } finally { + zos.closeArchiveEntry(); + } + } catch (IOException e) { + throw new OpenXML4JException(e.getLocalizedMessage(), e); + } + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.java index 384ad7687e..9519af2d35 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.java @@ -47,146 +47,146 @@ import org.w3c.dom.Element; * Zip part marshaller. This marshaller is use to save any part in a zip stream. */ public final class ZipPartMarshaller implements PartMarshaller { - private static final Logger LOG = LogManager.getLogger(ZipPartMarshaller.class); + private static final Logger LOG = LogManager.getLogger(ZipPartMarshaller.class); - /** - * Save the specified part to the given stream. - * - * @param part The {@link PackagePart} to save - * @param os The stream to write the data to - * @return true if saving was successful or there was nothing to save, - * false if an error occurred. - * In case of errors, logging via Log4j 2 is used to provide more information. - * @throws OpenXML4JException - * Throws if the stream cannot be written to or an internal exception is thrown. - */ - @Override - public boolean marshall(PackagePart part, OutputStream os) - throws OpenXML4JException { - if (!(os instanceof ZipArchiveOutputStream)) { - LOG.atError().log("Unexpected class {}", os.getClass().getName()); - throw new OpenXML4JException("ZipOutputStream expected !"); - // Normally should happen only in development phase, so just throw - // exception - } + /** + * Save the specified part to the given stream. + * + * @param part The {@link PackagePart} to save + * @param os The stream to write the data to + * @return true if saving was successful or there was nothing to save, + * false if an error occurred. + * In case of errors, logging via Log4j 2 is used to provide more information. + * @throws OpenXML4JException + * Throws if the stream cannot be written to or an internal exception is thrown. + */ + @Override + public boolean marshall(PackagePart part, OutputStream os) + throws OpenXML4JException { + if (!(os instanceof ZipArchiveOutputStream)) { + LOG.atError().log("Unexpected class {}", os.getClass().getName()); + throw new OpenXML4JException("ZipOutputStream expected !"); + // Normally should happen only in development phase, so just throw + // exception + } - // check if there is anything to save for some parts. We don't do this for all parts as some code - // might depend on empty parts being saved, e.g. some unit tests verify this currently. - if(part.getSize() == 0 && part.getPartName().getName().equals(XSSFRelation.SHARED_STRINGS.getDefaultFileName())) { - return true; - } + // check if there is anything to save for some parts. We don't do this for all parts as some code + // might depend on empty parts being saved, e.g. some unit tests verify this currently. + if(part.getSize() == 0 && part.getPartName().getName().equals(XSSFRelation.SHARED_STRINGS.getDefaultFileName())) { + return true; + } - ZipArchiveOutputStream zos = (ZipArchiveOutputStream) os; - ZipArchiveEntry partEntry = new ZipArchiveEntry(ZipHelper - .getZipItemNameFromOPCName(part.getPartName().getURI() - .getPath())); - try { - // Create next zip entry - zos.putArchiveEntry(partEntry); + ZipArchiveOutputStream zos = (ZipArchiveOutputStream) os; + ZipArchiveEntry partEntry = new ZipArchiveEntry(ZipHelper + .getZipItemNameFromOPCName(part.getPartName().getURI() + .getPath())); + try { + // Create next zip entry + zos.putArchiveEntry(partEntry); - // Saving data in the ZIP file - try (final InputStream ins = part.getInputStream()) { - IOUtils.copy(ins, zos); - } finally { - zos.closeArchiveEntry(); - } - } catch (IOException ioe) { - LOG.atError().withThrowable(ioe).log("Cannot write: {}: in ZIP", part.getPartName()); - return false; - } + // Saving data in the ZIP file + try (final InputStream ins = part.getInputStream()) { + IOUtils.copy(ins, zos); + } finally { + zos.closeArchiveEntry(); + } + } catch (IOException ioe) { + LOG.atError().withThrowable(ioe).log("Cannot write: {}: in ZIP", part.getPartName()); + return false; + } - // Saving relationship part - if (part.hasRelationships()) { - PackagePartName relationshipPartName = PackagingURIHelper - .getRelationshipPartName(part.getPartName()); + // Saving relationship part + if (part.hasRelationships()) { + PackagePartName relationshipPartName = PackagingURIHelper + .getRelationshipPartName(part.getPartName()); - marshallRelationshipPart(part.getRelationships(), - relationshipPartName, zos); - } + marshallRelationshipPart(part.getRelationships(), + relationshipPartName, zos); + } - return true; - } + return true; + } - /** - * Save relationships into the part. - * - * @param rels - * The relationships collection to marshall. - * @param relPartName - * Part name of the relationship part to marshall. - * @param zos - * Zip output stream in which to save the XML content of the - * relationships serialization. - * @return true if saving was successful, - * false if an error occurred. - * In case of errors, logging via Log4j 2 is used to provide more information. - */ - public static boolean marshallRelationshipPart( - PackageRelationshipCollection rels, PackagePartName relPartName, - ZipArchiveOutputStream zos) { - // Building xml - Document xmlOutDoc = DocumentHelper.createDocument(); - // make something like - Element root = xmlOutDoc.createElementNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIPS_TAG_NAME); + /** + * Save relationships into the part. + * + * @param rels + * The relationships collection to marshall. + * @param relPartName + * Part name of the relationship part to marshall. + * @param zos + * Zip output stream in which to save the XML content of the + * relationships serialization. + * @return true if saving was successful, + * false if an error occurred. + * In case of errors, logging via Log4j 2 is used to provide more information. + */ + public static boolean marshallRelationshipPart( + PackageRelationshipCollection rels, PackagePartName relPartName, + ZipArchiveOutputStream zos) { + // Building xml + Document xmlOutDoc = DocumentHelper.createDocument(); + // make something like + Element root = xmlOutDoc.createElementNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIPS_TAG_NAME); xmlOutDoc.appendChild(root); - // + // - URI sourcePartURI = PackagingURIHelper - .getSourcePartUriFromRelationshipPartUri(relPartName.getURI()); + URI sourcePartURI = PackagingURIHelper + .getSourcePartUriFromRelationshipPartUri(relPartName.getURI()); - for (PackageRelationship rel : rels) { - // the relationship element + for (PackageRelationship rel : rels) { + // the relationship element Element relElem = xmlOutDoc.createElementNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIP_TAG_NAME); root.appendChild(relElem); - // the relationship ID - relElem.setAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel.getId()); + // the relationship ID + relElem.setAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel.getId()); - // the relationship Type - relElem.setAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel.getRelationshipType()); + // the relationship Type + relElem.setAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel.getRelationshipType()); - // the relationship Target - String targetValue; - URI uri = rel.getTargetURI(); - if (rel.getTargetMode() == TargetMode.EXTERNAL) { - // Save the target as-is - we don't need to validate it, - // alter it etc - targetValue = uri.toString(); + // the relationship Target + String targetValue; + URI uri = rel.getTargetURI(); + if (rel.getTargetMode() == TargetMode.EXTERNAL) { + // Save the target as-is - we don't need to validate it, + // alter it etc + targetValue = uri.toString(); - // add TargetMode attribute (as it is external link external) - relElem.setAttribute(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME, "External"); - } else { + // add TargetMode attribute (as it is external link external) + relElem.setAttribute(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME, "External"); + } else { URI targetURI = rel.getTargetURI(); targetValue = PackagingURIHelper.relativizeURI( - sourcePartURI, targetURI, true).toString(); - } - relElem.setAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME, targetValue); - } + sourcePartURI, targetURI, true).toString(); + } + relElem.setAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME, targetValue); + } - xmlOutDoc.normalize(); + xmlOutDoc.normalize(); - // String schemaFilename = Configuration.getPathForXmlSchema()+ - // File.separator + "opc-relationships.xsd"; + // String schemaFilename = Configuration.getPathForXmlSchema()+ + // File.separator + "opc-relationships.xsd"; - // Save part in zip - ZipArchiveEntry ctEntry = new ZipArchiveEntry(ZipHelper.getZipURIFromOPCName( - relPartName.getURI().toASCIIString()).getPath()); - try { - zos.putArchiveEntry(ctEntry); - try { - return StreamHelper.saveXmlInStream(xmlOutDoc, zos); - } finally { - zos.closeArchiveEntry(); - } - } catch (IOException e) { - LOG.atError().withThrowable(e).log("Cannot create zip entry {}", relPartName); - return false; - } - } + // Save part in zip + ZipArchiveEntry ctEntry = new ZipArchiveEntry(ZipHelper.getZipURIFromOPCName( + relPartName.getURI().toASCIIString()).getPath()); + try { + zos.putArchiveEntry(ctEntry); + try { + return StreamHelper.saveXmlInStream(xmlOutDoc, zos); + } finally { + zos.closeArchiveEntry(); + } + } catch (IOException e) { + LOG.atError().withThrowable(e).log("Cannot create zip entry {}", relPartName); + return false; + } + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/PackagePropertiesUnmarshaller.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/PackagePropertiesUnmarshaller.java index ddcd0975c3..f3fac329d1 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/PackagePropertiesUnmarshaller.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/PackagePropertiesUnmarshaller.java @@ -44,97 +44,97 @@ import org.xml.sax.SAXException; */ public final class PackagePropertiesUnmarshaller implements PartUnmarshaller { - protected static final String KEYWORD_CATEGORY = "category"; + protected static final String KEYWORD_CATEGORY = "category"; - protected static final String KEYWORD_CONTENT_STATUS = "contentStatus"; + protected static final String KEYWORD_CONTENT_STATUS = "contentStatus"; - protected static final String KEYWORD_CONTENT_TYPE = "contentType"; + protected static final String KEYWORD_CONTENT_TYPE = "contentType"; - protected static final String KEYWORD_CREATED = "created"; + protected static final String KEYWORD_CREATED = "created"; - protected static final String KEYWORD_CREATOR = "creator"; + protected static final String KEYWORD_CREATOR = "creator"; - protected static final String KEYWORD_DESCRIPTION = "description"; + protected static final String KEYWORD_DESCRIPTION = "description"; - protected static final String KEYWORD_IDENTIFIER = "identifier"; + protected static final String KEYWORD_IDENTIFIER = "identifier"; - protected static final String KEYWORD_KEYWORDS = "keywords"; + protected static final String KEYWORD_KEYWORDS = "keywords"; - protected static final String KEYWORD_LANGUAGE = "language"; + protected static final String KEYWORD_LANGUAGE = "language"; - protected static final String KEYWORD_LAST_MODIFIED_BY = "lastModifiedBy"; + protected static final String KEYWORD_LAST_MODIFIED_BY = "lastModifiedBy"; - protected static final String KEYWORD_LAST_PRINTED = "lastPrinted"; + protected static final String KEYWORD_LAST_PRINTED = "lastPrinted"; - protected static final String KEYWORD_MODIFIED = "modified"; + protected static final String KEYWORD_MODIFIED = "modified"; - protected static final String KEYWORD_REVISION = "revision"; + protected static final String KEYWORD_REVISION = "revision"; - protected static final String KEYWORD_SUBJECT = "subject"; + protected static final String KEYWORD_SUBJECT = "subject"; - protected static final String KEYWORD_TITLE = "title"; + protected static final String KEYWORD_TITLE = "title"; - protected static final String KEYWORD_VERSION = "version"; + protected static final String KEYWORD_VERSION = "version"; - // TODO Load element with XMLBeans or dynamic table - // TODO Check every element/namespace for compliance - public PackagePart unmarshall(UnmarshallContext context, InputStream in) - throws InvalidFormatException, IOException { - PackagePropertiesPart coreProps = new PackagePropertiesPart(context - .getPackage(), context.getPartName()); + // TODO Load element with XMLBeans or dynamic table + // TODO Check every element/namespace for compliance + public PackagePart unmarshall(UnmarshallContext context, InputStream in) + throws InvalidFormatException, IOException { + PackagePropertiesPart coreProps = new PackagePropertiesPart(context + .getPackage(), context.getPartName()); - // If the input stream is null then we try to get it from the - // package. - if (in == null) { - if (context.getZipEntry() != null) { - in = ((ZipPackage) context.getPackage()).getZipArchive() - .getInputStream(context.getZipEntry()); - } else if (context.getPackage() != null) { - // Try to retrieve the part inputstream from the URI - ZipArchiveEntry zipEntry = ZipHelper - .getCorePropertiesZipEntry((ZipPackage) context - .getPackage()); - in = ((ZipPackage) context.getPackage()).getZipArchive() - .getInputStream(zipEntry); - } else - throw new IOException( - "Error while trying to get the part input stream."); - } + // If the input stream is null then we try to get it from the + // package. + if (in == null) { + if (context.getZipEntry() != null) { + in = ((ZipPackage) context.getPackage()).getZipArchive() + .getInputStream(context.getZipEntry()); + } else if (context.getPackage() != null) { + // Try to retrieve the part inputstream from the URI + ZipArchiveEntry zipEntry = ZipHelper + .getCorePropertiesZipEntry((ZipPackage) context + .getPackage()); + in = ((ZipPackage) context.getPackage()).getZipArchive() + .getInputStream(zipEntry); + } else + throw new IOException( + "Error while trying to get the part input stream."); + } - Document xmlDoc; - try { - xmlDoc = DocumentHelper.readDocument(in); + Document xmlDoc; + try { + xmlDoc = DocumentHelper.readDocument(in); - /* Check OPC compliance */ + /* Check OPC compliance */ - // Rule M4.2, M4.3, M4.4 and M4.5/ - checkElementForOPCCompliance(xmlDoc.getDocumentElement()); + // Rule M4.2, M4.3, M4.4 and M4.5/ + checkElementForOPCCompliance(xmlDoc.getDocumentElement()); - /* End OPC compliance */ + /* End OPC compliance */ } catch (SAXException e) { throw new IOException(e.getMessage()); } coreProps.setCategoryProperty(loadCategory(xmlDoc)); - coreProps.setContentStatusProperty(loadContentStatus(xmlDoc)); - coreProps.setContentTypeProperty(loadContentType(xmlDoc)); - coreProps.setCreatedProperty(loadCreated(xmlDoc)); - coreProps.setCreatorProperty(loadCreator(xmlDoc)); - coreProps.setDescriptionProperty(loadDescription(xmlDoc)); - coreProps.setIdentifierProperty(loadIdentifier(xmlDoc)); - coreProps.setKeywordsProperty(loadKeywords(xmlDoc)); - coreProps.setLanguageProperty(loadLanguage(xmlDoc)); - coreProps.setLastModifiedByProperty(loadLastModifiedBy(xmlDoc)); - coreProps.setLastPrintedProperty(loadLastPrinted(xmlDoc)); - coreProps.setModifiedProperty(loadModified(xmlDoc)); - coreProps.setRevisionProperty(loadRevision(xmlDoc)); - coreProps.setSubjectProperty(loadSubject(xmlDoc)); - coreProps.setTitleProperty(loadTitle(xmlDoc)); - coreProps.setVersionProperty(loadVersion(xmlDoc)); + coreProps.setContentStatusProperty(loadContentStatus(xmlDoc)); + coreProps.setContentTypeProperty(loadContentType(xmlDoc)); + coreProps.setCreatedProperty(loadCreated(xmlDoc)); + coreProps.setCreatorProperty(loadCreator(xmlDoc)); + coreProps.setDescriptionProperty(loadDescription(xmlDoc)); + coreProps.setIdentifierProperty(loadIdentifier(xmlDoc)); + coreProps.setKeywordsProperty(loadKeywords(xmlDoc)); + coreProps.setLanguageProperty(loadLanguage(xmlDoc)); + coreProps.setLastModifiedByProperty(loadLastModifiedBy(xmlDoc)); + coreProps.setLastPrintedProperty(loadLastPrinted(xmlDoc)); + coreProps.setModifiedProperty(loadModified(xmlDoc)); + coreProps.setRevisionProperty(loadRevision(xmlDoc)); + coreProps.setSubjectProperty(loadSubject(xmlDoc)); + coreProps.setTitleProperty(loadTitle(xmlDoc)); + coreProps.setVersionProperty(loadVersion(xmlDoc)); - return coreProps; - } + return coreProps; + } private String readElement(Document xmlDoc, String localName, String namespaceURI) { Element el = (Element)xmlDoc.getDocumentElement().getElementsByTagNameNS(namespaceURI, localName).item(0); @@ -144,97 +144,97 @@ public final class PackagePropertiesUnmarshaller implements PartUnmarshaller { return el.getTextContent(); } - private String loadCategory(Document xmlDoc) { + private String loadCategory(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_CATEGORY, PackageNamespaces.CORE_PROPERTIES); - } + } private String loadContentStatus(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_CONTENT_STATUS, PackageNamespaces.CORE_PROPERTIES); - } + } - private String loadContentType(Document xmlDoc) { + private String loadContentType(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_CONTENT_TYPE, PackageNamespaces.CORE_PROPERTIES); - } + } - private String loadCreated(Document xmlDoc) { + private String loadCreated(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_CREATED, PackageProperties.NAMESPACE_DCTERMS); - } + } - private String loadCreator(Document xmlDoc) { + private String loadCreator(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_CREATOR, PackageProperties.NAMESPACE_DC); - } + } - private String loadDescription(Document xmlDoc) { + private String loadDescription(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_DESCRIPTION, PackageProperties.NAMESPACE_DC); - } + } - private String loadIdentifier(Document xmlDoc) { + private String loadIdentifier(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_IDENTIFIER, PackageProperties.NAMESPACE_DC); - } + } - private String loadKeywords(Document xmlDoc) { + private String loadKeywords(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_KEYWORDS, PackageNamespaces.CORE_PROPERTIES); - } + } - private String loadLanguage(Document xmlDoc) { + private String loadLanguage(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_LANGUAGE, PackageProperties.NAMESPACE_DC); - } + } - private String loadLastModifiedBy(Document xmlDoc) { + private String loadLastModifiedBy(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_LAST_MODIFIED_BY, PackageNamespaces.CORE_PROPERTIES); - } + } - private String loadLastPrinted(Document xmlDoc) { + private String loadLastPrinted(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_LAST_PRINTED, PackageNamespaces.CORE_PROPERTIES); - } + } - private String loadModified(Document xmlDoc) { + private String loadModified(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_MODIFIED, PackageProperties.NAMESPACE_DCTERMS); - } + } - private String loadRevision(Document xmlDoc) { + private String loadRevision(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_REVISION, PackageNamespaces.CORE_PROPERTIES); - } + } - private String loadSubject(Document xmlDoc) { + private String loadSubject(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_SUBJECT, PackageProperties.NAMESPACE_DC); - } + } - private String loadTitle(Document xmlDoc) { + private String loadTitle(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_TITLE, PackageProperties.NAMESPACE_DC); - } + } - private String loadVersion(Document xmlDoc) { + private String loadVersion(Document xmlDoc) { return readElement(xmlDoc, KEYWORD_VERSION, PackageNamespaces.CORE_PROPERTIES); - } + } - /* OPC Compliance methods */ + /* OPC Compliance methods */ - /** - * Check the element for the following OPC compliance rules: - *

- * Rule M4.2: A format consumer shall consider the use of the Markup - * Compatibility namespace to be an error. - *

- * Rule M4.3: Producers shall not create a document element that contains - * refinements to the Dublin Core elements, except for the two specified in - * the schema: <dcterms:created> and <dcterms:modified> Consumers shall - * consider a document element that violates this constraint to be an error. - *

- * Rule M4.4: Producers shall not create a document element that contains - * the xml:lang attribute. Consumers shall consider a document element that - * violates this constraint to be an error. - *

- * Rule M4.5: Producers shall not create a document element that contains - * the xsi:type attribute, except for a <dcterms:created> or - * <dcterms:modified> element where the xsi:type attribute shall be present - * and shall hold the value dcterms:W3CDTF, where dcterms is the namespace - * prefix of the Dublin Core namespace. Consumers shall consider a document - * element that violates this constraint to be an error. - */ - public void checkElementForOPCCompliance(Element el) - throws InvalidFormatException { - // Check the current element + /** + * Check the element for the following OPC compliance rules: + *

+ * Rule M4.2: A format consumer shall consider the use of the Markup + * Compatibility namespace to be an error. + *

+ * Rule M4.3: Producers shall not create a document element that contains + * refinements to the Dublin Core elements, except for the two specified in + * the schema: <dcterms:created> and <dcterms:modified> Consumers shall + * consider a document element that violates this constraint to be an error. + *

+ * Rule M4.4: Producers shall not create a document element that contains + * the xml:lang attribute. Consumers shall consider a document element that + * violates this constraint to be an error. + *

+ * Rule M4.5: Producers shall not create a document element that contains + * the xsi:type attribute, except for a <dcterms:created> or + * <dcterms:modified> element where the xsi:type attribute shall be present + * and shall hold the value dcterms:W3CDTF, where dcterms is the namespace + * prefix of the Dublin Core namespace. Consumers shall consider a document + * element that violates this constraint to be an error. + */ + public void checkElementForOPCCompliance(Element el) + throws InvalidFormatException { + // Check the current element NamedNodeMap namedNodeMap = el.getAttributes(); int namedNodeCount = namedNodeMap.getLength(); for (int i = 0; i < namedNodeCount; i++) { @@ -249,42 +249,42 @@ public final class PackagePropertiesUnmarshaller implements PartUnmarshaller { } } - // Rule M4.3 + // Rule M4.3 String elName = el.getLocalName(); if (el.getNamespaceURI().equals(PackageProperties.NAMESPACE_DCTERMS)) if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED))) throw new InvalidFormatException( "OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: and Consumers shall consider a document element that violates this constraint to be an error."); - // Rule M4.4 - if (el.getAttributeNodeNS(XMLConstants.XML_NS_URI, "lang") != null) - throw new InvalidFormatException( - "OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error."); + // Rule M4.4 + if (el.getAttributeNodeNS(XMLConstants.XML_NS_URI, "lang") != null) + throw new InvalidFormatException( + "OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error."); - // Rule M4.5 - if (el.getNamespaceURI().equals(PackageProperties.NAMESPACE_DCTERMS)) { - // DCTerms namespace only use with 'created' and 'modified' elements - if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED))) - throw new InvalidFormatException("Namespace error : " + elName - + " shouldn't have the following naemspace -> " - + PackageProperties.NAMESPACE_DCTERMS); + // Rule M4.5 + if (el.getNamespaceURI().equals(PackageProperties.NAMESPACE_DCTERMS)) { + // DCTerms namespace only use with 'created' and 'modified' elements + if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED))) + throw new InvalidFormatException("Namespace error : " + elName + + " shouldn't have the following naemspace -> " + + PackageProperties.NAMESPACE_DCTERMS); - // Check for the 'xsi:type' attribute - Attr typeAtt = el.getAttributeNodeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type"); - if (typeAtt == null) - throw new InvalidFormatException("The element '" + elName - + "' must have the 'xsi:type' attribute present !"); + // Check for the 'xsi:type' attribute + Attr typeAtt = el.getAttributeNodeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type"); + if (typeAtt == null) + throw new InvalidFormatException("The element '" + elName + + "' must have the 'xsi:type' attribute present !"); - // Check for the attribute value => 'dcterms:W3CDTF' - if (!typeAtt.getValue().equals(el.getPrefix() + ":W3CDTF")) - throw new InvalidFormatException("The element '" + elName - + "' must have the 'xsi:type' attribute with the value '" + el.getPrefix() + ":W3CDTF', but had '" + typeAtt.getValue() + "' !"); - } + // Check for the attribute value => 'dcterms:W3CDTF' + if (!typeAtt.getValue().equals(el.getPrefix() + ":W3CDTF")) + throw new InvalidFormatException("The element '" + elName + + "' must have the 'xsi:type' attribute with the value '" + el.getPrefix() + ":W3CDTF', but had '" + typeAtt.getValue() + "' !"); + } - // Check its children + // Check its children NodeList childElements = el.getElementsByTagName("*"); int childElementCount = childElements.getLength(); for (int i = 0; i < childElementCount; i++) checkElementForOPCCompliance((Element)childElements.item(i)); - } + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/UnmarshallContext.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/UnmarshallContext.java index 485b549b72..62643baa4d 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/UnmarshallContext.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/UnmarshallContext.java @@ -28,67 +28,67 @@ import org.apache.poi.openxml4j.opc.PackagePartName; */ public final class UnmarshallContext { - private OPCPackage _package; + private OPCPackage _package; - private PackagePartName partName; + private PackagePartName partName; - private ZipArchiveEntry zipEntry; + private ZipArchiveEntry zipEntry; - /** - * Constructor. - * - * @param targetPackage - * Container. - * @param partName - * Name of the part to unmarshall. - */ - public UnmarshallContext(OPCPackage targetPackage, PackagePartName partName) { - this._package = targetPackage; - this.partName = partName; - } + /** + * Constructor. + * + * @param targetPackage + * Container. + * @param partName + * Name of the part to unmarshall. + */ + public UnmarshallContext(OPCPackage targetPackage, PackagePartName partName) { + this._package = targetPackage; + this.partName = partName; + } - /** - * @return the container - */ - OPCPackage getPackage() { - return _package; - } + /** + * @return the container + */ + OPCPackage getPackage() { + return _package; + } - /** - * @param container - * the container to set - */ - public void setPackage(OPCPackage container) { - this._package = container; - } + /** + * @param container + * the container to set + */ + public void setPackage(OPCPackage container) { + this._package = container; + } - /** - * @return the partName - */ - PackagePartName getPartName() { - return partName; - } + /** + * @return the partName + */ + PackagePartName getPartName() { + return partName; + } - /** - * @param partName - * the partName to set - */ - public void setPartName(PackagePartName partName) { - this.partName = partName; - } + /** + * @param partName + * the partName to set + */ + public void setPartName(PackagePartName partName) { + this.partName = partName; + } - /** - * @return the zipEntry - */ - ZipArchiveEntry getZipEntry() { - return zipEntry; - } + /** + * @return the zipEntry + */ + ZipArchiveEntry getZipEntry() { + return zipEntry; + } - /** - * @param zipEntry - * the zipEntry to set - */ - public void setZipEntry(ZipArchiveEntry zipEntry) { - this.zipEntry = zipEntry; - } + /** + * @param zipEntry + * the zipEntry to set + */ + public void setZipEntry(ZipArchiveEntry zipEntry) { + this.zipEntry = zipEntry; + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/util/ZipEntrySource.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/util/ZipEntrySource.java index 00961dffd4..8f4737038a 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/util/ZipEntrySource.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/util/ZipEntrySource.java @@ -31,35 +31,35 @@ import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; * being annoyingly very different. */ public interface ZipEntrySource extends Closeable { - /** - * Returns an Enumeration of all the Entries - */ - Enumeration getEntries(); + /** + * Returns an Enumeration of all the Entries + */ + Enumeration getEntries(); - /** - * Return an entry by its path - * @param path the path in unix-notation - * @return the entry or {@code null} if not found - * - * @since POI 4.0.0 - */ - ZipArchiveEntry getEntry(String path); + /** + * Return an entry by its path + * @param path the path in unix-notation + * @return the entry or {@code null} if not found + * + * @since POI 4.0.0 + */ + ZipArchiveEntry getEntry(String path); - /** - * Returns an InputStream of the decompressed - * data that makes up the entry - */ - InputStream getInputStream(ZipArchiveEntry entry) throws IOException; - - /** - * Indicates we are done with reading, and - * resources may be freed - */ - @Override - void close() throws IOException; - - /** - * Has close been called already? - */ - boolean isClosed(); + /** + * Returns an InputStream of the decompressed + * data that makes up the entry + */ + InputStream getInputStream(ZipArchiveEntry entry) throws IOException; + + /** + * Indicates we are done with reading, and + * resources may be freed + */ + @Override + void close() throws IOException; + + /** + * Has close been called already? + */ + boolean isClosed(); } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/util/ZipInputStreamZipEntrySource.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/util/ZipInputStreamZipEntrySource.java index 57103d2906..ee25086f78 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/util/ZipInputStreamZipEntrySource.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/util/ZipInputStreamZipEntrySource.java @@ -34,66 +34,66 @@ import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; * done, to free up that memory! */ public class ZipInputStreamZipEntrySource implements ZipEntrySource { - private final Map zipEntries = new HashMap<>(); + private final Map zipEntries = new HashMap<>(); - private InputStream streamToClose; + private InputStream streamToClose; - /** - * Reads all the entries from the ZipInputStream - * into memory, and don't close (since POI 4.0.1) the source stream. - * We'll then eat lots of memory, but be able to - * work with the entries at-will. - */ - public ZipInputStreamZipEntrySource(ZipArchiveThresholdInputStream inp) throws IOException { - for (;;) { - final ZipArchiveEntry zipEntry = inp.getNextEntry(); - if (zipEntry == null) { - break; - } - zipEntries.put(zipEntry.getName(), new ZipArchiveFakeEntry(zipEntry, inp)); - } + /** + * Reads all the entries from the ZipInputStream + * into memory, and don't close (since POI 4.0.1) the source stream. + * We'll then eat lots of memory, but be able to + * work with the entries at-will. + */ + public ZipInputStreamZipEntrySource(ZipArchiveThresholdInputStream inp) throws IOException { + for (;;) { + final ZipArchiveEntry zipEntry = inp.getNextEntry(); + if (zipEntry == null) { + break; + } + zipEntries.put(zipEntry.getName(), new ZipArchiveFakeEntry(zipEntry, inp)); + } - streamToClose = inp; - } + streamToClose = inp; + } - @Override - public Enumeration getEntries() { - return Collections.enumeration(zipEntries.values()); - } + @Override + public Enumeration getEntries() { + return Collections.enumeration(zipEntries.values()); + } - @Override - public InputStream getInputStream(ZipArchiveEntry zipEntry) { - assert (zipEntry instanceof ZipArchiveFakeEntry); - return ((ZipArchiveFakeEntry)zipEntry).getInputStream(); - } + @Override + public InputStream getInputStream(ZipArchiveEntry zipEntry) { + assert (zipEntry instanceof ZipArchiveFakeEntry); + return ((ZipArchiveFakeEntry)zipEntry).getInputStream(); + } - @Override - public void close() throws IOException { - // Free the memory - zipEntries.clear(); + @Override + public void close() throws IOException { + // Free the memory + zipEntries.clear(); - streamToClose.close(); - } + streamToClose.close(); + } - @Override - public boolean isClosed() { - return zipEntries.isEmpty(); - } + @Override + public boolean isClosed() { + return zipEntries.isEmpty(); + } - @Override - public ZipArchiveEntry getEntry(final String path) { - final String normalizedPath = path.replace('\\', '/'); - final ZipArchiveEntry ze = zipEntries.get(normalizedPath); - if (ze != null) { - return ze; - } + @Override + public ZipArchiveEntry getEntry(final String path) { + final String normalizedPath = path.replace('\\', '/'); + final ZipArchiveEntry ze = zipEntries.get(normalizedPath); + if (ze != null) { + return ze; + } - for (final Map.Entry fze : zipEntries.entrySet()) { - if (normalizedPath.equalsIgnoreCase(fze.getKey())) { - return fze.getValue(); - } - } + for (final Map.Entry fze : zipEntries.entrySet()) { + if (normalizedPath.equalsIgnoreCase(fze.getKey())) { + return fze.getValue(); + } + } - return null; - } + return null; + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xddf/usermodel/chart/XDDFManualLayout.java b/poi-ooxml/src/main/java/org/apache/poi/xddf/usermodel/chart/XDDFManualLayout.java index 856a530fbc..85c128ff3d 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xddf/usermodel/chart/XDDFManualLayout.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xddf/usermodel/chart/XDDFManualLayout.java @@ -1,10 +1,10 @@ /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with + contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at + the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFComment.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFComment.java index ab925b2f0c..9abc38ebe8 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFComment.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFComment.java @@ -68,7 +68,7 @@ public class XSLFComment implements Comment { final CTCommentAuthor newAuthor = list.addNewCmAuthor(); newAuthor.setName(author); newAuthor.setId(maxId+1); - newAuthor.setInitials(author.replaceAll( "\\s*(\\w)\\S*", "$1").toUpperCase(LocaleUtil.getUserLocale())); + newAuthor.setInitials(author.replaceAll( "\\s*(\\w)\\S*", "$1").toUpperCase(LocaleUtil.getUserLocale())); comment.setAuthorId(maxId+1); } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFGraphicFrame.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFGraphicFrame.java index 59109b7e32..e85e9608ec 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFGraphicFrame.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFGraphicFrame.java @@ -122,7 +122,7 @@ public class XSLFGraphicFrame extends XSLFShape implements GraphicalFrame { @Override public XSLFTheme getTheme(){ final XSLFNotesMaster m = getMasterSheet(); - return (m != null) ? m.getTheme() : null; + return (m != null) ? m.getTheme() : null; } @Override diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFNotesMaster.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFNotesMaster.java index 00e7f09819..b3bd64f348 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFNotesMaster.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFNotesMaster.java @@ -46,7 +46,7 @@ import org.openxmlformats.schemas.presentationml.x2006.main.NotesMasterDocument; @Beta public class XSLFNotesMaster extends XSLFSheet implements MasterSheet { - private CTNotesMaster _slide; + private CTNotesMaster _slide; XSLFNotesMaster() { super(); diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSlideMaster.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSlideMaster.java index 7a20d04d1d..c473fa2389 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSlideMaster.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSlideMaster.java @@ -53,7 +53,7 @@ import org.openxmlformats.schemas.presentationml.x2006.main.SldMasterDocument; @Beta public class XSLFSlideMaster extends XSLFSheet implements MasterSheet { - private CTSlideMaster _slide; + private CTSlideMaster _slide; private Map _layouts; /** @@ -67,9 +67,9 @@ import org.openxmlformats.schemas.presentationml.x2006.main.SldMasterDocument; } @Override - public CTSlideMaster getXmlObject() { - return _slide; - } + public CTSlideMaster getXmlObject() { + return _slide; + } @Override protected String getRootElementName(){ diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSlideShow.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSlideShow.java index 4b30679d41..f7719d3073 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSlideShow.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFSlideShow.java @@ -6,7 +6,7 @@ (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, @@ -61,203 +61,203 @@ import org.openxmlformats.schemas.presentationml.x2006.main.SldMasterDocument; */ public class XSLFSlideShow extends POIXMLDocument { - private final PresentationDocument presentationDoc; - /** - * The embedded OLE2 files in the OPC package - */ - private final List embedds; + private final PresentationDocument presentationDoc; + /** + * The embedded OLE2 files in the OPC package + */ + private final List embedds; - public XSLFSlideShow(OPCPackage container) throws OpenXML4JException, IOException, XmlException { - super(container); + public XSLFSlideShow(OPCPackage container) throws OpenXML4JException, IOException, XmlException { + super(container); - if(getCorePart().getContentType().equals(XSLFRelation.THEME_MANAGER.getContentType())) { - rebase(getPackage()); - } + if(getCorePart().getContentType().equals(XSLFRelation.THEME_MANAGER.getContentType())) { + rebase(getPackage()); + } - presentationDoc = - PresentationDocument.Factory.parse(getCorePart().getInputStream(), DEFAULT_XML_OPTIONS); + presentationDoc = + PresentationDocument.Factory.parse(getCorePart().getInputStream(), DEFAULT_XML_OPTIONS); - embedds = new LinkedList<>(); - for (CTSlideIdListEntry ctSlide : getSlideReferences().getSldIdArray()) { - PackagePart corePart = getCorePart(); - PackagePart slidePart = corePart.getRelatedPart(corePart.getRelationship(ctSlide.getId2())); + embedds = new LinkedList<>(); + for (CTSlideIdListEntry ctSlide : getSlideReferences().getSldIdArray()) { + PackagePart corePart = getCorePart(); + PackagePart slidePart = corePart.getRelatedPart(corePart.getRelationship(ctSlide.getId2())); - for(PackageRelationship rel : slidePart.getRelationshipsByType(OLE_OBJECT_REL_TYPE)) { - if (TargetMode.EXTERNAL == rel.getTargetMode()) { - continue; - } - // TODO: Add this reference to each slide as well - embedds.add(slidePart.getRelatedPart(rel)); - } + for(PackageRelationship rel : slidePart.getRelationshipsByType(OLE_OBJECT_REL_TYPE)) { + if (TargetMode.EXTERNAL == rel.getTargetMode()) { + continue; + } + // TODO: Add this reference to each slide as well + embedds.add(slidePart.getRelatedPart(rel)); + } - for (PackageRelationship rel : slidePart.getRelationshipsByType(PACK_OBJECT_REL_TYPE)) { - embedds.add(slidePart.getRelatedPart(rel)); - } - } - } - public XSLFSlideShow(String file) throws OpenXML4JException, IOException, XmlException { - this(openPackage(file)); - } + for (PackageRelationship rel : slidePart.getRelationshipsByType(PACK_OBJECT_REL_TYPE)) { + embedds.add(slidePart.getRelatedPart(rel)); + } + } + } + public XSLFSlideShow(String file) throws OpenXML4JException, IOException, XmlException { + this(openPackage(file)); + } - /** - * Returns the low level presentation base object - */ - @Internal - public CTPresentation getPresentation() { - return presentationDoc.getPresentation(); - } + /** + * Returns the low level presentation base object + */ + @Internal + public CTPresentation getPresentation() { + return presentationDoc.getPresentation(); + } - /** - * Returns the references from the presentation to its - * slides. - * You'll need these to figure out the slide ordering, - * and to get at the actual slides themselves - */ - @Internal - public CTSlideIdList getSlideReferences() { - if(! getPresentation().isSetSldIdLst()) { - getPresentation().setSldIdLst(CTSlideIdList.Factory.newInstance()); - } - return getPresentation().getSldIdLst(); - } + /** + * Returns the references from the presentation to its + * slides. + * You'll need these to figure out the slide ordering, + * and to get at the actual slides themselves + */ + @Internal + public CTSlideIdList getSlideReferences() { + if(! getPresentation().isSetSldIdLst()) { + getPresentation().setSldIdLst(CTSlideIdList.Factory.newInstance()); + } + return getPresentation().getSldIdLst(); + } - /** - * Returns the references from the presentation to its - * slide masters. - * You'll need these to get at the actual slide - * masters themselves - */ - @Internal - public CTSlideMasterIdList getSlideMasterReferences() { - return getPresentation().getSldMasterIdLst(); - } + /** + * Returns the references from the presentation to its + * slide masters. + * You'll need these to get at the actual slide + * masters themselves + */ + @Internal + public CTSlideMasterIdList getSlideMasterReferences() { + return getPresentation().getSldMasterIdLst(); + } - public PackagePart getSlideMasterPart(CTSlideMasterIdListEntry master) throws IOException, XmlException { - try { - PackagePart corePart = getCorePart(); - return corePart.getRelatedPart( - corePart.getRelationship(master.getId2()) - ); - } catch(InvalidFormatException e) { - throw new XmlException(e); - } - } - /** - * Returns the low level slide master object from - * the supplied slide master reference - */ - @Internal - public CTSlideMaster getSlideMaster(CTSlideMasterIdListEntry master) throws IOException, XmlException { - PackagePart masterPart = getSlideMasterPart(master); - SldMasterDocument masterDoc = - SldMasterDocument.Factory.parse(masterPart.getInputStream(), DEFAULT_XML_OPTIONS); - return masterDoc.getSldMaster(); - } + public PackagePart getSlideMasterPart(CTSlideMasterIdListEntry master) throws IOException, XmlException { + try { + PackagePart corePart = getCorePart(); + return corePart.getRelatedPart( + corePart.getRelationship(master.getId2()) + ); + } catch(InvalidFormatException e) { + throw new XmlException(e); + } + } + /** + * Returns the low level slide master object from + * the supplied slide master reference + */ + @Internal + public CTSlideMaster getSlideMaster(CTSlideMasterIdListEntry master) throws IOException, XmlException { + PackagePart masterPart = getSlideMasterPart(master); + SldMasterDocument masterDoc = + SldMasterDocument.Factory.parse(masterPart.getInputStream(), DEFAULT_XML_OPTIONS); + return masterDoc.getSldMaster(); + } - public PackagePart getSlidePart(CTSlideIdListEntry slide) throws IOException, XmlException { - try { - PackagePart corePart = getCorePart(); - return corePart.getRelatedPart(corePart.getRelationship(slide.getId2())); - } catch(InvalidFormatException e) { - throw new XmlException(e); - } - } - /** - * Returns the low level slide object from - * the supplied slide reference - */ - @Internal - public CTSlide getSlide(CTSlideIdListEntry slide) throws IOException, XmlException { - PackagePart slidePart = getSlidePart(slide); - SldDocument slideDoc = - SldDocument.Factory.parse(slidePart.getInputStream(), DEFAULT_XML_OPTIONS); - return slideDoc.getSld(); - } + public PackagePart getSlidePart(CTSlideIdListEntry slide) throws IOException, XmlException { + try { + PackagePart corePart = getCorePart(); + return corePart.getRelatedPart(corePart.getRelationship(slide.getId2())); + } catch(InvalidFormatException e) { + throw new XmlException(e); + } + } + /** + * Returns the low level slide object from + * the supplied slide reference + */ + @Internal + public CTSlide getSlide(CTSlideIdListEntry slide) throws IOException, XmlException { + PackagePart slidePart = getSlidePart(slide); + SldDocument slideDoc = + SldDocument.Factory.parse(slidePart.getInputStream(), DEFAULT_XML_OPTIONS); + return slideDoc.getSld(); + } - /** - * Gets the PackagePart of the notes for the - * given slide, or null if there isn't one. - */ - public PackagePart getNodesPart(CTSlideIdListEntry parentSlide) throws IOException, XmlException { - PackageRelationshipCollection notes; - PackagePart slidePart = getSlidePart(parentSlide); + /** + * Gets the PackagePart of the notes for the + * given slide, or null if there isn't one. + */ + public PackagePart getNodesPart(CTSlideIdListEntry parentSlide) throws IOException, XmlException { + PackageRelationshipCollection notes; + PackagePart slidePart = getSlidePart(parentSlide); - try { - notes = slidePart.getRelationshipsByType(XSLFRelation.NOTES.getRelation()); - } catch(InvalidFormatException e) { - throw new IllegalStateException(e); - } + try { + notes = slidePart.getRelationshipsByType(XSLFRelation.NOTES.getRelation()); + } catch(InvalidFormatException e) { + throw new IllegalStateException(e); + } - if(notes.size() == 0) { - // No notes for this slide - return null; - } - if(notes.size() > 1) { - throw new IllegalStateException("Expecting 0 or 1 notes for a slide, but found " + notes.size()); - } + if(notes.size() == 0) { + // No notes for this slide + return null; + } + if(notes.size() > 1) { + throw new IllegalStateException("Expecting 0 or 1 notes for a slide, but found " + notes.size()); + } - try { - return slidePart.getRelatedPart(notes.getRelationship(0)); - } catch(InvalidFormatException e) { - throw new IllegalStateException(e); - } - } - /** - * Returns the low level notes object for the given - * slide, as found from the supplied slide reference - */ - @Internal - public CTNotesSlide getNotes(CTSlideIdListEntry slide) throws IOException, XmlException { - PackagePart notesPart = getNodesPart(slide); - if(notesPart == null) - return null; + try { + return slidePart.getRelatedPart(notes.getRelationship(0)); + } catch(InvalidFormatException e) { + throw new IllegalStateException(e); + } + } + /** + * Returns the low level notes object for the given + * slide, as found from the supplied slide reference + */ + @Internal + public CTNotesSlide getNotes(CTSlideIdListEntry slide) throws IOException, XmlException { + PackagePart notesPart = getNodesPart(slide); + if(notesPart == null) + return null; - NotesDocument notesDoc = - NotesDocument.Factory.parse(notesPart.getInputStream(), DEFAULT_XML_OPTIONS); + NotesDocument notesDoc = + NotesDocument.Factory.parse(notesPart.getInputStream(), DEFAULT_XML_OPTIONS); - return notesDoc.getNotes(); - } + return notesDoc.getNotes(); + } - /** - * Returns all the comments for the given slide - */ - @Internal - public CTCommentList getSlideComments(CTSlideIdListEntry slide) throws IOException, XmlException { - PackageRelationshipCollection commentRels; - PackagePart slidePart = getSlidePart(slide); + /** + * Returns all the comments for the given slide + */ + @Internal + public CTCommentList getSlideComments(CTSlideIdListEntry slide) throws IOException, XmlException { + PackageRelationshipCollection commentRels; + PackagePart slidePart = getSlidePart(slide); - try { - commentRels = slidePart.getRelationshipsByType(XSLFRelation.COMMENTS.getRelation()); - } catch(InvalidFormatException e) { - throw new IllegalStateException(e); - } + try { + commentRels = slidePart.getRelationshipsByType(XSLFRelation.COMMENTS.getRelation()); + } catch(InvalidFormatException e) { + throw new IllegalStateException(e); + } - if(commentRels.size() == 0) { - // No comments for this slide - return null; - } - if(commentRels.size() > 1) { - throw new IllegalStateException("Expecting 0 or 1 comments for a slide, but found " + commentRels.size()); - } + if(commentRels.size() == 0) { + // No comments for this slide + return null; + } + if(commentRels.size() > 1) { + throw new IllegalStateException("Expecting 0 or 1 comments for a slide, but found " + commentRels.size()); + } - try { - PackagePart cPart = slidePart.getRelatedPart( - commentRels.getRelationship(0) - ); - CmLstDocument commDoc = - CmLstDocument.Factory.parse(cPart.getInputStream(), DEFAULT_XML_OPTIONS); - return commDoc.getCmLst(); - } catch(InvalidFormatException e) { - throw new IllegalStateException(e); - } - } + try { + PackagePart cPart = slidePart.getRelatedPart( + commentRels.getRelationship(0) + ); + CmLstDocument commDoc = + CmLstDocument.Factory.parse(cPart.getInputStream(), DEFAULT_XML_OPTIONS); + return commDoc.getCmLst(); + } catch(InvalidFormatException e) { + throw new IllegalStateException(e); + } + } - /** - * Get the document's embedded files. - */ - @Override - public List getAllEmbeddedParts() throws OpenXML4JException { - return embedds; - } + /** + * Get the document's embedded files. + */ + @Override + public List getAllEmbeddedParts() throws OpenXML4JException { + return embedds; + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTable.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTable.java index e640ba82ae..d2adc919e1 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTable.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTable.java @@ -279,50 +279,50 @@ public class XSLFTable extends XSLFGraphicFrame implements Iterable lastRow) { - throw new IllegalArgumentException( - "Cannot merge, first row > last row : " - + firstRow + " > " + lastRow - ); - } + if(firstRow > lastRow) { + throw new IllegalArgumentException( + "Cannot merge, first row > last row : " + + firstRow + " > " + lastRow + ); + } - if(firstCol > lastCol) { - throw new IllegalArgumentException( - "Cannot merge, first column > last column : " - + firstCol + " > " + lastCol - ); - } + if(firstCol > lastCol) { + throw new IllegalArgumentException( + "Cannot merge, first column > last column : " + + firstCol + " > " + lastCol + ); + } - int rowSpan = (lastRow - firstRow) + 1; - boolean mergeRowRequired = rowSpan > 1; + int rowSpan = (lastRow - firstRow) + 1; + boolean mergeRowRequired = rowSpan > 1; - int colSpan = (lastCol - firstCol) + 1; - boolean mergeColumnRequired = colSpan > 1; + int colSpan = (lastCol - firstCol) + 1; + boolean mergeColumnRequired = colSpan > 1; - for(int i = firstRow; i <= lastRow; i++) { + for(int i = firstRow; i <= lastRow; i++) { - XSLFTableRow row = _rows.get(i); + XSLFTableRow row = _rows.get(i); - for(int colPos = firstCol; colPos <= lastCol; colPos++) { + for(int colPos = firstCol; colPos <= lastCol; colPos++) { - XSLFTableCell cell = row.getCells().get(colPos); + XSLFTableCell cell = row.getCells().get(colPos); - if(mergeRowRequired) { - if(i == firstRow) { - cell.setRowSpan(rowSpan); - } else { - cell.setVMerge(); - } - } - if(mergeColumnRequired) { - if(colPos == firstCol) { - cell.setGridSpan(colSpan); - } else { - cell.setHMerge(); - } - } - } - } + if(mergeRowRequired) { + if(i == firstRow) { + cell.setRowSpan(rowSpan); + } else { + cell.setVMerge(); + } + } + if(mergeColumnRequired) { + if(colPos == firstCol) { + cell.setGridSpan(colSpan); + } else { + cell.setHMerge(); + } + } + } + } } /** diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTextParagraph.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTextParagraph.java index a30571f16e..ca9f2f64bb 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTextParagraph.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTextParagraph.java @@ -717,18 +717,18 @@ public class XSLFTextParagraph implements TextParagraph= 0) { cur.push(); - if (cur.toChild(XSLFRelation.NS_DRAWINGML, "lvl" +(level+1)+ "pPr")) { - return (CTTextParagraphProperties)cur.getObject(); - } - cur.pop(); - level--; + if (cur.toChild(XSLFRelation.NS_DRAWINGML, "lvl" +(level+1)+ "pPr")) { + return (CTTextParagraphProperties)cur.getObject(); + } + cur.pop(); + level--; } } } finally { - cur.dispose(); + cur.dispose(); } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTheme.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTheme.java index 8744b80690..f033792eb4 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTheme.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFTheme.java @@ -87,7 +87,7 @@ public class XSLFTheme extends POIXMLDocumentPart { public CTColor getCTColor(String name) { CTBaseStyles elems = _theme.getThemeElements(); CTColorScheme scheme = (elems == null) ? null : elems.getClrScheme(); - return getMapColor(name, scheme); + return getMapColor(name, scheme); } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/XLSBUnsupportedException.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/XLSBUnsupportedException.java index 6834d81001..1cc79b256c 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/XLSBUnsupportedException.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/XLSBUnsupportedException.java @@ -28,6 +28,6 @@ public class XLSBUnsupportedException extends UnsupportedFileFormatException { public static final String MESSAGE = ".XLSB Binary Workbooks are not supported"; public XLSBUnsupportedException() { - super(MESSAGE); - } + super(MESSAGE); + } } \ No newline at end of file diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java index d918ae1a65..c6afb66558 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java @@ -461,14 +461,14 @@ public class XSSFExportToXml implements Comparator{ return indexMap.getOrDefault(withPath, -1); } - private Node getNameOrRefElement(Node node) { - Node returnNode = node.getAttributes().getNamedItem("ref"); + private Node getNameOrRefElement(Node node) { + Node returnNode = node.getAttributes().getNamedItem("ref"); if(returnNode != null) { return returnNode; - } - + } + return node.getAttributes().getNamedItem("name"); - } + } private Node getComplexTypeForElement(String elementName,Node xmlSchema,Node localComplexTypeRootNode) { String elementNameWithoutNamespace = removeNamespace(elementName); diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/model/MapInfo.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/model/MapInfo.java index 1361e310d9..c210181e9a 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/model/MapInfo.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/model/MapInfo.java @@ -48,40 +48,40 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.MapInfoDocument; public class MapInfo extends POIXMLDocumentPart { - private CTMapInfo mapInfo; + private CTMapInfo mapInfo; - private Map maps ; + private Map maps ; - public MapInfo() { - super(); - mapInfo = CTMapInfo.Factory.newInstance(); + public MapInfo() { + super(); + mapInfo = CTMapInfo.Factory.newInstance(); - } - - /** - * @since POI 3.14-Beta1 - */ - public MapInfo(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); } - public void readFrom(InputStream is) throws IOException { - try { - MapInfoDocument doc = MapInfoDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - mapInfo = doc.getMapInfo(); + /** + * @since POI 3.14-Beta1 + */ + public MapInfo(PackagePart part) throws IOException { + super(part); + readFrom(part.getInputStream()); + } + + public void readFrom(InputStream is) throws IOException { + try { + MapInfoDocument doc = MapInfoDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); + mapInfo = doc.getMapInfo(); maps= new HashMap<>(); for(CTMap map :mapInfo.getMapArray()){ maps.put((int)map.getID(), new XSSFMap(map,this)); } - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } + } catch (XmlException e) { + throw new IOException(e.getLocalizedMessage()); + } + } - /** + /** * Returns the parent XSSFWorkbook * * @return the parent XSSFWorkbook @@ -90,70 +90,70 @@ public class MapInfo extends POIXMLDocumentPart { return (XSSFWorkbook)getParent(); } - /** - * - * @return the internal data object - */ - public CTMapInfo getCTMapInfo(){ - return mapInfo; + /** + * + * @return the internal data object + */ + public CTMapInfo getCTMapInfo(){ + return mapInfo; - } + } - /** - * Gets the - * @param schemaId the schema ID - * @return CTSchema by it's ID - */ - public CTSchema getCTSchemaById(String schemaId){ - CTSchema xmlSchema = null; + /** + * Gets the + * @param schemaId the schema ID + * @return CTSchema by it's ID + */ + public CTSchema getCTSchemaById(String schemaId){ + CTSchema xmlSchema = null; - for(CTSchema schema: mapInfo.getSchemaArray()){ - if(schema.getID().equals(schemaId)){ - xmlSchema = schema; - break; - } - } - return xmlSchema; - } + for(CTSchema schema: mapInfo.getSchemaArray()){ + if(schema.getID().equals(schemaId)){ + xmlSchema = schema; + break; + } + } + return xmlSchema; + } - public XSSFMap getXSSFMapById(int id){ - return maps.get(id); - } + public XSSFMap getXSSFMapById(int id){ + return maps.get(id); + } - public XSSFMap getXSSFMapByName(String name){ + public XSSFMap getXSSFMapByName(String name){ - XSSFMap matchedMap = null; + XSSFMap matchedMap = null; - for(XSSFMap map :maps.values()){ - if(map.getCtMap().getName()!=null && map.getCtMap().getName().equals(name)){ - matchedMap = map; - } - } + for(XSSFMap map :maps.values()){ + if(map.getCtMap().getName()!=null && map.getCtMap().getName().equals(name)){ + matchedMap = map; + } + } - return matchedMap; - } + return matchedMap; + } - /** - * - * @return all the mappings configured in this document - */ - public Collection getAllXSSFMaps(){ - return maps.values(); - } + /** + * + * @return all the mappings configured in this document + */ + public Collection getAllXSSFMaps(){ + return maps.values(); + } - protected void writeTo(OutputStream out) throws IOException { - MapInfoDocument doc = MapInfoDocument.Factory.newInstance(); - doc.setMapInfo(mapInfo); - doc.save(out, DEFAULT_XML_OPTIONS); - } + protected void writeTo(OutputStream out) throws IOException { + MapInfoDocument doc = MapInfoDocument.Factory.newInstance(); + doc.setMapInfo(mapInfo); + doc.save(out, DEFAULT_XML_OPTIONS); + } - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - writeTo(out); - out.close(); - } + @Override + protected void commit() throws IOException { + PackagePart part = getPackagePart(); + OutputStream out = part.getOutputStream(); + writeTo(out); + out.close(); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/model/SingleXmlCells.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/model/SingleXmlCells.java index 08b63c451b..445865bcaf 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/model/SingleXmlCells.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/model/SingleXmlCells.java @@ -43,63 +43,63 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.SingleXmlCellsDocumen public class SingleXmlCells extends POIXMLDocumentPart { - private CTSingleXmlCells singleXMLCells; + private CTSingleXmlCells singleXMLCells; - public SingleXmlCells() { - super(); - singleXMLCells = CTSingleXmlCells.Factory.newInstance(); + public SingleXmlCells() { + super(); + singleXMLCells = CTSingleXmlCells.Factory.newInstance(); - } + } - /** - * @since POI 3.14-Beta1 - */ - public SingleXmlCells(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } + /** + * @since POI 3.14-Beta1 + */ + public SingleXmlCells(PackagePart part) throws IOException { + super(part); + readFrom(part.getInputStream()); + } - public void readFrom(InputStream is) throws IOException { - try { - SingleXmlCellsDocument doc = SingleXmlCellsDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - singleXMLCells = doc.getSingleXmlCells(); - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } + public void readFrom(InputStream is) throws IOException { + try { + SingleXmlCellsDocument doc = SingleXmlCellsDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); + singleXMLCells = doc.getSingleXmlCells(); + } catch (XmlException e) { + throw new IOException(e.getLocalizedMessage()); + } + } - public XSSFSheet getXSSFSheet(){ - return (XSSFSheet) getParent(); - } + public XSSFSheet getXSSFSheet(){ + return (XSSFSheet) getParent(); + } - protected void writeTo(OutputStream out) throws IOException { - SingleXmlCellsDocument doc = SingleXmlCellsDocument.Factory.newInstance(); - doc.setSingleXmlCells(singleXMLCells); - doc.save(out, DEFAULT_XML_OPTIONS); - } + protected void writeTo(OutputStream out) throws IOException { + SingleXmlCellsDocument doc = SingleXmlCellsDocument.Factory.newInstance(); + doc.setSingleXmlCells(singleXMLCells); + doc.save(out, DEFAULT_XML_OPTIONS); + } - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - writeTo(out); - out.close(); - } + @Override + protected void commit() throws IOException { + PackagePart part = getPackagePart(); + OutputStream out = part.getOutputStream(); + writeTo(out); + out.close(); + } - public CTSingleXmlCells getCTSingleXMLCells(){ - return singleXMLCells; - } + public CTSingleXmlCells getCTSingleXMLCells(){ + return singleXMLCells; + } - /** - * - * @return all the SimpleXmlCell contained in this SingleXmlCells element - */ - public List getAllSimpleXmlCell(){ - List list = new Vector<>(); + /** + * + * @return all the SimpleXmlCell contained in this SingleXmlCells element + */ + public List getAllSimpleXmlCell(){ + List list = new Vector<>(); - for(CTSingleXmlCell singleXmlCell: singleXMLCells.getSingleXmlCellArray()){ - list.add(new XSSFSingleXmlCell(singleXmlCell,this)); - } - return list; - } + for(CTSingleXmlCell singleXmlCell: singleXMLCells.getSingleXmlCellArray()){ + list.add(new XSSFSingleXmlCell(singleXmlCell,this)); + } + return list; + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/GZIPSheetDataWriter.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/GZIPSheetDataWriter.java index ce2da084e9..eff1234791 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/GZIPSheetDataWriter.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/GZIPSheetDataWriter.java @@ -39,11 +39,11 @@ public class GZIPSheetDataWriter extends SheetDataWriter { public GZIPSheetDataWriter() throws IOException { super(); } - - /** + + /** * @param sharedStringsTable the shared strings table, or null if inline text is used */ - public GZIPSheetDataWriter(SharedStringsTable sharedStringsTable) throws IOException { + public GZIPSheetDataWriter(SharedStringsTable sharedStringsTable) throws IOException { super(sharedStringsTable); } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFFormulaEvaluator.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFFormulaEvaluator.java index 574dc69dbc..ff9ae7b159 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFFormulaEvaluator.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFFormulaEvaluator.java @@ -113,8 +113,8 @@ public final class SXSSFFormulaEvaluator extends BaseXSSFFormulaEvaluator { int lastFlushedRowNum = ((SXSSFSheet) sheet).getLastFlushedRowNum(); if (lastFlushedRowNum > -1) { if (!skipOutOfWindow) { - throw new RowFlushedException(0, lastFlushedRowNum); - } + throw new RowFlushedException(0, lastFlushedRowNum); + } LOG.atInfo().log("Rows up to {} have already been flushed, skipping", box(lastFlushedRowNum)); } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFPicture.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFPicture.java index a39eb590c8..3f50a196fc 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFPicture.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFPicture.java @@ -200,7 +200,7 @@ public final class SXSSFPicture implements Picture { private float getRowHeightInPixels(int rowIndex) { // THE FOLLOWING THREE LINES ARE THE MAIN CHANGE compared to the non-streaming version: use the SXSSF sheet, - // not the XSSF sheet (which never contais rows when using SXSSF) + // not the XSSF sheet (which never contais rows when using SXSSF) XSSFSheet xssfSheet = getSheet(); SXSSFSheet sxSheet = _wb.getSXSSFSheet(xssfSheet); Sheet sheet = sxSheet == null ? xssfSheet : sxSheet; diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/TextFontAlign.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/TextFontAlign.java index 96417980c4..5832c80109 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/TextFontAlign.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/TextFontAlign.java @@ -22,10 +22,10 @@ package org.apache.poi.xssf.usermodel; * Specified a list of text font alignment types */ public enum TextFontAlign { - /** - * Automatic alignment - */ - AUTO, + /** + * Automatic alignment + */ + AUTO, /** * Align text to the top. */ diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataValidationConstraint.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataValidationConstraint.java index 396b01d05c..0aa5ec1406 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataValidationConstraint.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataValidationConstraint.java @@ -27,227 +27,227 @@ public class XSSFDataValidationConstraint implements DataValidationConstraint { /** * Excel validation constraints with static lists are delimited with optional whitespace and the Windows List Separator, * which is typically comma, but can be changed by users. POI will just assume comma. - * In addition, Excel validation with static lists has a maximum size of 255 characters, including separators and excluding quotes. + * In addition, Excel validation with static lists has a maximum size of 255 characters, including separators and excluding quotes. */ private static final String LIST_SEPARATOR = ","; private static final Pattern LIST_SPLIT_REGEX = Pattern.compile("\\s*" + LIST_SEPARATOR + "\\s*"); private static final String QUOTE = "\""; - private static final int MAX_EXPLICIT_LIST_LENGTH = 257; + private static final int MAX_EXPLICIT_LIST_LENGTH = 257; - private String formula1; - private String formula2; - private final int validationType; - private int operator = -1; - private String[] explicitListOfValues; + private String formula1; + private String formula2; + private final int validationType; + private int operator = -1; + private String[] explicitListOfValues; - /** - * list literal constructor - */ - public XSSFDataValidationConstraint(String[] explicitListOfValues) { - if( explicitListOfValues==null || explicitListOfValues.length==0) { - throw new IllegalArgumentException("List validation with explicit values must specify at least one value"); - } - this.validationType = ValidationType.LIST; - setExplicitListValues(explicitListOfValues); + /** + * list literal constructor + */ + public XSSFDataValidationConstraint(String[] explicitListOfValues) { + if( explicitListOfValues==null || explicitListOfValues.length==0) { + throw new IllegalArgumentException("List validation with explicit values must specify at least one value"); + } + this.validationType = ValidationType.LIST; + setExplicitListValues(explicitListOfValues); - validate(); - } + validate(); + } - public XSSFDataValidationConstraint(int validationType, String formula1) { - super(); - setFormula1(formula1); - this.validationType = validationType; - validate(); - } + public XSSFDataValidationConstraint(int validationType, String formula1) { + super(); + setFormula1(formula1); + this.validationType = validationType; + validate(); + } - public XSSFDataValidationConstraint(int validationType, int operator, String formula1) { - super(); - setFormula1(formula1); - this.validationType = validationType; - this.operator = operator; - validate(); - } + public XSSFDataValidationConstraint(int validationType, int operator, String formula1) { + super(); + setFormula1(formula1); + this.validationType = validationType; + this.operator = operator; + validate(); + } - /** - * This is the constructor called using the OOXML raw data. Excel overloads formula1 to also encode explicit value lists, - * so this constructor has to check for and parse that syntax. - * @param formula1 Overloaded: formula1 or list of explicit values - * @param formula2 (formula1 is a list of explicit values, this is ignored: use {@code null}) - */ - public XSSFDataValidationConstraint(int validationType, int operator, String formula1, String formula2) { - super(); - //removes leading equals sign if present - setFormula1(formula1); - setFormula2(formula2); - this.validationType = validationType; - this.operator = operator; + /** + * This is the constructor called using the OOXML raw data. Excel overloads formula1 to also encode explicit value lists, + * so this constructor has to check for and parse that syntax. + * @param formula1 Overloaded: formula1 or list of explicit values + * @param formula2 (formula1 is a list of explicit values, this is ignored: use {@code null}) + */ + public XSSFDataValidationConstraint(int validationType, int operator, String formula1, String formula2) { + super(); + //removes leading equals sign if present + setFormula1(formula1); + setFormula2(formula2); + this.validationType = validationType; + this.operator = operator; - validate(); + validate(); - //FIXME: Need to confirm if this is not a formula. - // empirical testing shows Excel saves explicit lists surrounded by double quotes, - // range formula expressions can't start with quotes (I think - anyone have a creative counter example?) - if ( ValidationType.LIST == validationType - && this.formula1 != null - && isQuoted(this.formula1) ) { - explicitListOfValues = LIST_SPLIT_REGEX.split(unquote(this.formula1)); - } - } + //FIXME: Need to confirm if this is not a formula. + // empirical testing shows Excel saves explicit lists surrounded by double quotes, + // range formula expressions can't start with quotes (I think - anyone have a creative counter example?) + if ( ValidationType.LIST == validationType + && this.formula1 != null + && isQuoted(this.formula1) ) { + explicitListOfValues = LIST_SPLIT_REGEX.split(unquote(this.formula1)); + } + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getExplicitListValues() - */ - @Override - public String[] getExplicitListValues() { - return explicitListOfValues; - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getExplicitListValues() + */ + @Override + public String[] getExplicitListValues() { + return explicitListOfValues; + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getFormula1() - */ - @Override - public String getFormula1() { - return formula1; - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getFormula1() + */ + @Override + public String getFormula1() { + return formula1; + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getFormula2() - */ - @Override - public String getFormula2() { - return formula2; - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getFormula2() + */ + @Override + public String getFormula2() { + return formula2; + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getOperator() - */ - @Override - public int getOperator() { - return operator; - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getOperator() + */ + @Override + public int getOperator() { + return operator; + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getValidationType() - */ - @Override - public int getValidationType() { - return validationType; - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getValidationType() + */ + @Override + public int getValidationType() { + return validationType; + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setExplicitListValues(java.lang.String[]) - */ - @Override - public void setExplicitListValues(String[] explicitListValues) { - this.explicitListOfValues = explicitListValues; + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setExplicitListValues(java.lang.String[]) + */ + @Override + public void setExplicitListValues(String[] explicitListValues) { + this.explicitListOfValues = explicitListValues; - // for OOXML we need to set formula1 to the quoted csv list of values (doesn't appear documented, but that's where Excel puts its lists) - // further, Excel has no escaping for commas in explicit lists, so we don't need to worry about that. - if ( explicitListOfValues!=null && explicitListOfValues.length > 0 ) { - StringBuilder builder = new StringBuilder(QUOTE); - for (String string : explicitListValues) { - if (builder.length() > 1) { - builder.append(LIST_SEPARATOR); - } - builder.append(string); - } - builder.append(QUOTE); - setFormula1(builder.toString()); - } - } + // for OOXML we need to set formula1 to the quoted csv list of values (doesn't appear documented, but that's where Excel puts its lists) + // further, Excel has no escaping for commas in explicit lists, so we don't need to worry about that. + if ( explicitListOfValues!=null && explicitListOfValues.length > 0 ) { + StringBuilder builder = new StringBuilder(QUOTE); + for (String string : explicitListValues) { + if (builder.length() > 1) { + builder.append(LIST_SEPARATOR); + } + builder.append(string); + } + builder.append(QUOTE); + setFormula1(builder.toString()); + } + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setFormula1(java.lang.String) - */ - @Override - public void setFormula1(String formula1) { - this.formula1 = removeLeadingEquals(formula1); - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setFormula1(java.lang.String) + */ + @Override + public void setFormula1(String formula1) { + this.formula1 = removeLeadingEquals(formula1); + } - protected static String removeLeadingEquals(String formula1) { - return isFormulaEmpty(formula1) ? formula1 : formula1.charAt(0)=='=' ? formula1.substring(1) : formula1; - } - private static boolean isQuoted(String s) { - return s.startsWith(QUOTE) && s.endsWith(QUOTE); - } - private static String unquote(String s) { - // removes leading and trailing quotes from a quoted string - if (isQuoted(s)) { - return s.substring(1, s.length()-1); - } - return s; - } - protected static boolean isFormulaEmpty(String formula1) { - return formula1 == null || formula1.trim().length()==0; - } + protected static String removeLeadingEquals(String formula1) { + return isFormulaEmpty(formula1) ? formula1 : formula1.charAt(0)=='=' ? formula1.substring(1) : formula1; + } + private static boolean isQuoted(String s) { + return s.startsWith(QUOTE) && s.endsWith(QUOTE); + } + private static String unquote(String s) { + // removes leading and trailing quotes from a quoted string + if (isQuoted(s)) { + return s.substring(1, s.length()-1); + } + return s; + } + protected static boolean isFormulaEmpty(String formula1) { + return formula1 == null || formula1.trim().length()==0; + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setFormula2(java.lang.String) - */ - @Override - public void setFormula2(String formula2) { - this.formula2 = removeLeadingEquals(formula2); - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setFormula2(java.lang.String) + */ + @Override + public void setFormula2(String formula2) { + this.formula2 = removeLeadingEquals(formula2); + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setOperator(int) - */ - @Override - public void setOperator(int operator) { - this.operator = operator; - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setOperator(int) + */ + @Override + public void setOperator(int operator) { + this.operator = operator; + } - public void validate() { - if (validationType==ValidationType.ANY) { - return; - } + public void validate() { + if (validationType==ValidationType.ANY) { + return; + } - if (validationType==ValidationType.LIST ) { - if (isFormulaEmpty(formula1)) { - throw new IllegalArgumentException("A valid formula or a list of values must be specified for list validation."); - } - if(formula1.length() > MAX_EXPLICIT_LIST_LENGTH) { - throw new IllegalArgumentException("A valid formula or a list of values must be less than or equal to 255 characters (including separators)."); - } - } else { - if( isFormulaEmpty(formula1) ) { - throw new IllegalArgumentException("Formula is not specified. Formula is required for all validation types except explicit list validation."); - } + if (validationType==ValidationType.LIST ) { + if (isFormulaEmpty(formula1)) { + throw new IllegalArgumentException("A valid formula or a list of values must be specified for list validation."); + } + if(formula1.length() > MAX_EXPLICIT_LIST_LENGTH) { + throw new IllegalArgumentException("A valid formula or a list of values must be less than or equal to 255 characters (including separators)."); + } + } else { + if( isFormulaEmpty(formula1) ) { + throw new IllegalArgumentException("Formula is not specified. Formula is required for all validation types except explicit list validation."); + } - if( validationType!= ValidationType.FORMULA ) { - if (operator==-1) { - throw new IllegalArgumentException("This validation type requires an operator to be specified."); - } else if (( operator==OperatorType.BETWEEN || operator==OperatorType.NOT_BETWEEN) && isFormulaEmpty(formula2)) { - throw new IllegalArgumentException("Between and not between comparisons require two formulae to be specified."); - } - } - } - } + if( validationType!= ValidationType.FORMULA ) { + if (operator==-1) { + throw new IllegalArgumentException("This validation type requires an operator to be specified."); + } else if (( operator==OperatorType.BETWEEN || operator==OperatorType.NOT_BETWEEN) && isFormulaEmpty(formula2)) { + throw new IllegalArgumentException("Between and not between comparisons require two formulae to be specified."); + } + } + } + } - public String prettyPrint() { - StringBuilder builder = new StringBuilder(); - STDataValidationType.Enum vt = XSSFDataValidation.validationTypeMappings.get(validationType); - Enum ot = XSSFDataValidation.operatorTypeMappings.get(operator); - builder.append(vt); - builder.append(' '); - if (validationType!=ValidationType.ANY) { - if (validationType != ValidationType.LIST - && validationType != ValidationType.FORMULA) { - builder.append(LIST_SEPARATOR).append(ot).append(", "); - } - final String NOQUOTE = ""; - if (validationType == ValidationType.LIST && explicitListOfValues != null) { - builder.append(NOQUOTE).append(Arrays.asList(explicitListOfValues)).append(NOQUOTE).append(' '); - } else { - builder.append(NOQUOTE).append(formula1).append(NOQUOTE).append(' '); - } - if (formula2 != null) { - builder.append(NOQUOTE).append(formula2).append(NOQUOTE).append(' '); - } - } - return builder.toString(); - } + public String prettyPrint() { + StringBuilder builder = new StringBuilder(); + STDataValidationType.Enum vt = XSSFDataValidation.validationTypeMappings.get(validationType); + Enum ot = XSSFDataValidation.operatorTypeMappings.get(operator); + builder.append(vt); + builder.append(' '); + if (validationType!=ValidationType.ANY) { + if (validationType != ValidationType.LIST + && validationType != ValidationType.FORMULA) { + builder.append(LIST_SEPARATOR).append(ot).append(", "); + } + final String NOQUOTE = ""; + if (validationType == ValidationType.LIST && explicitListOfValues != null) { + builder.append(NOQUOTE).append(Arrays.asList(explicitListOfValues)).append(NOQUOTE).append(' '); + } else { + builder.append(NOQUOTE).append(formula1).append(NOQUOTE).append(' '); + } + if (formula2 != null) { + builder.append(NOQUOTE).append(formula2).append(NOQUOTE).append(' '); + } + } + return builder.toString(); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataValidationHelper.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataValidationHelper.java index 5508411d4b..06bfb3e4f9 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataValidationHelper.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFDataValidationHelper.java @@ -31,143 +31,143 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationOpera import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationType; public class XSSFDataValidationHelper implements DataValidationHelper { - // Findbugs: URF_UNREAD_FIELD. Do not delete without understanding how this class works. - //private XSSFSheet xssfSheet; + // Findbugs: URF_UNREAD_FIELD. Do not delete without understanding how this class works. + //private XSSFSheet xssfSheet; public XSSFDataValidationHelper(XSSFSheet xssfSheet) { - super(); - // Findbugs: URF_UNREAD_FIELD. Do not delete without understanding how this class works. - //this.xssfSheet = xssfSheet; - } + super(); + // Findbugs: URF_UNREAD_FIELD. Do not delete without understanding how this class works. + //this.xssfSheet = xssfSheet; + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createDateConstraint(int, java.lang.String, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createDateConstraint(int operatorType, String formula1, String formula2, String dateFormat) { - return new XSSFDataValidationConstraint(ValidationType.DATE, operatorType,formula1, formula2); - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationHelper#createDateConstraint(int, java.lang.String, java.lang.String, java.lang.String) + */ + public DataValidationConstraint createDateConstraint(int operatorType, String formula1, String formula2, String dateFormat) { + return new XSSFDataValidationConstraint(ValidationType.DATE, operatorType,formula1, formula2); + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createDecimalConstraint(int, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createDecimalConstraint(int operatorType, String formula1, String formula2) { - return new XSSFDataValidationConstraint(ValidationType.DECIMAL, operatorType,formula1, formula2); - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationHelper#createDecimalConstraint(int, java.lang.String, java.lang.String) + */ + public DataValidationConstraint createDecimalConstraint(int operatorType, String formula1, String formula2) { + return new XSSFDataValidationConstraint(ValidationType.DECIMAL, operatorType,formula1, formula2); + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createExplicitListConstraint(java.lang.String[]) - */ - public DataValidationConstraint createExplicitListConstraint(String[] listOfValues) { - return new XSSFDataValidationConstraint(listOfValues); - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationHelper#createExplicitListConstraint(java.lang.String[]) + */ + public DataValidationConstraint createExplicitListConstraint(String[] listOfValues) { + return new XSSFDataValidationConstraint(listOfValues); + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createFormulaListConstraint(java.lang.String) - */ - public DataValidationConstraint createFormulaListConstraint(String listFormula) { - return new XSSFDataValidationConstraint(ValidationType.LIST, listFormula); - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationHelper#createFormulaListConstraint(java.lang.String) + */ + public DataValidationConstraint createFormulaListConstraint(String listFormula) { + return new XSSFDataValidationConstraint(ValidationType.LIST, listFormula); + } - public DataValidationConstraint createNumericConstraint(int validationType, int operatorType, String formula1, String formula2) { - if( validationType==ValidationType.INTEGER) { - return createIntegerConstraint(operatorType, formula1, formula2); - } else if ( validationType==ValidationType.DECIMAL) { - return createDecimalConstraint(operatorType, formula1, formula2); - } else if ( validationType==ValidationType.TEXT_LENGTH) { - return createTextLengthConstraint(operatorType, formula1, formula2); - } - return null; - } + public DataValidationConstraint createNumericConstraint(int validationType, int operatorType, String formula1, String formula2) { + if( validationType==ValidationType.INTEGER) { + return createIntegerConstraint(operatorType, formula1, formula2); + } else if ( validationType==ValidationType.DECIMAL) { + return createDecimalConstraint(operatorType, formula1, formula2); + } else if ( validationType==ValidationType.TEXT_LENGTH) { + return createTextLengthConstraint(operatorType, formula1, formula2); + } + return null; + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createIntegerConstraint(int, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createIntegerConstraint(int operatorType, String formula1, String formula2) { - return new XSSFDataValidationConstraint(ValidationType.INTEGER, operatorType,formula1,formula2); - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationHelper#createIntegerConstraint(int, java.lang.String, java.lang.String) + */ + public DataValidationConstraint createIntegerConstraint(int operatorType, String formula1, String formula2) { + return new XSSFDataValidationConstraint(ValidationType.INTEGER, operatorType,formula1,formula2); + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createTextLengthConstraint(int, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createTextLengthConstraint(int operatorType, String formula1, String formula2) { - return new XSSFDataValidationConstraint(ValidationType.TEXT_LENGTH, operatorType,formula1,formula2); - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationHelper#createTextLengthConstraint(int, java.lang.String, java.lang.String) + */ + public DataValidationConstraint createTextLengthConstraint(int operatorType, String formula1, String formula2) { + return new XSSFDataValidationConstraint(ValidationType.TEXT_LENGTH, operatorType,formula1,formula2); + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createTimeConstraint(int, java.lang.String, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createTimeConstraint(int operatorType, String formula1, String formula2) { - return new XSSFDataValidationConstraint(ValidationType.TIME, operatorType,formula1,formula2); - } + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationHelper#createTimeConstraint(int, java.lang.String, java.lang.String, java.lang.String) + */ + public DataValidationConstraint createTimeConstraint(int operatorType, String formula1, String formula2) { + return new XSSFDataValidationConstraint(ValidationType.TIME, operatorType,formula1,formula2); + } - public DataValidationConstraint createCustomConstraint(String formula) { - return new XSSFDataValidationConstraint(ValidationType.FORMULA, formula); - } + public DataValidationConstraint createCustomConstraint(String formula) { + return new XSSFDataValidationConstraint(ValidationType.FORMULA, formula); + } - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createValidation(org.apache.poi.ss.usermodel.DataValidationConstraint, org.apache.poi.ss.util.CellRangeAddressList) - */ - public DataValidation createValidation(DataValidationConstraint constraint, CellRangeAddressList cellRangeAddressList) { - XSSFDataValidationConstraint dataValidationConstraint = (XSSFDataValidationConstraint)constraint; - CTDataValidation newDataValidation = CTDataValidation.Factory.newInstance(); + /* (non-Javadoc) + * @see org.apache.poi.ss.usermodel.DataValidationHelper#createValidation(org.apache.poi.ss.usermodel.DataValidationConstraint, org.apache.poi.ss.util.CellRangeAddressList) + */ + public DataValidation createValidation(DataValidationConstraint constraint, CellRangeAddressList cellRangeAddressList) { + XSSFDataValidationConstraint dataValidationConstraint = (XSSFDataValidationConstraint)constraint; + CTDataValidation newDataValidation = CTDataValidation.Factory.newInstance(); - int validationType = constraint.getValidationType(); - switch(validationType) { - case DataValidationConstraint.ValidationType.LIST: - newDataValidation.setType(STDataValidationType.LIST); - newDataValidation.setFormula1(constraint.getFormula1()); - break; - case DataValidationConstraint.ValidationType.ANY: - newDataValidation.setType(STDataValidationType.NONE); - break; - case DataValidationConstraint.ValidationType.TEXT_LENGTH: - newDataValidation.setType(STDataValidationType.TEXT_LENGTH); - break; - case DataValidationConstraint.ValidationType.DATE: - newDataValidation.setType(STDataValidationType.DATE); - break; - case DataValidationConstraint.ValidationType.INTEGER: - newDataValidation.setType(STDataValidationType.WHOLE); - break; - case DataValidationConstraint.ValidationType.DECIMAL: - newDataValidation.setType(STDataValidationType.DECIMAL); - break; - case DataValidationConstraint.ValidationType.TIME: - newDataValidation.setType(STDataValidationType.TIME); - break; - case DataValidationConstraint.ValidationType.FORMULA: - newDataValidation.setType(STDataValidationType.CUSTOM); - break; - default: - newDataValidation.setType(STDataValidationType.NONE); - } + int validationType = constraint.getValidationType(); + switch(validationType) { + case DataValidationConstraint.ValidationType.LIST: + newDataValidation.setType(STDataValidationType.LIST); + newDataValidation.setFormula1(constraint.getFormula1()); + break; + case DataValidationConstraint.ValidationType.ANY: + newDataValidation.setType(STDataValidationType.NONE); + break; + case DataValidationConstraint.ValidationType.TEXT_LENGTH: + newDataValidation.setType(STDataValidationType.TEXT_LENGTH); + break; + case DataValidationConstraint.ValidationType.DATE: + newDataValidation.setType(STDataValidationType.DATE); + break; + case DataValidationConstraint.ValidationType.INTEGER: + newDataValidation.setType(STDataValidationType.WHOLE); + break; + case DataValidationConstraint.ValidationType.DECIMAL: + newDataValidation.setType(STDataValidationType.DECIMAL); + break; + case DataValidationConstraint.ValidationType.TIME: + newDataValidation.setType(STDataValidationType.TIME); + break; + case DataValidationConstraint.ValidationType.FORMULA: + newDataValidation.setType(STDataValidationType.CUSTOM); + break; + default: + newDataValidation.setType(STDataValidationType.NONE); + } - if (validationType!=ValidationType.ANY && validationType!=ValidationType.LIST) { + if (validationType!=ValidationType.ANY && validationType!=ValidationType.LIST) { STDataValidationOperator.Enum op = XSSFDataValidation.operatorTypeMappings.get(constraint.getOperator()); - if(op != null) { + if(op != null) { newDataValidation.setOperator(op); } - if (constraint.getFormula1() != null) { - newDataValidation.setFormula1(constraint.getFormula1()); - } - if (constraint.getFormula2() != null) { - newDataValidation.setFormula2(constraint.getFormula2()); - } - } + if (constraint.getFormula1() != null) { + newDataValidation.setFormula1(constraint.getFormula1()); + } + if (constraint.getFormula2() != null) { + newDataValidation.setFormula2(constraint.getFormula2()); + } + } - CellRangeAddress[] cellRangeAddresses = cellRangeAddressList.getCellRangeAddresses(); - List sqref = new ArrayList<>(); - for (int i = 0; i < cellRangeAddresses.length; i++) { - CellRangeAddress cellRangeAddress = cellRangeAddresses[i]; - sqref.add(cellRangeAddress.formatAsString()); - } - newDataValidation.setSqref(sqref); - newDataValidation.setAllowBlank(true); - newDataValidation.setErrorStyle(STDataValidationErrorStyle.STOP); + CellRangeAddress[] cellRangeAddresses = cellRangeAddressList.getCellRangeAddresses(); + List sqref = new ArrayList<>(); + for (int i = 0; i < cellRangeAddresses.length; i++) { + CellRangeAddress cellRangeAddress = cellRangeAddresses[i]; + sqref.add(cellRangeAddress.formatAsString()); + } + newDataValidation.setSqref(sqref); + newDataValidation.setAllowBlank(true); + newDataValidation.setErrorStyle(STDataValidationErrorStyle.STOP); - return new XSSFDataValidation(dataValidationConstraint,cellRangeAddressList,newDataValidation); - } + return new XSSFDataValidation(dataValidationConstraint,cellRangeAddressList,newDataValidation); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java index 221154b331..a8a3783a33 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java @@ -27,79 +27,79 @@ import org.apache.poi.ss.util.CellRangeAddress; */ final class XSSFEvaluationCell implements EvaluationCell { - private final EvaluationSheet _evalSheet; - private final XSSFCell _cell; + private final EvaluationSheet _evalSheet; + private final XSSFCell _cell; - public XSSFEvaluationCell(XSSFCell cell, XSSFEvaluationSheet evaluationSheet) { - _cell = cell; - _evalSheet = evaluationSheet; - } + public XSSFEvaluationCell(XSSFCell cell, XSSFEvaluationSheet evaluationSheet) { + _cell = cell; + _evalSheet = evaluationSheet; + } - public XSSFEvaluationCell(XSSFCell cell) { - this(cell, new XSSFEvaluationSheet(cell.getSheet())); - } + public XSSFEvaluationCell(XSSFCell cell) { + this(cell, new XSSFEvaluationSheet(cell.getSheet())); + } - @Override - public Object getIdentityKey() { - // save memory by just using the cell itself as the identity key - // Note - this assumes XSSFCell has not overridden hashCode and equals - return _cell; - } + @Override + public Object getIdentityKey() { + // save memory by just using the cell itself as the identity key + // Note - this assumes XSSFCell has not overridden hashCode and equals + return _cell; + } - public XSSFCell getXSSFCell() { - return _cell; - } - @Override - public boolean getBooleanCellValue() { - return _cell.getBooleanCellValue(); - } - /** - * @return cell type - */ - @Override - public CellType getCellType() { - return _cell.getCellType(); - } - @Override - public int getColumnIndex() { - return _cell.getColumnIndex(); - } - @Override - public int getErrorCellValue() { - return _cell.getErrorCellValue(); - } - @Override - public double getNumericCellValue() { - return _cell.getNumericCellValue(); - } - @Override - public int getRowIndex() { - return _cell.getRowIndex(); - } - @Override - public EvaluationSheet getSheet() { - return _evalSheet; - } - @Override - public String getStringCellValue() { - return _cell.getRichStringCellValue().getString(); - } - - @Override - public CellRangeAddress getArrayFormulaRange() { - return _cell.getArrayFormulaRange(); - } - - @Override - public boolean isPartOfArrayFormulaGroup() { - return _cell.isPartOfArrayFormulaGroup(); - } - - /** - * @return cell type of cached formula result - */ - @Override - public CellType getCachedFormulaResultType() { - return _cell.getCachedFormulaResultType(); - } + public XSSFCell getXSSFCell() { + return _cell; + } + @Override + public boolean getBooleanCellValue() { + return _cell.getBooleanCellValue(); + } + /** + * @return cell type + */ + @Override + public CellType getCellType() { + return _cell.getCellType(); + } + @Override + public int getColumnIndex() { + return _cell.getColumnIndex(); + } + @Override + public int getErrorCellValue() { + return _cell.getErrorCellValue(); + } + @Override + public double getNumericCellValue() { + return _cell.getNumericCellValue(); + } + @Override + public int getRowIndex() { + return _cell.getRowIndex(); + } + @Override + public EvaluationSheet getSheet() { + return _evalSheet; + } + @Override + public String getStringCellValue() { + return _cell.getRichStringCellValue().getString(); + } + + @Override + public CellRangeAddress getArrayFormulaRange() { + return _cell.getArrayFormulaRange(); + } + + @Override + public boolean isPartOfArrayFormulaGroup() { + return _cell.isPartOfArrayFormulaGroup(); + } + + /** + * @return cell type of cached formula result + */ + @Override + public CellType getCachedFormulaResultType() { + return _cell.getCachedFormulaResultType(); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFEvenFooter.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFEvenFooter.java index 8e27980b78..118fa793aa 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFEvenFooter.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFEvenFooter.java @@ -67,14 +67,14 @@ public class XSSFEvenFooter extends XSSFHeaderFooter implements Footer{ */ @Override public void setText(String text) { - if(text == null) { - getHeaderFooter().unsetEvenFooter(); - if (!getHeaderFooter().isSetEvenHeader()) { - getHeaderFooter().unsetDifferentOddEven(); - } - } else { - getHeaderFooter().setEvenFooter(text); - } + if(text == null) { + getHeaderFooter().unsetEvenFooter(); + if (!getHeaderFooter().isSetEvenHeader()) { + getHeaderFooter().unsetDifferentOddEven(); + } + } else { + getHeaderFooter().setEvenFooter(text); + } } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFirstFooter.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFirstFooter.java index 3ce5cd5dd9..6902066b6f 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFirstFooter.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFirstFooter.java @@ -65,13 +65,13 @@ public class XSSFFirstFooter extends XSSFHeaderFooter implements Footer{ */ @Override public void setText(String text) { - if(text == null) { - getHeaderFooter().unsetFirstFooter(); - if (!getHeaderFooter().isSetFirstHeader()) { - getHeaderFooter().unsetDifferentFirst(); - } - } else { - getHeaderFooter().setFirstFooter(text); - } + if(text == null) { + getHeaderFooter().unsetFirstFooter(); + if (!getHeaderFooter().isSetFirstHeader()) { + getHeaderFooter().unsetDifferentFirst(); + } + } else { + getHeaderFooter().setFirstFooter(text); + } } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFirstHeader.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFirstHeader.java index 9d7d69c370..a28a113523 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFirstHeader.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFFirstHeader.java @@ -63,14 +63,14 @@ public class XSSFFirstHeader extends XSSFHeaderFooter implements Header{ */ @Override public void setText(String text) { - if(text == null) { - getHeaderFooter().unsetFirstHeader(); - if (!getHeaderFooter().isSetFirstFooter()) { - getHeaderFooter().unsetDifferentFirst(); - } - } else { - getHeaderFooter().setFirstHeader(text); - } + if(text == null) { + getHeaderFooter().unsetFirstHeader(); + if (!getHeaderFooter().isSetFirstFooter()) { + getHeaderFooter().unsetDifferentFirst(); + } + } else { + getHeaderFooter().setFirstHeader(text); + } } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFGraphicFrame.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFGraphicFrame.java index 9d53abd5dc..8ba7848484 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFGraphicFrame.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFGraphicFrame.java @@ -41,21 +41,21 @@ import org.w3c.dom.NodeList; */ public final class XSSFGraphicFrame extends XSSFShape { - private static CTGraphicalObjectFrame prototype; + private static CTGraphicalObjectFrame prototype; - private final CTGraphicalObjectFrame graphicFrame; + private final CTGraphicalObjectFrame graphicFrame; - /** - * Construct a new XSSFGraphicFrame object. - * - * @param drawing the XSSFDrawing that owns this frame - * @param ctGraphicFrame the XML bean that stores this frame content - */ - protected XSSFGraphicFrame(XSSFDrawing drawing, CTGraphicalObjectFrame ctGraphicFrame) { - this.drawing = drawing; // protected field on XSSFShape - this.graphicFrame = ctGraphicFrame; - // TODO: there may be a better way to delegate this - CTGraphicalObjectData graphicData = graphicFrame.getGraphic().getGraphicData(); + /** + * Construct a new XSSFGraphicFrame object. + * + * @param drawing the XSSFDrawing that owns this frame + * @param ctGraphicFrame the XML bean that stores this frame content + */ + protected XSSFGraphicFrame(XSSFDrawing drawing, CTGraphicalObjectFrame ctGraphicFrame) { + this.drawing = drawing; // protected field on XSSFShape + this.graphicFrame = ctGraphicFrame; + // TODO: there may be a better way to delegate this + CTGraphicalObjectData graphicData = graphicFrame.getGraphic().getGraphicData(); if (graphicData != null) { NodeList nodes = graphicData.getDomNode().getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { @@ -71,134 +71,134 @@ public final class XSSFGraphicFrame extends XSSFShape { } } } - } + } - @Internal - public CTGraphicalObjectFrame getCTGraphicalObjectFrame() { - return graphicFrame; - } + @Internal + public CTGraphicalObjectFrame getCTGraphicalObjectFrame() { + return graphicFrame; + } - /** - * Initialize default structure of a new graphic frame - */ - protected static CTGraphicalObjectFrame prototype() { - if (prototype == null) { - CTGraphicalObjectFrame graphicFrame = CTGraphicalObjectFrame.Factory.newInstance(); + /** + * Initialize default structure of a new graphic frame + */ + protected static CTGraphicalObjectFrame prototype() { + if (prototype == null) { + CTGraphicalObjectFrame graphicFrame = CTGraphicalObjectFrame.Factory.newInstance(); - CTGraphicalObjectFrameNonVisual nvGraphic = graphicFrame.addNewNvGraphicFramePr(); - CTNonVisualDrawingProps props = nvGraphic.addNewCNvPr(); - props.setId(0); - props.setName("Diagramm 1"); - nvGraphic.addNewCNvGraphicFramePr(); + CTGraphicalObjectFrameNonVisual nvGraphic = graphicFrame.addNewNvGraphicFramePr(); + CTNonVisualDrawingProps props = nvGraphic.addNewCNvPr(); + props.setId(0); + props.setName("Diagramm 1"); + nvGraphic.addNewCNvGraphicFramePr(); - CTTransform2D transform = graphicFrame.addNewXfrm(); - CTPositiveSize2D extPoint = transform.addNewExt(); - CTPoint2D offPoint = transform.addNewOff(); + CTTransform2D transform = graphicFrame.addNewXfrm(); + CTPositiveSize2D extPoint = transform.addNewExt(); + CTPoint2D offPoint = transform.addNewOff(); - extPoint.setCx(0); - extPoint.setCy(0); - offPoint.setX(0); - offPoint.setY(0); + extPoint.setCx(0); + extPoint.setCy(0); + offPoint.setX(0); + offPoint.setY(0); - /* CTGraphicalObject graphic = */ graphicFrame.addNewGraphic(); + /* CTGraphicalObject graphic = */ graphicFrame.addNewGraphic(); - prototype = graphicFrame; - } - return prototype; - } + prototype = graphicFrame; + } + return prototype; + } - /** - * Sets the frame macro. - */ - public void setMacro(String macro) { - graphicFrame.setMacro(macro); - } + /** + * Sets the frame macro. + */ + public void setMacro(String macro) { + graphicFrame.setMacro(macro); + } - /** - * Sets the frame name. - */ - public void setName(String name) { - getNonVisualProperties().setName(name); - } + /** + * Sets the frame name. + */ + public void setName(String name) { + getNonVisualProperties().setName(name); + } - /** - * Returns the frame name. - * @return name of the frame - */ - public String getName() { - return getNonVisualProperties().getName(); - } + /** + * Returns the frame name. + * @return name of the frame + */ + public String getName() { + return getNonVisualProperties().getName(); + } - private CTNonVisualDrawingProps getNonVisualProperties() { - CTGraphicalObjectFrameNonVisual nvGraphic = graphicFrame.getNvGraphicFramePr(); - return nvGraphic.getCNvPr(); - } + private CTNonVisualDrawingProps getNonVisualProperties() { + CTGraphicalObjectFrameNonVisual nvGraphic = graphicFrame.getNvGraphicFramePr(); + return nvGraphic.getCNvPr(); + } - /** - * Attaches frame to an anchor. - */ - protected void setAnchor(XSSFClientAnchor anchor) { - this.anchor = anchor; - } + /** + * Attaches frame to an anchor. + */ + protected void setAnchor(XSSFClientAnchor anchor) { + this.anchor = anchor; + } - /** - * Returns the frame anchor. - * @return the XSSFClientAnchor anchor this frame is attached to - */ - @Override + /** + * Returns the frame anchor. + * @return the XSSFClientAnchor anchor this frame is attached to + */ + @Override public XSSFClientAnchor getAnchor() { - return (XSSFClientAnchor) anchor; - } + return (XSSFClientAnchor) anchor; + } - /** - * Assign a DrawingML chart to the graphic frame. - */ - protected void setChart(XSSFChart chart, String relId) { - CTGraphicalObjectData data = graphicFrame.getGraphic().addNewGraphicData(); - appendChartElement(data, relId); - chart.setGraphicFrame(this); - } + /** + * Assign a DrawingML chart to the graphic frame. + */ + protected void setChart(XSSFChart chart, String relId) { + CTGraphicalObjectData data = graphicFrame.getGraphic().addNewGraphicData(); + appendChartElement(data, relId); + chart.setGraphicFrame(this); + } - /** - * Gets the frame id. - */ - public long getId() { - return graphicFrame.getNvGraphicFramePr().getCNvPr().getId(); - } + /** + * Gets the frame id. + */ + public long getId() { + return graphicFrame.getNvGraphicFramePr().getCNvPr().getId(); + } - /** - * Sets the frame id. - */ - protected void setId(long id) { - graphicFrame.getNvGraphicFramePr().getCNvPr().setId(id); - } + /** + * Sets the frame id. + */ + protected void setId(long id) { + graphicFrame.getNvGraphicFramePr().getCNvPr().setId(id); + } - /** - * The low level code to insert {@code } tag into - * {@code }. - * - * Here is the schema (ECMA-376): - *

-	 * {@code
-	 * 
-	 *   
-	 *     
-	 *   
-	 *   
-	 * 
-	 * }
-	 * 
- */ - private void appendChartElement(CTGraphicalObjectData data, String id) { - String r_namespaceUri = STRelationshipId.type.getName().getNamespaceURI(); - String c_namespaceUri = XSSFDrawing.NAMESPACE_C; - XmlCursor cursor = data.newCursor(); - cursor.toNextToken(); - cursor.beginElement(new QName(c_namespaceUri, "chart", "c")); - cursor.insertAttributeWithValue(new QName(r_namespaceUri, "id", "r"), id); - cursor.dispose(); - data.setUri(c_namespaceUri); - } + /** + * The low level code to insert {@code } tag into + * {@code }. + * + * Here is the schema (ECMA-376): + *
+     * {@code
+     * 
+     *   
+     *     
+     *   
+     *   
+     * 
+     * }
+     * 
+ */ + private void appendChartElement(CTGraphicalObjectData data, String id) { + String r_namespaceUri = STRelationshipId.type.getName().getNamespaceURI(); + String c_namespaceUri = XSSFDrawing.NAMESPACE_C; + XmlCursor cursor = data.newCursor(); + cursor.toNextToken(); + cursor.beginElement(new QName(c_namespaceUri, "chart", "c")); + cursor.insertAttributeWithValue(new QName(r_namespaceUri, "id", "r"), id); + cursor.dispose(); + data.setUri(c_namespaceUri); + } @Override protected CTShapeProperties getShapeProperties(){ diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFHeaderFooterProperties.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFHeaderFooterProperties.java index 338d9b31f5..52df8b4c0b 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFHeaderFooterProperties.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFHeaderFooterProperties.java @@ -29,85 +29,85 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; *

*/ public class XSSFHeaderFooterProperties { - private final CTHeaderFooter headerFooter; - - /** - * Create an instance of XSSFHeaderFooterProperties from the supplied XML bean - */ - public XSSFHeaderFooterProperties(CTHeaderFooter headerFooter) { - this.headerFooter = headerFooter; - } - - /** - * Returns the underlying CTHeaderFooter xml bean - * - * @return the underlying CTHeaderFooter xml bean - */ - @Internal - public CTHeaderFooter getHeaderFooter() { - return this.headerFooter; - } + private final CTHeaderFooter headerFooter; /** - * returns alignWithMargins attribute - */ - public boolean getAlignWithMargins() { - return getHeaderFooter().isSetAlignWithMargins() && getHeaderFooter().getAlignWithMargins(); - } + * Create an instance of XSSFHeaderFooterProperties from the supplied XML bean + */ + public XSSFHeaderFooterProperties(CTHeaderFooter headerFooter) { + this.headerFooter = headerFooter; + } - /** - * returns differentFirst attribute - */ - public boolean getDifferentFirst() { - return getHeaderFooter().isSetDifferentFirst() && getHeaderFooter().getDifferentFirst(); - } + /** + * Returns the underlying CTHeaderFooter xml bean + * + * @return the underlying CTHeaderFooter xml bean + */ + @Internal + public CTHeaderFooter getHeaderFooter() { + return this.headerFooter; + } - /** - * returns differentOddEven attribute - */ - public boolean getDifferentOddEven() { - return getHeaderFooter().isSetDifferentOddEven() && getHeaderFooter().getDifferentOddEven(); - } + /** + * returns alignWithMargins attribute + */ + public boolean getAlignWithMargins() { + return getHeaderFooter().isSetAlignWithMargins() && getHeaderFooter().getAlignWithMargins(); + } - /** - * returns scaleWithDoc attribute - */ - public boolean getScaleWithDoc() { - return getHeaderFooter().isSetScaleWithDoc() && getHeaderFooter().getScaleWithDoc(); - } + /** + * returns differentFirst attribute + */ + public boolean getDifferentFirst() { + return getHeaderFooter().isSetDifferentFirst() && getHeaderFooter().getDifferentFirst(); + } - /** - * set alignWithMargins attribute - */ - public void setAlignWithMargins(boolean flag) { - getHeaderFooter().setAlignWithMargins(flag); - } + /** + * returns differentOddEven attribute + */ + public boolean getDifferentOddEven() { + return getHeaderFooter().isSetDifferentOddEven() && getHeaderFooter().getDifferentOddEven(); + } + + /** + * returns scaleWithDoc attribute + */ + public boolean getScaleWithDoc() { + return getHeaderFooter().isSetScaleWithDoc() && getHeaderFooter().getScaleWithDoc(); + } + + /** + * set alignWithMargins attribute + */ + public void setAlignWithMargins(boolean flag) { + getHeaderFooter().setAlignWithMargins(flag); + } /** * set differentFirst attribute */ - public void setDifferentFirst(boolean flag) { + public void setDifferentFirst(boolean flag) { getHeaderFooter().setDifferentFirst(flag); } /** * set differentOddEven attribute */ - public void setDifferentOddEven(boolean flag) { + public void setDifferentOddEven(boolean flag) { getHeaderFooter().setDifferentOddEven(flag); } /** * set scaleWithDoc attribute */ - public void setScaleWithDoc(boolean flag) { + public void setScaleWithDoc(boolean flag) { getHeaderFooter().setScaleWithDoc(flag); } /** * remove alignWithMargins attribute */ - public void removeAlignWithMargins() { + public void removeAlignWithMargins() { if (getHeaderFooter().isSetAlignWithMargins()) { getHeaderFooter().unsetAlignWithMargins(); } @@ -116,7 +116,7 @@ public class XSSFHeaderFooterProperties { /** * remove differentFirst attribute */ - public void removeDifferentFirst() { + public void removeDifferentFirst() { if (getHeaderFooter().isSetDifferentFirst()) { getHeaderFooter().unsetDifferentFirst(); } @@ -125,7 +125,7 @@ public class XSSFHeaderFooterProperties { /** * remove differentOddEven attribute */ - public void removeDifferentOddEven() { + public void removeDifferentOddEven() { if (getHeaderFooter().isSetDifferentOddEven()) { getHeaderFooter().unsetDifferentOddEven(); } @@ -134,7 +134,7 @@ public class XSSFHeaderFooterProperties { /** * remove scaleWithDoc attribute */ - public void removeScaleWithDoc() { + public void removeScaleWithDoc() { if (getHeaderFooter().isSetScaleWithDoc()) { getHeaderFooter().unsetScaleWithDoc(); } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFHyperlink.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFHyperlink.java index 1d13e688c5..6c5f792065 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFHyperlink.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFHyperlink.java @@ -360,7 +360,7 @@ public class XSSFHyperlink implements Hyperlink { @Override public void setLastRow(int row) { setFirstRow(row); - } + } /** * @return additional text to help the user understand more about the hyperlink diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOddFooter.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOddFooter.java index 5cacff490e..fc3541db54 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOddFooter.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOddFooter.java @@ -53,10 +53,10 @@ public class XSSFOddFooter extends XSSFHeaderFooter implements Footer{ */ @Override public void setText(String text) { - if(text == null) { - getHeaderFooter().unsetOddFooter(); - } else { - getHeaderFooter().setOddFooter(text); - } + if(text == null) { + getHeaderFooter().unsetOddFooter(); + } else { + getHeaderFooter().setOddFooter(text); + } } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOddHeader.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOddHeader.java index d4133a94cd..ca0e423765 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOddHeader.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFOddHeader.java @@ -53,10 +53,10 @@ public class XSSFOddHeader extends XSSFHeaderFooter implements Header{ */ @Override public void setText(String text) { - if(text == null) { - getHeaderFooter().unsetOddHeader(); - } else { - getHeaderFooter().setOddHeader(text); - } + if(text == null) { + getHeaderFooter().unsetOddHeader(); + } else { + getHeaderFooter().setOddHeader(text); + } } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCache.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCache.java index 2f5888976a..fd0a24f40e 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCache.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCache.java @@ -60,7 +60,7 @@ public class XSSFPivotCache extends POIXMLDocumentPart { @Beta protected void readFrom(InputStream is) throws IOException { - try { + try { XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS); //Removing root element options.setLoadReplaceDocumentElement(null); diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheDefinition.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheDefinition.java index 540494c35f..d55470c335 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheDefinition.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheDefinition.java @@ -70,7 +70,7 @@ public class XSSFPivotCacheDefinition extends POIXMLDocumentPart{ @Beta public void readFrom(InputStream is) throws IOException { - try { + try { XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS); //Removing root element options.setLoadReplaceDocumentElement(null); diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheRecords.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheRecords.java index d45f6c6a18..1172007901 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheRecords.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheRecords.java @@ -57,7 +57,7 @@ public class XSSFPivotCacheRecords extends POIXMLDocumentPart { @Beta protected void readFrom(InputStream is) throws IOException { - try { + try { XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS); //Removing root element options.setLoadReplaceDocumentElement(null); diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotTable.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotTable.java index 8ace06e95a..de45c7d9e5 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotTable.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFPivotTable.java @@ -100,7 +100,7 @@ public class XSSFPivotTable extends POIXMLDocumentPart { @Beta public void readFrom(InputStream is) throws IOException { - try { + try { XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS); //Removing root element options.setLoadReplaceDocumentElement(null); diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFSheetConditionalFormatting.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFSheetConditionalFormatting.java index 00829321f9..979250173f 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFSheetConditionalFormatting.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFSheetConditionalFormatting.java @@ -56,16 +56,16 @@ public class XSSFSheetConditionalFormatting implements SheetConditionalFormattin * TODO - formulas containing cell references are currently not parsed properly * * @param comparisonOperation - a constant value from - * {@code {@link org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator}}: + * {@code {@link org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator}}: *
    - *
  • BETWEEN
  • - *
  • NOT_BETWEEN
  • - *
  • EQUAL
  • - *
  • NOT_EQUAL
  • - *
  • GT
  • - *
  • LT
  • - *
  • GE
  • - *
  • LE
  • + *
  • BETWEEN
  • + *
  • NOT_BETWEEN
  • + *
  • EQUAL
  • + *
  • NOT_EQUAL
  • + *
  • GT
  • + *
  • LT
  • + *
  • GE
  • + *
  • LE
  • *
* * @param formula1 - formula for the valued, compared with the cell @@ -266,7 +266,7 @@ public class XSSFSheetConditionalFormatting implements SheetConditionalFormattin * gets Conditional Formatting object at a particular index * * @param index - * of the Conditional Formatting object to fetch + * of the Conditional Formatting object to fetch * @return Conditional Formatting object */ @Override diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFTextRun.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFTextRun.java index 0dfa82149e..955d4f0901 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFTextRun.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFTextRun.java @@ -111,7 +111,7 @@ public class XSSFTextRun { */ public double getFontSize(){ double scale = 1; - double size = XSSFFont.DEFAULT_FONT_SIZE; // default font size + double size = XSSFFont.DEFAULT_FONT_SIZE; // default font size CTTextNormalAutofit afit = getParentParagraph().getParentShape().getTxBody().getBodyPr().getNormAutofit(); if(afit != null) scale = (double)afit.getFontScale() / 100000; diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellAlignment.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellAlignment.java index 15837ca575..b006afc5e2 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellAlignment.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellAlignment.java @@ -192,11 +192,11 @@ public class XSSFCellAlignment { } public boolean getShrinkToFit() { - return cellAlignement.getShrinkToFit(); + return cellAlignement.getShrinkToFit(); } public void setShrinkToFit(boolean shrink) { - cellAlignement.setShrinkToFit(shrink); + cellAlignement.setShrinkToFit(shrink); } /** diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/extensions/XSSFHeaderFooter.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/extensions/XSSFHeaderFooter.java index 2872c3ff16..c56963685a 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/extensions/XSSFHeaderFooter.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/extensions/XSSFHeaderFooter.java @@ -121,124 +121,124 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; * */ public abstract class XSSFHeaderFooter implements HeaderFooter { - private final HeaderFooterHelper helper; - private final CTHeaderFooter headerFooter; + private final HeaderFooterHelper helper; + private final CTHeaderFooter headerFooter; - private boolean stripFields; + private boolean stripFields; - /** - * Create an instance of XSSFAbstractHeaderFooter from the supplied XML bean - */ - public XSSFHeaderFooter(CTHeaderFooter headerFooter) { + /** + * Create an instance of XSSFAbstractHeaderFooter from the supplied XML bean + */ + public XSSFHeaderFooter(CTHeaderFooter headerFooter) { this.headerFooter = headerFooter; - this.helper = new HeaderFooterHelper(); - } + this.helper = new HeaderFooterHelper(); + } - /** - * Returns the underlying CTHeaderFooter xml bean - * - * @return the underlying CTHeaderFooter xml bean - */ + /** + * Returns the underlying CTHeaderFooter xml bean + * + * @return the underlying CTHeaderFooter xml bean + */ @Internal - public CTHeaderFooter getHeaderFooter() { - return this.headerFooter; - } + public CTHeaderFooter getHeaderFooter() { + return this.headerFooter; + } /** * Returns the value of the header or footer. * * @return the value of the header or footer. */ - public String getValue() { - String value = getText(); - if (value == null) - return ""; - return value; - } + public String getValue() { + String value = getText(); + if (value == null) + return ""; + return value; + } - /** - * Are fields currently being stripped from the text that this - * XSSFHeaderFooter returns? Default is false, but can be changed - */ - public boolean areFieldsStripped() { - return stripFields; - } + /** + * Are fields currently being stripped from the text that this + * XSSFHeaderFooter returns? Default is false, but can be changed + */ + public boolean areFieldsStripped() { + return stripFields; + } - /** - * Should fields (eg macros) be stripped from the text that this class - * returns? Default is not to strip. - */ - public void setAreFieldsStripped(boolean stripFields) { - this.stripFields = stripFields; - } + /** + * Should fields (eg macros) be stripped from the text that this class + * returns? Default is not to strip. + */ + public void setAreFieldsStripped(boolean stripFields) { + this.stripFields = stripFields; + } - /** - * Removes any fields (eg macros, page markers etc) from the string. - * Normally used to make some text suitable for showing to humans, and the - * resultant text should not normally be saved back into the document! - */ - public static String stripFields(String text) { - return org.apache.poi.hssf.usermodel.HeaderFooter.stripFields(text); - } + /** + * Removes any fields (eg macros, page markers etc) from the string. + * Normally used to make some text suitable for showing to humans, and the + * resultant text should not normally be saved back into the document! + */ + public static String stripFields(String text) { + return org.apache.poi.hssf.usermodel.HeaderFooter.stripFields(text); + } - public abstract String getText(); + public abstract String getText(); - protected abstract void setText(String text); + protected abstract void setText(String text); - /** - * get the text representing the center part of this element - */ - @Override - public String getCenter() { - String text = helper.getCenterSection(getText()); - if (stripFields) - return stripFields(text); - return text; - } + /** + * get the text representing the center part of this element + */ + @Override + public String getCenter() { + String text = helper.getCenterSection(getText()); + if (stripFields) + return stripFields(text); + return text; + } - /** - * get the text representing the left part of this element - */ - @Override - public String getLeft() { - String text = helper.getLeftSection(getText()); - if (stripFields) - return stripFields(text); - return text; - } + /** + * get the text representing the left part of this element + */ + @Override + public String getLeft() { + String text = helper.getLeftSection(getText()); + if (stripFields) + return stripFields(text); + return text; + } - /** - * get the text representing the right part of this element - */ - @Override - public String getRight() { - String text = helper.getRightSection(getText()); - if (stripFields) - return stripFields(text); - return text; - } + /** + * get the text representing the right part of this element + */ + @Override + public String getRight() { + String text = helper.getRightSection(getText()); + if (stripFields) + return stripFields(text); + return text; + } - /** - * set a centered string value for this element - */ - @Override - public void setCenter(String newCenter) { - setText(helper.setCenterSection(getText(), newCenter)); - } + /** + * set a centered string value for this element + */ + @Override + public void setCenter(String newCenter) { + setText(helper.setCenterSection(getText(), newCenter)); + } - /** - * set a left string value for this element - */ - @Override - public void setLeft(String newLeft) { - setText(helper.setLeftSection(getText(), newLeft)); - } + /** + * set a left string value for this element + */ + @Override + public void setLeft(String newLeft) { + setText(helper.setLeftSection(getText(), newLeft)); + } - /** - * set a right string value for this element - */ - @Override - public void setRight(String newRight) { - setText(helper.setRightSection(getText(), newRight)); - } + /** + * set a right string value for this element + */ + @Override + public void setRight(String newRight) { + setText(helper.setRightSection(getText(), newRight)); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java index e4731dae11..5e3c4ee024 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java @@ -20,7 +20,7 @@ package org.apache.poi.xssf.usermodel.helpers; public class HeaderFooterHelper { // Note - XmlBeans handles entity encoding for us, - // so these should be & forms, not the & ones! + // so these should be & forms, not the & ones! private static final String HeaderFooterEntity_L = "&L"; private static final String HeaderFooterEntity_C = "&C"; private static final String HeaderFooterEntity_R = "&R"; @@ -32,28 +32,28 @@ public class HeaderFooterHelper { public static final String HeaderFooterEntity_Time = "&T"; public String getLeftSection(String string) { - return getParts(string)[0]; + return getParts(string)[0]; } public String getCenterSection(String string) { - return getParts(string)[1]; + return getParts(string)[1]; } public String getRightSection(String string) { - return getParts(string)[2]; + return getParts(string)[2]; } public String setLeftSection(String string, String newLeft) { - String[] parts = getParts(string); - parts[0] = newLeft; + String[] parts = getParts(string); + parts[0] = newLeft; return joinParts(parts); } public String setCenterSection(String string, String newCenter) { - String[] parts = getParts(string); - parts[1] = newCenter; + String[] parts = getParts(string); + parts[1] = newCenter; return joinParts(parts); } public String setRightSection(String string, String newRight) { - String[] parts = getParts(string); - parts[2] = newRight; + String[] parts = getParts(string); + parts[2] = newRight; return joinParts(parts); } @@ -61,59 +61,59 @@ public class HeaderFooterHelper { * Split into left, center, right */ private String[] getParts(String string) { - String[] parts = new String[] { "", "", "" }; - if(string == null) - return parts; - - // They can come in any order, which is just nasty - // Work backwards from the end, picking the last - // on off each time as we go - int lAt = 0; - int cAt = 0; - int rAt = 0; - - while( - // Ensure all indicies get updated, then -1 tested - (lAt = string.indexOf(HeaderFooterEntity_L)) > -2 && - (cAt = string.indexOf(HeaderFooterEntity_C)) > -2 && - (rAt = string.indexOf(HeaderFooterEntity_R)) > -2 && - (lAt > -1 || cAt > -1 || rAt > -1) - ) { - // Pick off the last one - if(rAt > cAt && rAt > lAt) { - parts[2] = string.substring(rAt + HeaderFooterEntity_R.length()); - string = string.substring(0, rAt); - } else if(cAt > rAt && cAt > lAt) { - parts[1] = string.substring(cAt + HeaderFooterEntity_C.length()); - string = string.substring(0, cAt); - } else { - parts[0] = string.substring(lAt + HeaderFooterEntity_L.length()); - string = string.substring(0, lAt); - } - } - - return parts; + String[] parts = new String[] { "", "", "" }; + if(string == null) + return parts; + + // They can come in any order, which is just nasty + // Work backwards from the end, picking the last + // on off each time as we go + int lAt = 0; + int cAt = 0; + int rAt = 0; + + while( + // Ensure all indicies get updated, then -1 tested + (lAt = string.indexOf(HeaderFooterEntity_L)) > -2 && + (cAt = string.indexOf(HeaderFooterEntity_C)) > -2 && + (rAt = string.indexOf(HeaderFooterEntity_R)) > -2 && + (lAt > -1 || cAt > -1 || rAt > -1) + ) { + // Pick off the last one + if(rAt > cAt && rAt > lAt) { + parts[2] = string.substring(rAt + HeaderFooterEntity_R.length()); + string = string.substring(0, rAt); + } else if(cAt > rAt && cAt > lAt) { + parts[1] = string.substring(cAt + HeaderFooterEntity_C.length()); + string = string.substring(0, cAt); + } else { + parts[0] = string.substring(lAt + HeaderFooterEntity_L.length()); + string = string.substring(0, lAt); + } + } + + return parts; } private String joinParts(String[] parts) { - return joinParts(parts[0], parts[1], parts[2]); + return joinParts(parts[0], parts[1], parts[2]); } private String joinParts(String l, String c, String r) { - StringBuilder ret = new StringBuilder(64); + StringBuilder ret = new StringBuilder(64); - // Join as c, l, r - if(c.length() > 0) { - ret.append(HeaderFooterEntity_C); - ret.append(c); - } - if(l.length() > 0) { - ret.append(HeaderFooterEntity_L); - ret.append(l); - } - if(r.length() > 0) { - ret.append(HeaderFooterEntity_R); - ret.append(r); - } - - return ret.toString(); + // Join as c, l, r + if(c.length() > 0) { + ret.append(HeaderFooterEntity_C); + ret.append(c); + } + if(l.length() > 0) { + ret.append(HeaderFooterEntity_L); + ret.append(l); + } + if(r.length() > 0) { + ret.append(HeaderFooterEntity_R); + ret.append(r); + } + + return ret.toString(); } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/XSSFSingleXmlCell.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/XSSFSingleXmlCell.java index 5fea3505db..98c4c8c297 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/XSSFSingleXmlCell.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/XSSFSingleXmlCell.java @@ -32,53 +32,53 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXmlPr; */ public class XSSFSingleXmlCell { - private CTSingleXmlCell singleXmlCell; - private SingleXmlCells parent; + private CTSingleXmlCell singleXmlCell; + private SingleXmlCells parent; - public XSSFSingleXmlCell(CTSingleXmlCell singleXmlCell, SingleXmlCells parent){ - this.singleXmlCell = singleXmlCell; - this.parent = parent; - } + public XSSFSingleXmlCell(CTSingleXmlCell singleXmlCell, SingleXmlCells parent){ + this.singleXmlCell = singleXmlCell; + this.parent = parent; + } - /** - * Gets the XSSFCell referenced by the R attribute or creates a new one if cell doesn't exists - * @return the referenced XSSFCell, null if the cell reference is invalid - */ - public XSSFCell getReferencedCell(){ - XSSFCell cell = null; + /** + * Gets the XSSFCell referenced by the R attribute or creates a new one if cell doesn't exists + * @return the referenced XSSFCell, null if the cell reference is invalid + */ + public XSSFCell getReferencedCell(){ + XSSFCell cell = null; - CellReference cellReference = new CellReference(singleXmlCell.getR()); + CellReference cellReference = new CellReference(singleXmlCell.getR()); - XSSFRow row = parent.getXSSFSheet().getRow(cellReference.getRow()); - if(row==null){ - row = parent.getXSSFSheet().createRow(cellReference.getRow()); - } + XSSFRow row = parent.getXSSFSheet().getRow(cellReference.getRow()); + if(row==null){ + row = parent.getXSSFSheet().createRow(cellReference.getRow()); + } - cell = row.getCell(cellReference.getCol()); - if(cell==null){ - cell = row.createCell(cellReference.getCol()); - } + cell = row.getCell(cellReference.getCol()); + if(cell==null){ + cell = row.createCell(cellReference.getCol()); + } - return cell; - } + return cell; + } - public String getXpath(){ - CTXmlCellPr xmlCellPr = singleXmlCell.getXmlCellPr(); - CTXmlPr xmlPr = xmlCellPr.getXmlPr(); + public String getXpath(){ + CTXmlCellPr xmlCellPr = singleXmlCell.getXmlCellPr(); + CTXmlPr xmlPr = xmlCellPr.getXmlPr(); return xmlPr.getXpath(); - } + } - public long getMapId(){ - return singleXmlCell.getXmlCellPr().getXmlPr().getMapId(); - } + public long getMapId(){ + return singleXmlCell.getXmlCellPr().getXmlPr().getMapId(); + } - public String getXmlDataType() { - CTXmlCellPr xmlCellPr = singleXmlCell.getXmlCellPr(); - CTXmlPr xmlPr = xmlCellPr.getXmlPr(); - return xmlPr.getXmlDataType(); - } + public String getXmlDataType() { + CTXmlCellPr xmlCellPr = singleXmlCell.getXmlCellPr(); + CTXmlPr xmlPr = xmlCellPr.getXmlPr(); + return xmlPr.getXmlDataType(); + } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xwpf/model/XWPFHeaderFooterPolicy.java b/poi-ooxml/src/main/java/org/apache/poi/xwpf/model/XWPFHeaderFooterPolicy.java index 3c956be237..f45728f0af 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xwpf/model/XWPFHeaderFooterPolicy.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xwpf/model/XWPFHeaderFooterPolicy.java @@ -241,14 +241,14 @@ public class XWPFHeaderFooterPolicy { } private CTHdrFtr buildFtr(Enum type, XWPFHeaderFooter wrapper, XWPFParagraph[] pars) { - //CTHdrFtr ftr = buildHdrFtr(pStyle, pars); // MB 24 May 2010 + //CTHdrFtr ftr = buildHdrFtr(pStyle, pars); // MB 24 May 2010 CTHdrFtr ftr = buildHdrFtr(pars, wrapper); // MB 24 May 2010 setFooterReference(type, wrapper); return ftr; } private CTHdrFtr buildHdr(Enum type, XWPFHeaderFooter wrapper, XWPFParagraph[] pars) { - //CTHdrFtr hdr = buildHdrFtr(pStyle, pars); // MB 24 May 2010 + //CTHdrFtr hdr = buildHdrFtr(pStyle, pars); // MB 24 May 2010 CTHdrFtr hdr = buildHdrFtr(pars, wrapper); // MB 24 May 2010 setHeaderReference(type, wrapper); return hdr; diff --git a/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFSettings.java b/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFSettings.java index 072a48a091..d0ee95fb35 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFSettings.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFSettings.java @@ -109,7 +109,7 @@ public class XWPFSettings extends POIXMLDocumentPart { zoom.setPercent(BigInteger.valueOf(zoomPercent)); } - /** + /** * Verifies the documentProtection tag inside settings.xml file
* if the protection is enforced (w:enforcement="1")
*

@@ -122,7 +122,7 @@ public class XWPFSettings extends POIXMLDocumentPart { * * @return true if documentProtection is enforced with option any */ - public boolean isEnforcedWith() { + public boolean isEnforcedWith() { CTDocProtect ctDocProtect = ctSettings.getDocumentProtection(); return ctDocProtect != null && POIXMLUnits.parseOnOff(ctDocProtect.xgetEnforcement()); diff --git a/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestDetectAsOOXML.java b/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestDetectAsOOXML.java index 13e46c5222..6d3708c139 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestDetectAsOOXML.java +++ b/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestDetectAsOOXML.java @@ -42,30 +42,30 @@ import org.junit.jupiter.params.provider.CsvSource; @SuppressWarnings("deprecation") class TestDetectAsOOXML { @Test - void testOpensProperly() throws IOException, InvalidFormatException { - try (InputStream is = openSampleFileStream("sample.xlsx"); - OPCPackage pkg = OPCPackage.open(is)) { - assertNotNull(pkg); - } - } + void testOpensProperly() throws IOException, InvalidFormatException { + try (InputStream is = openSampleFileStream("sample.xlsx"); + OPCPackage pkg = OPCPackage.open(is)) { + assertNotNull(pkg); + } + } @ParameterizedTest - @CsvSource({"SampleSS.xlsx, OOXML", "SampleSS.xls, OLE2", "SampleSS.txt, UNKNOWN"}) - void testDetectAsPOIFS(String file, FileMagic fm) throws IOException { - try (InputStream is = FileMagic.prepareToCheckMagic(openSampleFileStream(file))) { - FileMagic act = FileMagic.valueOf(is); + @CsvSource({"SampleSS.xlsx, OOXML", "SampleSS.xls, OLE2", "SampleSS.txt, UNKNOWN"}) + void testDetectAsPOIFS(String file, FileMagic fm) throws IOException { + try (InputStream is = FileMagic.prepareToCheckMagic(openSampleFileStream(file))) { + FileMagic act = FileMagic.valueOf(is); - assertEquals(act == FileMagic.OOXML, DocumentFactoryHelper.hasOOXMLHeader(is), - "OOXML files should be detected, others not"); + assertEquals(act == FileMagic.OOXML, DocumentFactoryHelper.hasOOXMLHeader(is), + "OOXML files should be detected, others not"); - assertEquals(fm, act, "file magic failed for " + file); - } - } + assertEquals(fm, act, "file magic failed for " + file); + } + } @Test void testFileCorruption() throws Exception { - // create test InputStream - byte[] testData = { 1, 2, 3 }; + // create test InputStream + byte[] testData = { 1, 2, 3 }; ByteArrayInputStream testInput = new ByteArrayInputStream(testData); InputStream is = FileMagic.prepareToCheckMagic(testInput); @@ -77,5 +77,5 @@ class TestDetectAsOOXML { assertArrayEquals(testData, act); assertEquals(-1, is.read()); is.close(); - } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestEmbedded.java b/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestEmbedded.java index e41193a3c8..86b925f784 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestEmbedded.java +++ b/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestEmbedded.java @@ -36,42 +36,42 @@ import org.junit.jupiter.api.Test; * Class to test that we handle embeded bits in OOXML files properly */ class TestEmbedded { - @Test - void testExcel() throws Exception { - POIXMLDocument doc = new XSSFWorkbook( + @Test + void testExcel() throws Exception { + POIXMLDocument doc = new XSSFWorkbook( POIDataSamples.getSpreadSheetInstance().openResourceAsStream("ExcelWithAttachments.xlsm") ); - test(doc, 4); - } + test(doc, 4); + } - @Test - void testWord() throws Exception { - POIXMLDocument doc = new XWPFDocument( + @Test + void testWord() throws Exception { + POIXMLDocument doc = new XWPFDocument( POIDataSamples.getDocumentInstance().openResourceAsStream("WordWithAttachments.docx") ); - test(doc, 5); - } + test(doc, 5); + } - @Test - void testPowerPoint() throws Exception { - POIXMLDocument doc = new XSLFSlideShow(OPCPackage.open( + @Test + void testPowerPoint() throws Exception { + POIXMLDocument doc = new XSLFSlideShow(OPCPackage.open( POIDataSamples.getSlideShowInstance().openResourceAsStream("PPTWithAttachments.pptm")) ); - test(doc, 4); - } + test(doc, 4); + } - private void test(POIXMLDocument doc, int expectedCount) throws Exception { - assertNotNull(doc.getAllEmbeddedParts()); - assertEquals(expectedCount, doc.getAllEmbeddedParts().size()); + private void test(POIXMLDocument doc, int expectedCount) throws Exception { + assertNotNull(doc.getAllEmbeddedParts()); + assertEquals(expectedCount, doc.getAllEmbeddedParts().size()); - for(int i=0; i 0); - } + byte[] b = IOUtils.toByteArray(pp.getInputStream()); + assertTrue(b.length > 0); + } - doc.close(); - } + doc.close(); + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestXMLPropertiesTextExtractor.java b/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestXMLPropertiesTextExtractor.java index c077e15085..501b61f8a6 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestXMLPropertiesTextExtractor.java +++ b/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestXMLPropertiesTextExtractor.java @@ -34,74 +34,74 @@ public final class TestXMLPropertiesTextExtractor { private static final POIDataSamples _ssSamples = POIDataSamples.getSpreadSheetInstance(); private static final POIDataSamples _slSamples = POIDataSamples.getSlideShowInstance(); - @Test - void testGetFromMainExtractor() throws Exception { - OPCPackage pkg = PackageHelper.open(_ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm")); + @Test + void testGetFromMainExtractor() throws Exception { + OPCPackage pkg = PackageHelper.open(_ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm")); - XSSFWorkbook wb = new XSSFWorkbook(pkg); + XSSFWorkbook wb = new XSSFWorkbook(pkg); - XSSFExcelExtractor ext = new XSSFExcelExtractor(wb); - POIXMLPropertiesTextExtractor textExt = ext.getMetadataTextExtractor(); + XSSFExcelExtractor ext = new XSSFExcelExtractor(wb); + POIXMLPropertiesTextExtractor textExt = ext.getMetadataTextExtractor(); - // Check basics - assertNotNull(textExt); - assertTrue(textExt.getText().length() > 0); + // Check basics + assertNotNull(textExt); + assertTrue(textExt.getText().length() > 0); - // Check some of the content - String text = textExt.getText(); - String cText = textExt.getCorePropertiesText(); + // Check some of the content + String text = textExt.getText(); + String cText = textExt.getCorePropertiesText(); - assertContains(text, "LastModifiedBy = Yury Batrakov"); - assertContains(cText, "LastModifiedBy = Yury Batrakov"); + assertContains(text, "LastModifiedBy = Yury Batrakov"); + assertContains(cText, "LastModifiedBy = Yury Batrakov"); - textExt.close(); - ext.close(); - } + textExt.close(); + ext.close(); + } - @Test - void testCore() throws Exception { - OPCPackage pkg = PackageHelper.open( + @Test + void testCore() throws Exception { + OPCPackage pkg = PackageHelper.open( _ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm") - ); - XSSFWorkbook wb = new XSSFWorkbook(pkg); + ); + XSSFWorkbook wb = new XSSFWorkbook(pkg); - POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(wb); - ext.getText(); + POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(wb); + ext.getText(); - // Now check - String text = ext.getText(); - String cText = ext.getCorePropertiesText(); + // Now check + String text = ext.getText(); + String cText = ext.getCorePropertiesText(); - assertContains(text, "LastModifiedBy = Yury Batrakov"); - assertContains(cText, "LastModifiedBy = Yury Batrakov"); + assertContains(text, "LastModifiedBy = Yury Batrakov"); + assertContains(cText, "LastModifiedBy = Yury Batrakov"); - ext.close(); - } + ext.close(); + } - @Test - void testExtended() throws Exception { - OPCPackage pkg = OPCPackage.open( + @Test + void testExtended() throws Exception { + OPCPackage pkg = OPCPackage.open( _ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm") - ); - XSSFWorkbook wb = new XSSFWorkbook(pkg); + ); + XSSFWorkbook wb = new XSSFWorkbook(pkg); - POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(wb); - ext.getText(); + POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(wb); + ext.getText(); - // Now check - String text = ext.getText(); - String eText = ext.getExtendedPropertiesText(); + // Now check + String text = ext.getText(); + String eText = ext.getExtendedPropertiesText(); - assertContains(text, "Application = Microsoft Excel"); - assertContains(text, "Company = Mera"); - assertContains(eText, "Application = Microsoft Excel"); - assertContains(eText, "Company = Mera"); + assertContains(text, "Application = Microsoft Excel"); + assertContains(text, "Company = Mera"); + assertContains(eText, "Application = Microsoft Excel"); + assertContains(eText, "Company = Mera"); - ext.close(); - } + ext.close(); + } - @Test - void testCustom() throws Exception { + @Test + void testCustom() throws Exception { OPCPackage pkg = OPCPackage.open( _ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm") ); @@ -118,14 +118,14 @@ public final class TestXMLPropertiesTextExtractor { assertContains(cText, "description = another value"); ext.close(); - } + } - /** - * Bug #49386 - some properties, especially - * dates can be null - */ - @Test - void testWithSomeNulls() throws Exception { + /** + * Bug #49386 - some properties, especially + * dates can be null + */ + @Test + void testWithSomeNulls() throws Exception { OPCPackage pkg = OPCPackage.open( _slSamples.openResourceAsStream("49386-null_dates.pptx") ); @@ -140,5 +140,5 @@ public final class TestXMLPropertiesTextExtractor { assertContains(text, "LastModifiedBy = IT Client Services"); ext.close(); - } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java index 4068a8e80d..b118b907ba 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java @@ -30,23 +30,23 @@ import java.io.IOException; public final class OpenXML4JTestDataSamples { private static final POIDataSamples _samples = POIDataSamples.getOpenXML4JInstance(); - private OpenXML4JTestDataSamples() { - // no instances of this class - } + private OpenXML4JTestDataSamples() { + // no instances of this class + } - public static InputStream openSampleStream(String sampleFileName) { - return _samples.openResourceAsStream(sampleFileName); - } - public static String getSampleFileName(String sampleFileName) { - return getSampleFile(sampleFileName).getAbsolutePath(); - } + public static InputStream openSampleStream(String sampleFileName) { + return _samples.openResourceAsStream(sampleFileName); + } + public static String getSampleFileName(String sampleFileName) { + return getSampleFile(sampleFileName).getAbsolutePath(); + } - public static File getSampleFile(String sampleFileName) { - return _samples.getFile(sampleFileName); - } + public static File getSampleFile(String sampleFileName) { + return _samples.getFile(sampleFileName); + } - public static File getOutputFile(String outputFileName) throws IOException { - int idx = outputFileName.lastIndexOf('.'); + public static File getOutputFile(String outputFileName) throws IOException { + int idx = outputFileName.lastIndexOf('.'); return TempFile.createTempFile(outputFileName.substring(0,idx), outputFileName.substring(idx)); - } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestFileHelper.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestFileHelper.java index c1998ca132..df6b364131 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestFileHelper.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestFileHelper.java @@ -30,27 +30,27 @@ import org.junit.jupiter.api.Test; */ public final class TestFileHelper { - /** - * TODO - use simple JDK methods on {@link File} instead:
- * {@link File#getParentFile()} instead of {@link FileHelper#getDirectory(File) - * {@link File#getName()} instead of {@link FileHelper#getFilename(File) - */ + /** + * TODO - use simple JDK methods on {@link File} instead:
+ * {@link File#getParentFile()} instead of {@link FileHelper#getDirectory(File) + * {@link File#getName()} instead of {@link FileHelper#getFilename(File) + */ @Test - void testGetDirectory() { - TreeMap expectedValue = new TreeMap<>(); - expectedValue.put("/dir1/test.doc", "/dir1"); - expectedValue.put("/dir1/dir2/test.doc.xml", "/dir1/dir2"); + void testGetDirectory() { + TreeMap expectedValue = new TreeMap<>(); + expectedValue.put("/dir1/test.doc", "/dir1"); + expectedValue.put("/dir1/dir2/test.doc.xml", "/dir1/dir2"); - for (String filename : expectedValue.keySet()) { - File f1 = new File(expectedValue.get(filename)); - File f2 = FileHelper.getDirectory(new File(filename)); + for (String filename : expectedValue.keySet()) { + File f1 = new File(expectedValue.get(filename)); + File f2 = FileHelper.getDirectory(new File(filename)); -// if (false) { -// // YK: The original version asserted expected values against File#getAbsolutePath(): -// assertTrue(expectedValue.get(filename).equalsIgnoreCase(f2.getAbsolutePath())); -// // This comparison is platform dependent. A better approach is below -// } - assertEquals(f1, f2); - } - } +// if (false) { +// // YK: The original version asserted expected values against File#getAbsolutePath(): +// assertTrue(expectedValue.get(filename).equalsIgnoreCase(f2.getAbsolutePath())); +// // This comparison is platform dependent. A better approach is below +// } + assertEquals(f1, f2); + } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestListParts.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestListParts.java index 481ce98620..a41d01971b 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestListParts.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestListParts.java @@ -34,71 +34,71 @@ import org.junit.jupiter.api.Test; public final class TestListParts { private static final Logger LOG = LogManager.getLogger(TestListParts.class); - private TreeMap expectedValues; + private TreeMap expectedValues; - private TreeMap values; + private TreeMap values; - @BeforeEach - void setUp() throws Exception { - values = new TreeMap<>(); + @BeforeEach + void setUp() throws Exception { + values = new TreeMap<>(); - // Expected values - expectedValues = new TreeMap<>(); - expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"), - "application/vnd.openxmlformats-package.relationships+xml"); + // Expected values + expectedValues = new TreeMap<>(); + expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"), + "application/vnd.openxmlformats-package.relationships+xml"); - expectedValues - .put(PackagingURIHelper.createPartName("/docProps/app.xml"), - "application/vnd.openxmlformats-officedocument.extended-properties+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/docProps/core.xml"), - "application/vnd.openxmlformats-package.core-properties+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/word/_rels/document.xml.rels"), - "application/vnd.openxmlformats-package.relationships+xml"); - expectedValues - .put( - PackagingURIHelper.createPartName("/word/document.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/fontTable.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/word/media/image1.gif"), "image/gif"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/settings.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/styles.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/word/theme/theme1.xml"), - "application/vnd.openxmlformats-officedocument.theme+xml"); - expectedValues - .put( - PackagingURIHelper - .createPartName("/word/webSettings.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"); - } + expectedValues + .put(PackagingURIHelper.createPartName("/docProps/app.xml"), + "application/vnd.openxmlformats-officedocument.extended-properties+xml"); + expectedValues.put(PackagingURIHelper + .createPartName("/docProps/core.xml"), + "application/vnd.openxmlformats-package.core-properties+xml"); + expectedValues.put(PackagingURIHelper + .createPartName("/word/_rels/document.xml.rels"), + "application/vnd.openxmlformats-package.relationships+xml"); + expectedValues + .put( + PackagingURIHelper.createPartName("/word/document.xml"), + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"); + expectedValues + .put(PackagingURIHelper.createPartName("/word/fontTable.xml"), + "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"); + expectedValues.put(PackagingURIHelper + .createPartName("/word/media/image1.gif"), "image/gif"); + expectedValues + .put(PackagingURIHelper.createPartName("/word/settings.xml"), + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"); + expectedValues + .put(PackagingURIHelper.createPartName("/word/styles.xml"), + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"); + expectedValues.put(PackagingURIHelper + .createPartName("/word/theme/theme1.xml"), + "application/vnd.openxmlformats-officedocument.theme+xml"); + expectedValues + .put( + PackagingURIHelper + .createPartName("/word/webSettings.xml"), + "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"); + } - /** - * List all parts of a package. - */ - @Test - void testListParts() throws InvalidFormatException, IOException { - try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.docx"); - OPCPackage p = OPCPackage.open(is)) { + /** + * List all parts of a package. + */ + @Test + void testListParts() throws InvalidFormatException, IOException { + try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.docx"); + OPCPackage p = OPCPackage.open(is)) { - for (PackagePart part : p.getParts()) { - values.put(part.getPartName(), part.getContentType()); - LOG.atDebug().log(part.getPartName()); - } + for (PackagePart part : p.getParts()) { + values.put(part.getPartName(), part.getContentType()); + LOG.atDebug().log(part.getPartName()); + } - // Compare expected values with values return by the package - for (PackagePartName partName : expectedValues.keySet()) { - assertNotNull(values.get(partName)); - assertEquals(expectedValues.get(partName), values.get(partName)); - } - } - } + // Compare expected values with values return by the package + for (PackagePartName partName : expectedValues.keySet()) { + assertNotNull(values.get(partName)); + assertEquals(expectedValues.get(partName), values.get(partName)); + } + } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java index 9e9997d38f..65bdc4bcbf 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java @@ -100,87 +100,87 @@ import org.xml.sax.SAXParseException; public final class TestPackage { private static final Logger LOG = LogManager.getLogger(TestPackage.class); - private static final String NS_OOXML_WP_MAIN = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; - private static final String CONTENT_EXT_PROPS = "application/vnd.openxmlformats-officedocument.extended-properties+xml"; - private static final POIDataSamples xlsSamples = POIDataSamples.getSpreadSheetInstance(); + private static final String NS_OOXML_WP_MAIN = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private static final String CONTENT_EXT_PROPS = "application/vnd.openxmlformats-officedocument.extended-properties+xml"; + private static final POIDataSamples xlsSamples = POIDataSamples.getSpreadSheetInstance(); - @Test - void isStrictOoxmlFormat() throws IOException, InvalidFormatException { - try (OPCPackage p = OPCPackage.open(getSampleFileName("TestPackageCommon.docx"), PackageAccess.READ)) { - assertFalse(p.isStrictOoxmlFormat()); - } - try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("sample.xlsx"), PackageAccess.READ)) { - assertFalse(p.isStrictOoxmlFormat()); - } - try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("sample.strict.xlsx"), PackageAccess.READ)) { - assertTrue(p.isStrictOoxmlFormat()); - } - } - - - /** - * Test that just opening and closing the file doesn't alter the document. - */ @Test - void openSave() throws IOException, InvalidFormatException { - String originalFile = getSampleFileName("TestPackageCommon.docx"); - File targetFile = getOutputFile("TestPackageOpenSaveTMP.docx"); + void isStrictOoxmlFormat() throws IOException, InvalidFormatException { + try (OPCPackage p = OPCPackage.open(getSampleFileName("TestPackageCommon.docx"), PackageAccess.READ)) { + assertFalse(p.isStrictOoxmlFormat()); + } + try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("sample.xlsx"), PackageAccess.READ)) { + assertFalse(p.isStrictOoxmlFormat()); + } + try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("sample.strict.xlsx"), PackageAccess.READ)) { + assertTrue(p.isStrictOoxmlFormat()); + } + } + + + /** + * Test that just opening and closing the file doesn't alter the document. + */ + @Test + void openSave() throws IOException, InvalidFormatException { + String originalFile = getSampleFileName("TestPackageCommon.docx"); + File targetFile = getOutputFile("TestPackageOpenSaveTMP.docx"); try (OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE)) { - try { - p.save(targetFile.getAbsoluteFile()); + try { + p.save(targetFile.getAbsoluteFile()); - // Compare the original and newly saved document - assertTrue(targetFile.exists()); - ZipFileAssert.assertEquals(new File(originalFile), targetFile); - assertTrue(targetFile.delete()); - } finally { - // use revert to not re-write the input file - p.revert(); - } - } - } + // Compare the original and newly saved document + assertTrue(targetFile.exists()); + ZipFileAssert.assertEquals(new File(originalFile), targetFile); + assertTrue(targetFile.delete()); + } finally { + // use revert to not re-write the input file + p.revert(); + } + } + } - /** - * Test that when we create a new Package, we give it - * the correct default content types - */ + /** + * Test that when we create a new Package, we give it + * the correct default content types + */ @Test - void createGetsContentTypes() + void createGetsContentTypes() throws IOException, InvalidFormatException, SecurityException, IllegalArgumentException { - File targetFile = getOutputFile("TestCreatePackageTMP.docx"); - - // Zap the target file, in case of an earlier run - if(targetFile.exists()) { - assertTrue(targetFile.delete()); - } - - try (OPCPackage pkg = OPCPackage.create(targetFile)) { - try { - // Check it has content types for rels and xml - ContentTypeManager ctm = getContentTypeManager(pkg); - assertEquals("application/xml", ctm.getContentType(createPartName("/foo.xml"))); - assertEquals(ContentTypes.RELATIONSHIPS_PART, ctm.getContentType(createPartName("/foo.rels"))); - assertNull(ctm.getContentType(createPartName("/foo.txt"))); - } finally { - pkg.revert(); - } - } - } - - /** - * Test package creation. - */ - @Test - void createPackageAddPart() throws IOException, InvalidFormatException { - File targetFile = getOutputFile("TestCreatePackageTMP.docx"); - - File expectedFile = getSampleFile("TestCreatePackageOUTPUT.docx"); + File targetFile = getOutputFile("TestCreatePackageTMP.docx"); // Zap the target file, in case of an earlier run if(targetFile.exists()) { - assertTrue(targetFile.delete()); - } + assertTrue(targetFile.delete()); + } + + try (OPCPackage pkg = OPCPackage.create(targetFile)) { + try { + // Check it has content types for rels and xml + ContentTypeManager ctm = getContentTypeManager(pkg); + assertEquals("application/xml", ctm.getContentType(createPartName("/foo.xml"))); + assertEquals(ContentTypes.RELATIONSHIPS_PART, ctm.getContentType(createPartName("/foo.rels"))); + assertNull(ctm.getContentType(createPartName("/foo.txt"))); + } finally { + pkg.revert(); + } + } + } + + /** + * Test package creation. + */ + @Test + void createPackageAddPart() throws IOException, InvalidFormatException { + File targetFile = getOutputFile("TestCreatePackageTMP.docx"); + + File expectedFile = getSampleFile("TestCreatePackageOUTPUT.docx"); + + // Zap the target file, in case of an earlier run + if(targetFile.exists()) { + assertTrue(targetFile.delete()); + } // Create a package OPCPackage pkg = OPCPackage.create(targetFile); @@ -209,81 +209,81 @@ public final class TestPackage { ZipFileAssert.assertEquals(expectedFile, targetFile); assertTrue(targetFile.delete()); - } + } - /** - * Tests that we can create a new package, add a core - * document and another part, save and re-load and - * have everything setup as expected - */ + /** + * Tests that we can create a new package, add a core + * document and another part, save and re-load and + * have everything setup as expected + */ @Test - void createPackageWithCoreDocument() throws IOException, InvalidFormatException, URISyntaxException, SAXException { - UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); - try (OPCPackage pkg = OPCPackage.create(baos)) { + void createPackageWithCoreDocument() throws IOException, InvalidFormatException, URISyntaxException, SAXException { + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); + try (OPCPackage pkg = OPCPackage.create(baos)) { - // Add a core document - PackagePartName corePartName = createPartName("/xl/workbook.xml"); - // Create main part relationship - pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); - // Create main document part - PackagePart corePart = pkg.createPart(corePartName, XSSFRelation.WORKBOOK.getContentType()); - // Put in some dummy content - try (OutputStream coreOut = corePart.getOutputStream()) { - coreOut.write("".getBytes(StandardCharsets.UTF_8)); - } + // Add a core document + PackagePartName corePartName = createPartName("/xl/workbook.xml"); + // Create main part relationship + pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); + // Create main document part + PackagePart corePart = pkg.createPart(corePartName, XSSFRelation.WORKBOOK.getContentType()); + // Put in some dummy content + try (OutputStream coreOut = corePart.getOutputStream()) { + coreOut.write("".getBytes(StandardCharsets.UTF_8)); + } - // And another bit - PackagePartName sheetPartName = createPartName("/xl/worksheets/sheet1.xml"); - PackageRelationship rel = corePart.addRelationship( - sheetPartName, TargetMode.INTERNAL, XSSFRelation.WORKSHEET.getRelation(), "rSheet1"); - assertNotNull(rel); + // And another bit + PackagePartName sheetPartName = createPartName("/xl/worksheets/sheet1.xml"); + PackageRelationship rel = corePart.addRelationship( + sheetPartName, TargetMode.INTERNAL, XSSFRelation.WORKSHEET.getRelation(), "rSheet1"); + assertNotNull(rel); - PackagePart part = pkg.createPart(sheetPartName, XSSFRelation.WORKSHEET.getContentType()); - assertNotNull(part); + PackagePart part = pkg.createPart(sheetPartName, XSSFRelation.WORKSHEET.getContentType()); + assertNotNull(part); - // Dummy content again - try (OutputStream coreOut = corePart.getOutputStream()) { - coreOut.write("".getBytes(StandardCharsets.UTF_8)); - } + // Dummy content again + try (OutputStream coreOut = corePart.getOutputStream()) { + coreOut.write("".getBytes(StandardCharsets.UTF_8)); + } - //add a relationship with internal target: "#Sheet1!A1" - corePart.addRelationship(new URI("#Sheet1!A1"), TargetMode.INTERNAL, PackageRelationshipTypes.HYPERLINK_PART, "rId2"); + //add a relationship with internal target: "#Sheet1!A1" + corePart.addRelationship(new URI("#Sheet1!A1"), TargetMode.INTERNAL, PackageRelationshipTypes.HYPERLINK_PART, "rId2"); - // Check things are as expected - PackageRelationshipCollection coreRels = - pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); - assertEquals(1, coreRels.size()); - PackageRelationship coreRel = coreRels.getRelationship(0); - assertNotNull(coreRel); - assertEquals("/", coreRel.getSourceURI().toString()); - assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString()); - assertNotNull(pkg.getPart(coreRel)); - } + // Check things are as expected + PackageRelationshipCollection coreRels = + pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); + assertEquals(1, coreRels.size()); + PackageRelationship coreRel = coreRels.getRelationship(0); + assertNotNull(coreRel); + assertEquals("/", coreRel.getSourceURI().toString()); + assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString()); + assertNotNull(pkg.getPart(coreRel)); + } - // Save and re-load + // Save and re-load File tmp = TempFile.createTempFile("testCreatePackageWithCoreDocument", ".zip"); - try (OutputStream fout = new FileOutputStream(tmp)) { - baos.writeTo(fout); - fout.flush(); - } + try (OutputStream fout = new FileOutputStream(tmp)) { + baos.writeTo(fout); + fout.flush(); + } try (OPCPackage pkg = OPCPackage.open(tmp.getPath())) { // Check still right - PackageRelationshipCollection coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); + PackageRelationshipCollection coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); assertEquals(1, coreRels.size()); - PackageRelationship coreRel = coreRels.getRelationship(0); + PackageRelationship coreRel = coreRels.getRelationship(0); - assertNotNull(coreRel); + assertNotNull(coreRel); assertEquals("/", coreRel.getSourceURI().toString()); assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString()); - PackagePart corePart = pkg.getPart(coreRel); + PackagePart corePart = pkg.getPart(coreRel); assertNotNull(corePart); PackageRelationshipCollection rels = corePart.getRelationshipsByType(PackageRelationshipTypes.HYPERLINK_PART); assertEquals(1, rels.size()); - PackageRelationship rel = rels.getRelationship(0); - assertNotNull(rel); + PackageRelationship rel = rels.getRelationship(0); + assertNotNull(rel); assertEquals("Sheet1!A1", rel.getTargetURI().getRawFragment()); assertMSCompatibility(pkg); @@ -308,37 +308,37 @@ public final class TestPackage { } /** - * Test package opening. - */ + * Test package opening. + */ @Test - void openPackage() throws IOException, InvalidFormatException { - File targetFile = getOutputFile("TestOpenPackageTMP.docx"); + void openPackage() throws IOException, InvalidFormatException { + File targetFile = getOutputFile("TestOpenPackageTMP.docx"); - File inputFile = getSampleFile("TestOpenPackageINPUT.docx"); + File inputFile = getSampleFile("TestOpenPackageINPUT.docx"); - File expectedFile = getSampleFile("TestOpenPackageOUTPUT.docx"); + File expectedFile = getSampleFile("TestOpenPackageOUTPUT.docx"); - // Copy the input file in the output directory - FileHelper.copyFile(inputFile, targetFile); + // Copy the input file in the output directory + FileHelper.copyFile(inputFile, targetFile); - // Create a package - OPCPackage pkg = OPCPackage.open(targetFile.getAbsolutePath()); + // Create a package + OPCPackage pkg = OPCPackage.open(targetFile.getAbsolutePath()); - // Modify core part - PackagePartName corePartName = createPartName("/word/document.xml"); + // Modify core part + PackagePartName corePartName = createPartName("/word/document.xml"); - PackagePart corePart = pkg.getPart(corePartName); + PackagePart corePart = pkg.getPart(corePartName); - // Delete some part to have a valid document - for (PackageRelationship rel : corePart.getRelationships()) { - corePart.removeRelationship(rel.getId()); - pkg.removePart(createPartName(PackagingURIHelper - .resolvePartUri(corePart.getPartName().getURI(), rel - .getTargetURI()))); - } + // Delete some part to have a valid document + for (PackageRelationship rel : corePart.getRelationships()) { + corePart.removeRelationship(rel.getId()); + pkg.removePart(createPartName(PackagingURIHelper + .resolvePartUri(corePart.getPartName().getURI(), rel + .getTargetURI()))); + } - // Create a content - Document doc = DocumentHelper.createDocument(); + // Create a content + Document doc = DocumentHelper.createDocument(); Element elDocument = doc.createElementNS(NS_OOXML_WP_MAIN, "w:document"); doc.appendChild(elDocument); Element elBody = doc.createElementNS(NS_OOXML_WP_MAIN, "w:body"); @@ -351,198 +351,198 @@ public final class TestPackage { elRun.appendChild(elText); elText.setTextContent("Hello Open XML !"); - StreamHelper.saveXmlInStream(doc, corePart.getOutputStream()); + StreamHelper.saveXmlInStream(doc, corePart.getOutputStream()); - // Save and close - assertDoesNotThrow(pkg::close); + // Save and close + assertDoesNotThrow(pkg::close); - ZipFileAssert.assertEquals(expectedFile, targetFile); - assertTrue(targetFile.delete()); - } + ZipFileAssert.assertEquals(expectedFile, targetFile); + assertTrue(targetFile.delete()); + } - /** - * Checks that we can write a package to a simple - * OutputStream, in addition to the normal writing - * to a file - */ + /** + * Checks that we can write a package to a simple + * OutputStream, in addition to the normal writing + * to a file + */ @Test - void saveToOutputStream() throws IOException, InvalidFormatException { - String originalFile = getSampleFileName("TestPackageCommon.docx"); - File targetFile = getOutputFile("TestPackageOpenSaveTMP.docx"); + void saveToOutputStream() throws IOException, InvalidFormatException { + String originalFile = getSampleFileName("TestPackageCommon.docx"); + File targetFile = getOutputFile("TestPackageOpenSaveTMP.docx"); - try (OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE)) { - try { - try (FileOutputStream fout = new FileOutputStream(targetFile)) { - p.save(fout); - } + try (OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE)) { + try { + try (FileOutputStream fout = new FileOutputStream(targetFile)) { + p.save(fout); + } - // Compare the original and newly saved document - assertTrue(targetFile.exists()); - ZipFileAssert.assertEquals(new File(originalFile), targetFile); - assertTrue(targetFile.delete()); - } finally { - // use revert to not re-write the input file - p.revert(); - } - } - } + // Compare the original and newly saved document + assertTrue(targetFile.exists()); + ZipFileAssert.assertEquals(new File(originalFile), targetFile); + assertTrue(targetFile.delete()); + } finally { + // use revert to not re-write the input file + p.revert(); + } + } + } - /** - * Checks that we can open+read a package from a - * simple InputStream, in addition to the normal - * reading from a file - */ + /** + * Checks that we can open+read a package from a + * simple InputStream, in addition to the normal + * reading from a file + */ @Test - void openFromInputStream() throws IOException, InvalidFormatException { - String originalFile = getSampleFileName("TestPackageCommon.docx"); + void openFromInputStream() throws IOException, InvalidFormatException { + String originalFile = getSampleFileName("TestPackageCommon.docx"); - try (FileInputStream finp = new FileInputStream(originalFile); - OPCPackage p = OPCPackage.open(finp)) { - try { - assertNotNull(p); - assertNotNull(p.getRelationships()); - assertEquals(12, p.getParts().size()); + try (FileInputStream finp = new FileInputStream(originalFile); + OPCPackage p = OPCPackage.open(finp)) { + try { + assertNotNull(p); + assertNotNull(p.getRelationships()); + assertEquals(12, p.getParts().size()); - // Check it has the usual bits - assertTrue(p.hasRelationships()); - assertTrue(p.containPart(createPartName("/_rels/.rels"))); - } finally { - p.revert(); - } - } - } + // Check it has the usual bits + assertTrue(p.hasRelationships()); + assertTrue(p.containPart(createPartName("/_rels/.rels"))); + } finally { + p.revert(); + } + } + } /** * TODO: fix and enable */ @Test - @Disabled + @Disabled void removePartRecursive() throws IOException, InvalidFormatException, URISyntaxException { - String originalFile = getSampleFileName("TestPackageCommon.docx"); - File targetFile = getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx"); - File tempFile = getOutputFile("TestPackageRemovePartRecursiveTMP.docx"); + String originalFile = getSampleFileName("TestPackageCommon.docx"); + File targetFile = getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx"); + File tempFile = getOutputFile("TestPackageRemovePartRecursiveTMP.docx"); - try (OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE)) { - p.removePartRecursive(createPartName(new URI("/word/document.xml"))); - p.save(tempFile.getAbsoluteFile()); + try (OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE)) { + p.removePartRecursive(createPartName(new URI("/word/document.xml"))); + p.save(tempFile.getAbsoluteFile()); - // Compare the original and newly saved document - assertTrue(targetFile.exists()); - ZipFileAssert.assertEquals(targetFile, tempFile); - assertTrue(targetFile.delete()); - p.revert(); - } - } + // Compare the original and newly saved document + assertTrue(targetFile.exists()); + ZipFileAssert.assertEquals(targetFile, tempFile); + assertTrue(targetFile.delete()); + p.revert(); + } + } @Test - void deletePart() throws InvalidFormatException, IOException { - final TreeMap expectedValues = new TreeMap<>(); - final TreeMap values = new TreeMap<>(); + void deletePart() throws InvalidFormatException, IOException { + final TreeMap expectedValues = new TreeMap<>(); + final TreeMap values = new TreeMap<>(); - // Expected values - expectedValues.put(createPartName("/_rels/.rels"), ContentTypes.RELATIONSHIPS_PART); - expectedValues.put(createPartName("/docProps/app.xml"), CONTENT_EXT_PROPS); - expectedValues.put(createPartName("/docProps/core.xml"), ContentTypes.CORE_PROPERTIES_PART); - expectedValues.put(createPartName("/word/fontTable.xml"), XWPFRelation.FONT_TABLE.getContentType()); - expectedValues.put(createPartName("/word/media/image1.gif"), XWPFRelation.IMAGE_GIF.getContentType()); - expectedValues.put(createPartName("/word/settings.xml"), XWPFRelation.SETTINGS.getContentType()); - expectedValues.put(createPartName("/word/styles.xml"), XWPFRelation.STYLES.getContentType()); - expectedValues.put(createPartName("/word/theme/theme1.xml"), XWPFRelation.THEME.getContentType()); - expectedValues.put(createPartName("/word/webSettings.xml"), XWPFRelation.WEB_SETTINGS.getContentType()); + // Expected values + expectedValues.put(createPartName("/_rels/.rels"), ContentTypes.RELATIONSHIPS_PART); + expectedValues.put(createPartName("/docProps/app.xml"), CONTENT_EXT_PROPS); + expectedValues.put(createPartName("/docProps/core.xml"), ContentTypes.CORE_PROPERTIES_PART); + expectedValues.put(createPartName("/word/fontTable.xml"), XWPFRelation.FONT_TABLE.getContentType()); + expectedValues.put(createPartName("/word/media/image1.gif"), XWPFRelation.IMAGE_GIF.getContentType()); + expectedValues.put(createPartName("/word/settings.xml"), XWPFRelation.SETTINGS.getContentType()); + expectedValues.put(createPartName("/word/styles.xml"), XWPFRelation.STYLES.getContentType()); + expectedValues.put(createPartName("/word/theme/theme1.xml"), XWPFRelation.THEME.getContentType()); + expectedValues.put(createPartName("/word/webSettings.xml"), XWPFRelation.WEB_SETTINGS.getContentType()); - String filepath = getSampleFileName("sample.docx"); + String filepath = getSampleFileName("sample.docx"); try (OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE)) { - try { - // Remove the core part - p.deletePart(createPartName("/word/document.xml")); + try { + // Remove the core part + p.deletePart(createPartName("/word/document.xml")); - for (PackagePart part : p.getParts()) { - values.put(part.getPartName(), part.getContentType()); - LOG.atDebug().log(part.getPartName()); - } + for (PackagePart part : p.getParts()) { + values.put(part.getPartName(), part.getContentType()); + LOG.atDebug().log(part.getPartName()); + } - // Compare expected values with values return by the package - for (PackagePartName partName : expectedValues.keySet()) { - assertNotNull(values.get(partName)); - assertEquals(expectedValues.get(partName), values.get(partName)); - } - } finally { - // Don't save modifications - p.revert(); - } - } - } + // Compare expected values with values return by the package + for (PackagePartName partName : expectedValues.keySet()) { + assertNotNull(values.get(partName)); + assertEquals(expectedValues.get(partName), values.get(partName)); + } + } finally { + // Don't save modifications + p.revert(); + } + } + } @Test - void deletePartRecursive() throws InvalidFormatException, IOException { - final TreeMap expectedValues = new TreeMap<>(); - final TreeMap values = new TreeMap<>(); + void deletePartRecursive() throws InvalidFormatException, IOException { + final TreeMap expectedValues = new TreeMap<>(); + final TreeMap values = new TreeMap<>(); - // Expected values - expectedValues.put(createPartName("/_rels/.rels"), ContentTypes.RELATIONSHIPS_PART); - expectedValues.put(createPartName("/docProps/app.xml"), CONTENT_EXT_PROPS); - expectedValues.put(createPartName("/docProps/core.xml"), ContentTypes.CORE_PROPERTIES_PART); + // Expected values + expectedValues.put(createPartName("/_rels/.rels"), ContentTypes.RELATIONSHIPS_PART); + expectedValues.put(createPartName("/docProps/app.xml"), CONTENT_EXT_PROPS); + expectedValues.put(createPartName("/docProps/core.xml"), ContentTypes.CORE_PROPERTIES_PART); - String filepath = getSampleFileName("sample.docx"); + String filepath = getSampleFileName("sample.docx"); try (OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE)) { - try { - // Remove the core part - p.deletePartRecursive(createPartName("/word/document.xml")); + try { + // Remove the core part + p.deletePartRecursive(createPartName("/word/document.xml")); - for (PackagePart part : p.getParts()) { - values.put(part.getPartName(), part.getContentType()); - LOG.atDebug().log(part.getPartName()); - } + for (PackagePart part : p.getParts()) { + values.put(part.getPartName(), part.getContentType()); + LOG.atDebug().log(part.getPartName()); + } - // Compare expected values with values return by the package - for (PackagePartName partName : expectedValues.keySet()) { - assertNotNull(values.get(partName)); - assertEquals(expectedValues.get(partName), values.get(partName)); - } - } finally { - // Don't save modifications - p.revert(); - } - } - } + // Compare expected values with values return by the package + for (PackagePartName partName : expectedValues.keySet()) { + assertNotNull(values.get(partName)); + assertEquals(expectedValues.get(partName), values.get(partName)); + } + } finally { + // Don't save modifications + p.revert(); + } + } + } - /** - * Test that we can open a file by path, and then - * write changes to it. - */ + /** + * Test that we can open a file by path, and then + * write changes to it. + */ @Test - void openFileThenOverwrite() throws IOException, InvalidFormatException { + void openFileThenOverwrite() throws IOException, InvalidFormatException { File tempFile = TempFile.createTempFile("poiTesting","tmp"); File origFile = getSampleFile("TestPackageCommon.docx"); FileHelper.copyFile(origFile, tempFile); // Open and close the temp file try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE)) { - assertNotNull(p); - } + assertNotNull(p); + } // Delete it assertTrue(tempFile.delete()); // Reset FileHelper.copyFile(origFile, tempFile); - try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE)) { - // Save it to the same file - not allowed - assertThrows(InvalidOperationException.class, () -> p.save(tempFile), - "You shouldn't be able to call save(File) to overwrite the current file"); - } + try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE)) { + // Save it to the same file - not allowed + assertThrows(InvalidOperationException.class, () -> p.save(tempFile), + "You shouldn't be able to call save(File) to overwrite the current file"); + } // Delete it assertTrue(tempFile.delete()); // Open it read only, then close and delete - allowed FileHelper.copyFile(origFile, tempFile); - try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ)) { - assertNotNull(p); - } + try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ)) { + assertNotNull(p); + } assertTrue(tempFile.delete()); - } + } /** * Test that we can open a file by path, save it @@ -556,315 +556,315 @@ public final class TestPackage { FileHelper.copyFile(origFile, tempFile); // Open the temp file - try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE)) { - // Save it to a different file - p.save(tempFile2); - } + try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE)) { + // Save it to a different file + p.save(tempFile2); + } // Delete both the files assertTrue(tempFile.delete()); assertTrue(tempFile2.delete()); } - private static ContentTypeManager getContentTypeManager(OPCPackage pkg) { - return POITestCase.getFieldValue(OPCPackage.class, pkg, ContentTypeManager.class, "contentTypeManager"); - } + private static ContentTypeManager getContentTypeManager(OPCPackage pkg) { + return POITestCase.getFieldValue(OPCPackage.class, pkg, ContentTypeManager.class, "contentTypeManager"); + } @Test void getPartsByName() throws InvalidFormatException, IOException { String filepath = getSampleFileName("sample.docx"); try (OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE)) { - try { - List rs = pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml")); - HashMap selected = new HashMap<>(); + try { + List rs = pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml")); + HashMap selected = new HashMap<>(); - for (PackagePart p : rs) - selected.put(p.getPartName().getName(), p); + for (PackagePart p : rs) + selected.put(p.getPartName().getName(), p); - assertEquals(6, selected.size()); - assertTrue(selected.containsKey("/word/document.xml")); - assertTrue(selected.containsKey("/word/fontTable.xml")); - assertTrue(selected.containsKey("/word/settings.xml")); - assertTrue(selected.containsKey("/word/styles.xml")); - assertTrue(selected.containsKey("/word/theme/theme1.xml")); - assertTrue(selected.containsKey("/word/webSettings.xml")); - } finally { - // use revert to not re-write the input file - pkg.revert(); - } - } + assertEquals(6, selected.size()); + assertTrue(selected.containsKey("/word/document.xml")); + assertTrue(selected.containsKey("/word/fontTable.xml")); + assertTrue(selected.containsKey("/word/settings.xml")); + assertTrue(selected.containsKey("/word/styles.xml")); + assertTrue(selected.containsKey("/word/theme/theme1.xml")); + assertTrue(selected.containsKey("/word/webSettings.xml")); + } finally { + // use revert to not re-write the input file + pkg.revert(); + } + } } @Test void getPartSize() throws IOException, InvalidFormatException { String filepath = getSampleFileName("sample.docx"); - try (OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ)) { - int checked = 0; - for (PackagePart part : pkg.getParts()) { - // Can get the size of zip parts - if (part.getPartName().getName().equals("/word/document.xml")) { - checked++; - assertEquals(ZipPackagePart.class, part.getClass()); - assertEquals(6031L, part.getSize()); - } - if (part.getPartName().getName().equals("/word/fontTable.xml")) { - checked++; - assertEquals(ZipPackagePart.class, part.getClass()); - assertEquals(1312L, part.getSize()); - } + try (OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ)) { + int checked = 0; + for (PackagePart part : pkg.getParts()) { + // Can get the size of zip parts + if (part.getPartName().getName().equals("/word/document.xml")) { + checked++; + assertEquals(ZipPackagePart.class, part.getClass()); + assertEquals(6031L, part.getSize()); + } + if (part.getPartName().getName().equals("/word/fontTable.xml")) { + checked++; + assertEquals(ZipPackagePart.class, part.getClass()); + assertEquals(1312L, part.getSize()); + } - // But not from the others - if (part.getPartName().getName().equals("/docProps/core.xml")) { - checked++; - assertEquals(PackagePropertiesPart.class, part.getClass()); - assertEquals(-1, part.getSize()); - } - } - // Ensure we actually found the parts we want to check - assertEquals(3, checked); - } + // But not from the others + if (part.getPartName().getName().equals("/docProps/core.xml")) { + checked++; + assertEquals(PackagePropertiesPart.class, part.getClass()); + assertEquals(-1, part.getSize()); + } + } + // Ensure we actually found the parts we want to check + assertEquals(3, checked); + } } @Test void replaceContentType() throws IOException, InvalidFormatException { try (InputStream is = openSampleStream("sample.xlsx"); - OPCPackage p = OPCPackage.open(is)) { - try { - ContentTypeManager mgr = getContentTypeManager(p); + OPCPackage p = OPCPackage.open(is)) { + try { + ContentTypeManager mgr = getContentTypeManager(p); - assertTrue(mgr.isContentTypeRegister(XSSFRelation.WORKBOOK.getContentType())); - assertFalse(mgr.isContentTypeRegister(XSSFRelation.MACROS_WORKBOOK.getContentType())); - assertTrue(p.replaceContentType(XSSFRelation.WORKBOOK.getContentType(), XSSFRelation.MACROS_WORKBOOK.getContentType())); + assertTrue(mgr.isContentTypeRegister(XSSFRelation.WORKBOOK.getContentType())); + assertFalse(mgr.isContentTypeRegister(XSSFRelation.MACROS_WORKBOOK.getContentType())); + assertTrue(p.replaceContentType(XSSFRelation.WORKBOOK.getContentType(), XSSFRelation.MACROS_WORKBOOK.getContentType())); - assertFalse(mgr.isContentTypeRegister(XSSFRelation.WORKBOOK.getContentType())); - assertTrue(mgr.isContentTypeRegister(XSSFRelation.MACROS_WORKBOOK.getContentType())); - } finally { - p.revert(); - } - } + assertFalse(mgr.isContentTypeRegister(XSSFRelation.WORKBOOK.getContentType())); + assertTrue(mgr.isContentTypeRegister(XSSFRelation.MACROS_WORKBOOK.getContentType())); + } finally { + p.revert(); + } + } } - @SuppressWarnings("unchecked") - @ParameterizedTest - @CsvSource({ - "SampleSS.xls, org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException, The supplied data appears to be in the OLE2 Format, You are calling the part of POI that deals with OOXML", - "SampleSS.xml, org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException, The supplied data appears to be a raw XML file, Formats such as Office 2003 XML", - "SampleSS.ods, org.apache.poi.openxml4j.exceptions.ODFNotOfficeXmlFileException, The supplied data appears to be in ODF, Formats like these (eg ODS", - "SampleSS.txt, org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException, No valid entries or contents found, not a valid OOXML" - }) - void NonOOXML_File(String file, String exClazzStr, String msg1, String msg2) throws Exception { - Class exClazz = (Class)Class.forName(exClazzStr); + @SuppressWarnings("unchecked") + @ParameterizedTest + @CsvSource({ + "SampleSS.xls, org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException, The supplied data appears to be in the OLE2 Format, You are calling the part of POI that deals with OOXML", + "SampleSS.xml, org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException, The supplied data appears to be a raw XML file, Formats such as Office 2003 XML", + "SampleSS.ods, org.apache.poi.openxml4j.exceptions.ODFNotOfficeXmlFileException, The supplied data appears to be in ODF, Formats like these (eg ODS", + "SampleSS.txt, org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException, No valid entries or contents found, not a valid OOXML" + }) + void NonOOXML_File(String file, String exClazzStr, String msg1, String msg2) throws Exception { + Class exClazz = (Class)Class.forName(exClazzStr); - try (InputStream stream = xlsSamples.openResourceAsStream(file)) { - Executable[] trs = { - () -> OPCPackage.open(stream), - () -> OPCPackage.open(xlsSamples.getFile(file)) - }; - for (Executable tr : trs) { - Exception ex = assertThrows(exClazz, tr, "Shouldn't be able to open "+file); - Stream.of(msg1, msg2).forEach(mp -> assertTrue(ex.getMessage().contains(mp))); - } - } - } + try (InputStream stream = xlsSamples.openResourceAsStream(file)) { + Executable[] trs = { + () -> OPCPackage.open(stream), + () -> OPCPackage.open(xlsSamples.getFile(file)) + }; + for (Executable tr : trs) { + Exception ex = assertThrows(exClazz, tr, "Shouldn't be able to open "+file); + Stream.of(msg1, msg2).forEach(mp -> assertTrue(ex.getMessage().contains(mp))); + } + } + } - /** - * Zip bomb handling test - * - * see bug #50090 / #56865 - */ + /** + * Zip bomb handling test + * + * see bug #50090 / #56865 + */ @Test void zipBombCreateAndHandle() throws IOException, EncryptedDocumentException { - UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(2500000); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(2500000); try (ZipFile zipFile = ZipHelper.openZipFile(getSampleFile("sample.xlsx")); - ZipArchiveOutputStream append = new ZipArchiveOutputStream(bos)) { - assertNotNull(zipFile); + ZipArchiveOutputStream append = new ZipArchiveOutputStream(bos)) { + assertNotNull(zipFile); - // first, copy contents from existing war - Enumeration entries = zipFile.getEntries(); - while (entries.hasMoreElements()) { - final ZipArchiveEntry eIn = entries.nextElement(); - final ZipArchiveEntry eOut = new ZipArchiveEntry(eIn.getName()); - eOut.setTime(eIn.getTime()); - eOut.setComment(eIn.getComment()); - eOut.setSize(eIn.getSize()); + // first, copy contents from existing war + Enumeration entries = zipFile.getEntries(); + while (entries.hasMoreElements()) { + final ZipArchiveEntry eIn = entries.nextElement(); + final ZipArchiveEntry eOut = new ZipArchiveEntry(eIn.getName()); + eOut.setTime(eIn.getTime()); + eOut.setComment(eIn.getComment()); + eOut.setSize(eIn.getSize()); - append.putArchiveEntry(eOut); - if (!eOut.isDirectory()) { - try (InputStream is = zipFile.getInputStream(eIn)) { - if ("[Content_Types].xml".equals(eOut.getName())) { - byte[] suffix = "".getBytes(StandardCharsets.UTF_8); - CountingOutputStream cos = new CountingOutputStream(append); - IOUtils.copy(is, cos, eOut.getSize() - suffix.length); + append.putArchiveEntry(eOut); + if (!eOut.isDirectory()) { + try (InputStream is = zipFile.getInputStream(eIn)) { + if ("[Content_Types].xml".equals(eOut.getName())) { + byte[] suffix = "".getBytes(StandardCharsets.UTF_8); + CountingOutputStream cos = new CountingOutputStream(append); + IOUtils.copy(is, cos, eOut.getSize() - suffix.length); byte[] spam = new byte[0x7FFF]; - Arrays.fill(spam, (byte) ' '); - // 0x7FFF0000 is the maximum for 32-bit zips, but less still works - while (cos.getByteCount() < 0x7FFF00) { - cos.write(spam); - } - cos.write(suffix); - eOut.setSize(cos.getByteCount()); - } else { - IOUtils.copy(is, append); - } - } - } - append.closeArchiveEntry(); - } - } + Arrays.fill(spam, (byte) ' '); + // 0x7FFF0000 is the maximum for 32-bit zips, but less still works + while (cos.getByteCount() < 0x7FFF00) { + cos.write(spam); + } + cos.write(suffix); + eOut.setSize(cos.getByteCount()); + } else { + IOUtils.copy(is, append); + } + } + } + append.closeArchiveEntry(); + } + } - IOException ex = assertThrows(IOException.class, () -> WorkbookFactory.create(bos.toInputStream())); + IOException ex = assertThrows(IOException.class, () -> WorkbookFactory.create(bos.toInputStream())); assertTrue(ex.getMessage().contains("Zip bomb detected!")); } - @Test - void testZipEntityExpansionTerminates() { - IllegalStateException ex = assertThrows( - IllegalStateException.class, - () -> openXmlBombFile("poc-shared-strings.xlsx") - ); - assertTrue(ex.getMessage().contains("The text would exceed the max allowed overall size of extracted text.")); - } + @Test + void testZipEntityExpansionTerminates() { + IllegalStateException ex = assertThrows( + IllegalStateException.class, + () -> openXmlBombFile("poc-shared-strings.xlsx") + ); + assertTrue(ex.getMessage().contains("The text would exceed the max allowed overall size of extracted text.")); + } - @Test - void testZipEntityExpansionSharedStringTableEvents() { - boolean before = ExtractorFactory.getThreadPrefersEventExtractors(); - ExtractorFactory.setThreadPrefersEventExtractors(true); - try { - IllegalStateException ex = assertThrows( - IllegalStateException.class, - () -> openXmlBombFile("poc-shared-strings.xlsx") - ); - assertTrue(ex.getMessage().contains("The text would exceed the max allowed overall size of extracted text.")); - } finally { - ExtractorFactory.setThreadPrefersEventExtractors(before); - } - } + @Test + void testZipEntityExpansionSharedStringTableEvents() { + boolean before = ExtractorFactory.getThreadPrefersEventExtractors(); + ExtractorFactory.setThreadPrefersEventExtractors(true); + try { + IllegalStateException ex = assertThrows( + IllegalStateException.class, + () -> openXmlBombFile("poc-shared-strings.xlsx") + ); + assertTrue(ex.getMessage().contains("The text would exceed the max allowed overall size of extracted text.")); + } finally { + ExtractorFactory.setThreadPrefersEventExtractors(before); + } + } - @Test - void testZipEntityExpansionExceedsMemory() { - IOException ex = assertThrows( - IOException.class, - () -> openXmlBombFile("poc-xmlbomb.xlsx") - ); - assertTrue(ex.getMessage().contains("unable to parse shared strings table")); - assertTrue(matchSAXEx(ex)); - } + @Test + void testZipEntityExpansionExceedsMemory() { + IOException ex = assertThrows( + IOException.class, + () -> openXmlBombFile("poc-xmlbomb.xlsx") + ); + assertTrue(ex.getMessage().contains("unable to parse shared strings table")); + assertTrue(matchSAXEx(ex)); + } - @Test - void testZipEntityExpansionExceedsMemory2() { - IOException ex = assertThrows( - IOException.class, - () -> openXmlBombFile("poc-xmlbomb-empty.xlsx") - ); - assertTrue(ex.getMessage().contains("unable to parse shared strings table")); - assertTrue(matchSAXEx(ex)); - } + @Test + void testZipEntityExpansionExceedsMemory2() { + IOException ex = assertThrows( + IOException.class, + () -> openXmlBombFile("poc-xmlbomb-empty.xlsx") + ); + assertTrue(ex.getMessage().contains("unable to parse shared strings table")); + assertTrue(matchSAXEx(ex)); + } - private static boolean matchSAXEx(Exception root) { - for (Throwable t = root; t != null; t = t.getCause()) { - if (t.getClass().isAssignableFrom(SAXParseException.class) && - t.getMessage().contains("The parser has encountered more than")) { - return true; - } - } - return false; - } + private static boolean matchSAXEx(Exception root) { + for (Throwable t = root; t != null; t = t.getCause()) { + if (t.getClass().isAssignableFrom(SAXParseException.class) && + t.getMessage().contains("The parser has encountered more than")) { + return true; + } + } + return false; + } - private void openXmlBombFile(String file) throws IOException { - final double minInf = ZipSecureFile.getMinInflateRatio(); - ZipSecureFile.setMinInflateRatio(0.002); - try (POITextExtractor extractor = ExtractorFactory.createExtractor(XSSFTestDataSamples.getSampleFile(file))) { - assertNotNull(extractor); - extractor.getText(); - } finally { - ZipSecureFile.setMinInflateRatio(minInf); - } - } + private void openXmlBombFile(String file) throws IOException { + final double minInf = ZipSecureFile.getMinInflateRatio(); + ZipSecureFile.setMinInflateRatio(0.002); + try (POITextExtractor extractor = ExtractorFactory.createExtractor(XSSFTestDataSamples.getSampleFile(file))) { + assertNotNull(extractor); + extractor.getText(); + } finally { + ZipSecureFile.setMinInflateRatio(minInf); + } + } @Test void zipBombCheckSizesWithinLimits() throws IOException, EncryptedDocumentException { - getZipStatsAndConsume((max_size, min_ratio) -> { - // use values close to, but within the limits - ZipSecureFile.setMinInflateRatio(min_ratio - 0.002); - assertEquals(min_ratio - 0.002, ZipSecureFile.getMinInflateRatio(), 0.00001); - ZipSecureFile.setMaxEntrySize(max_size + 1); - assertEquals(max_size + 1, ZipSecureFile.getMaxEntrySize()); - }); - } + getZipStatsAndConsume((max_size, min_ratio) -> { + // use values close to, but within the limits + ZipSecureFile.setMinInflateRatio(min_ratio - 0.002); + assertEquals(min_ratio - 0.002, ZipSecureFile.getMinInflateRatio(), 0.00001); + ZipSecureFile.setMaxEntrySize(max_size + 1); + assertEquals(max_size + 1, ZipSecureFile.getMaxEntrySize()); + }); + } - @Test - void zipBombCheckSizesRatioTooSmall() { - POIXMLException ex = assertThrows( - POIXMLException.class, - () -> getZipStatsAndConsume((max_size, min_ratio) -> { - // check ratio out of bounds - ZipSecureFile.setMinInflateRatio(min_ratio+0.002); - }) - ); - assertTrue(ex.getMessage().contains("You can adjust this limit via ZipSecureFile.setMinInflateRatio()")); - } + @Test + void zipBombCheckSizesRatioTooSmall() { + POIXMLException ex = assertThrows( + POIXMLException.class, + () -> getZipStatsAndConsume((max_size, min_ratio) -> { + // check ratio out of bounds + ZipSecureFile.setMinInflateRatio(min_ratio+0.002); + }) + ); + assertTrue(ex.getMessage().contains("You can adjust this limit via ZipSecureFile.setMinInflateRatio()")); + } - @Test - void zipBombCheckSizesSizeTooBig() throws EncryptedDocumentException { - POIXMLException ex = assertThrows( - POIXMLException.class, - () -> getZipStatsAndConsume((max_size, min_ratio) -> { - // check max entry size ouf of bounds - ZipSecureFile.setMinInflateRatio(min_ratio-0.002); - ZipSecureFile.setMaxEntrySize(max_size-200); - }) - ); - assertTrue(ex.getMessage().contains("You can adjust this limit via ZipSecureFile.setMaxEntrySize()")); - } + @Test + void zipBombCheckSizesSizeTooBig() throws EncryptedDocumentException { + POIXMLException ex = assertThrows( + POIXMLException.class, + () -> getZipStatsAndConsume((max_size, min_ratio) -> { + // check max entry size ouf of bounds + ZipSecureFile.setMinInflateRatio(min_ratio-0.002); + ZipSecureFile.setMaxEntrySize(max_size-200); + }) + ); + assertTrue(ex.getMessage().contains("You can adjust this limit via ZipSecureFile.setMaxEntrySize()")); + } - private void getZipStatsAndConsume(BiConsumer ratioCon) throws IOException { - // use a test file with a xml file bigger than 100k (ZipArchiveThresholdInputStream.GRACE_ENTRY_SIZE) - final File file = XSSFTestDataSamples.getSampleFile("poc-shared-strings.xlsx"); + private void getZipStatsAndConsume(BiConsumer ratioCon) throws IOException { + // use a test file with a xml file bigger than 100k (ZipArchiveThresholdInputStream.GRACE_ENTRY_SIZE) + final File file = XSSFTestDataSamples.getSampleFile("poc-shared-strings.xlsx"); - double min_ratio = Double.MAX_VALUE; - long max_size = 0; - try (ZipFile zf = ZipHelper.openZipFile(file)) { - assertNotNull(zf); - Enumeration entries = zf.getEntries(); - while (entries.hasMoreElements()) { - ZipArchiveEntry ze = entries.nextElement(); - if (ze.getSize() == 0) { - continue; - } - // add zip entry header ~ 128 bytes - long size = ze.getSize()+128; - double ratio = ze.getCompressedSize() / (double)size; - min_ratio = Math.min(min_ratio, ratio); - max_size = Math.max(max_size, size); - } - } - ratioCon.accept(max_size, min_ratio); + double min_ratio = Double.MAX_VALUE; + long max_size = 0; + try (ZipFile zf = ZipHelper.openZipFile(file)) { + assertNotNull(zf); + Enumeration entries = zf.getEntries(); + while (entries.hasMoreElements()) { + ZipArchiveEntry ze = entries.nextElement(); + if (ze.getSize() == 0) { + continue; + } + // add zip entry header ~ 128 bytes + long size = ze.getSize()+128; + double ratio = ze.getCompressedSize() / (double)size; + min_ratio = Math.min(min_ratio, ratio); + max_size = Math.max(max_size, size); + } + } + ratioCon.accept(max_size, min_ratio); - //noinspection EmptyTryBlock,unused - try (Workbook wb = WorkbookFactory.create(file, null, true)) { - } finally { - // reset otherwise a lot of ooxml tests will fail - ZipSecureFile.setMinInflateRatio(0.01d); - ZipSecureFile.setMaxEntrySize(0xFFFFFFFFL); - } - } + //noinspection EmptyTryBlock,unused + try (Workbook wb = WorkbookFactory.create(file, null, true)) { + } finally { + // reset otherwise a lot of ooxml tests will fail + ZipSecureFile.setMinInflateRatio(0.01d); + ZipSecureFile.setMaxEntrySize(0xFFFFFFFFL); + } + } @Test void testConstructors() throws IOException { // verify the various ways to construct a ZipSecureFile File file = getSampleFile("sample.xlsx"); try (ZipSecureFile zipFile = new ZipSecureFile(file)) { - assertNotNull(zipFile.getName()); - } + assertNotNull(zipFile.getName()); + } try (ZipSecureFile zipFile = new ZipSecureFile(file.getAbsolutePath())) { - assertNotNull(zipFile.getName()); - } + assertNotNull(zipFile.getName()); + } } @Test @@ -885,214 +885,214 @@ public final class TestPackage { assertThrows(NotOfficeXmlFileException.class, () -> OPCPackage.open(file, PackageAccess.READ)); } - private interface CountingStream { - InputStream create(InputStream is, int length); - } - - // bug 61381 - @Test - void testTooShortFilterStreams() throws IOException { - for (String file : new String[]{"sample.xlsx","SampleSS.xls"}) { - for (CountingStream cs : new CountingStream[]{PushbackInputStream::new, BufferedInputStream::new}) { - try (InputStream is = cs.create(xlsSamples.openResourceAsStream(file), 2); - Workbook wb = WorkbookFactory.create(is)) { - assertEquals(3, wb.getNumberOfSheets()); - } - } - } + private interface CountingStream { + InputStream create(InputStream is, int length); } - @Test - void testBug56479() throws Exception { - try (InputStream is = openSampleStream("dcterms_bug_56479.zip"); - OPCPackage p = OPCPackage.open(is)) { + // bug 61381 + @Test + void testTooShortFilterStreams() throws IOException { + for (String file : new String[]{"sample.xlsx","SampleSS.xls"}) { + for (CountingStream cs : new CountingStream[]{PushbackInputStream::new, BufferedInputStream::new}) { + try (InputStream is = cs.create(xlsSamples.openResourceAsStream(file), 2); + Workbook wb = WorkbookFactory.create(is)) { + assertEquals(3, wb.getNumberOfSheets()); + } + } + } + } - // Check we found the contents of it - boolean foundCoreProps = false, foundDocument = false, foundTheme1 = false; - for (final PackagePart part : p.getParts()) { - final String partName = part.getPartName().toString(); - final String contentType = part.getContentType(); - switch (partName) { - case "/docProps/core.xml": - assertEquals(ContentTypes.CORE_PROPERTIES_PART, contentType); - foundCoreProps = true; - break; - case "/word/document.xml": - assertEquals(XWPFRelation.DOCUMENT.getContentType(), contentType); - foundDocument = true; - break; - case "/word/theme/theme1.xml": - assertEquals(XWPFRelation.THEME.getContentType(), contentType); - foundTheme1 = true; - break; - } - } - assertTrue(foundCoreProps, "Core not found in " + p.getParts()); - assertFalse(foundDocument, "Document should not be found in " + p.getParts()); - assertFalse(foundTheme1, "Theme1 should not found in " + p.getParts()); - } - } + @Test + void testBug56479() throws Exception { + try (InputStream is = openSampleStream("dcterms_bug_56479.zip"); + OPCPackage p = OPCPackage.open(is)) { - @Test - void unparseableCentralDirectory() throws IOException { - File f = getSampleFile("at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx"); - try (SlideShow ppt = SlideShowFactory.create(f, null, true)) { - assertNotNull(ppt); - assertNotNull(ppt.getSlides().get(0)); - } - } + // Check we found the contents of it + boolean foundCoreProps = false, foundDocument = false, foundTheme1 = false; + for (final PackagePart part : p.getParts()) { + final String partName = part.getPartName().toString(); + final String contentType = part.getContentType(); + switch (partName) { + case "/docProps/core.xml": + assertEquals(ContentTypes.CORE_PROPERTIES_PART, contentType); + foundCoreProps = true; + break; + case "/word/document.xml": + assertEquals(XWPFRelation.DOCUMENT.getContentType(), contentType); + foundDocument = true; + break; + case "/word/theme/theme1.xml": + assertEquals(XWPFRelation.THEME.getContentType(), contentType); + foundTheme1 = true; + break; + } + } + assertTrue(foundCoreProps, "Core not found in " + p.getParts()); + assertFalse(foundDocument, "Document should not be found in " + p.getParts()); + assertFalse(foundTheme1, "Theme1 should not found in " + p.getParts()); + } + } - @Test - void testClosingStreamOnException() throws IOException { - File tmp = File.createTempFile("poi-test-truncated-zip", ""); + @Test + void unparseableCentralDirectory() throws IOException { + File f = getSampleFile("at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx"); + try (SlideShow ppt = SlideShowFactory.create(f, null, true)) { + assertNotNull(ppt); + assertNotNull(ppt.getSlides().get(0)); + } + } - // create a corrupted zip file by truncating a valid zip file to the first 100 bytes - try (InputStream is = openSampleStream("dcterms_bug_56479.zip"); - OutputStream os = new FileOutputStream(tmp)) { - IOUtils.copy(is, os, 100); - } + @Test + void testClosingStreamOnException() throws IOException { + File tmp = File.createTempFile("poi-test-truncated-zip", ""); - // feed the corrupted zip file to OPCPackage - // expected: the zip file is invalid - // this test does not care if open() throws an exception or not. - assertThrows(Exception.class, () -> OPCPackage.open(tmp, PackageAccess.READ)); + // create a corrupted zip file by truncating a valid zip file to the first 100 bytes + try (InputStream is = openSampleStream("dcterms_bug_56479.zip"); + OutputStream os = new FileOutputStream(tmp)) { + IOUtils.copy(is, os, 100); + } - // If the stream is not closed on exception, it will keep a file descriptor to tmp, - // and requests to the OS to delete the file will fail. - assertTrue(tmp.delete(), "Can't delete tmp file"); - } + // feed the corrupted zip file to OPCPackage + // expected: the zip file is invalid + // this test does not care if open() throws an exception or not. + assertThrows(Exception.class, () -> OPCPackage.open(tmp, PackageAccess.READ)); - /** - * If ZipPackage is passed an invalid file, a call to close - * (eg from the OPCPackage open method) should tidy up the - * stream / file the broken file is being read from. - * See bug #60128 for more - */ - @Test - void testTidyStreamOnInvalidFile1() throws Exception { - openInvalidFile("SampleSS.ods", false); - } + // If the stream is not closed on exception, it will keep a file descriptor to tmp, + // and requests to the OS to delete the file will fail. + assertTrue(tmp.delete(), "Can't delete tmp file"); + } - @Test - void testTidyStreamOnInvalidFile2() throws Exception { - openInvalidFile("SampleSS.ods", true); - } + /** + * If ZipPackage is passed an invalid file, a call to close + * (eg from the OPCPackage open method) should tidy up the + * stream / file the broken file is being read from. + * See bug #60128 for more + */ + @Test + void testTidyStreamOnInvalidFile1() throws Exception { + openInvalidFile("SampleSS.ods", false); + } - @Test - void testTidyStreamOnInvalidFile3() throws Exception { - openInvalidFile("SampleSS.txt", false); - } + @Test + void testTidyStreamOnInvalidFile2() throws Exception { + openInvalidFile("SampleSS.ods", true); + } - @Test - void testTidyStreamOnInvalidFile4() throws Exception { - openInvalidFile("SampleSS.txt", true); - } + @Test + void testTidyStreamOnInvalidFile3() throws Exception { + openInvalidFile("SampleSS.txt", false); + } - @Test - void testBug62592() throws Exception { - try (InputStream is = openSampleStream("62592.thmx")) { - assertThrows(InvalidFormatException.class, () -> OPCPackage.open(is)); - } - } + @Test + void testTidyStreamOnInvalidFile4() throws Exception { + openInvalidFile("SampleSS.txt", true); + } - @Test - void testBug62592SequentialCallsToGetParts() throws Exception { - //make absolutely certain that sequential calls don't throw InvalidFormatExceptions - String originalFile = getSampleFileName("TestPackageCommon.docx"); - try (OPCPackage p2 = OPCPackage.open(originalFile, PackageAccess.READ)) { - assertDoesNotThrow(p2::getParts); - assertDoesNotThrow(p2::getParts); - } - } + @Test + void testBug62592() throws Exception { + try (InputStream is = openSampleStream("62592.thmx")) { + assertThrows(InvalidFormatException.class, () -> OPCPackage.open(is)); + } + } - @Test - void testDoNotCloseStream() throws IOException { - // up to JDK 10 we did use Mockito here, but OutputStream is - // an abstract class and fails mocking with some changes in JDK 11 - // so we use a simple empty output stream implementation instead - OutputStream os = new OutputStream() { - @Override - public void write(int b) { - } + @Test + void testBug62592SequentialCallsToGetParts() throws Exception { + //make absolutely certain that sequential calls don't throw InvalidFormatExceptions + String originalFile = getSampleFileName("TestPackageCommon.docx"); + try (OPCPackage p2 = OPCPackage.open(originalFile, PackageAccess.READ)) { + assertDoesNotThrow(p2::getParts); + assertDoesNotThrow(p2::getParts); + } + } - @Override - public void close() { - fail("close should not be called here"); - } - }; + @Test + void testDoNotCloseStream() throws IOException { + // up to JDK 10 we did use Mockito here, but OutputStream is + // an abstract class and fails mocking with some changes in JDK 11 + // so we use a simple empty output stream implementation instead + OutputStream os = new OutputStream() { + @Override + public void write(int b) { + } - try (XSSFWorkbook wb = new XSSFWorkbook()) { - wb.createSheet(); - wb.write(os); - } + @Override + public void close() { + fail("close should not be called here"); + } + }; - try (SXSSFWorkbook wb = new SXSSFWorkbook()) { - wb.createSheet(); - wb.write(os); - } - } + try (XSSFWorkbook wb = new XSSFWorkbook()) { + wb.createSheet(); + wb.write(os); + } + + try (SXSSFWorkbook wb = new SXSSFWorkbook()) { + wb.createSheet(); + wb.write(os); + } + } - private static void openInvalidFile(final String name, final boolean useStream) throws IOException { - ZipPackage[] pkgTest = { null }; - try (final InputStream is = (useStream) ? xlsSamples.openResourceAsStream(name) : null) { - assertThrows(NotOfficeXmlFileException.class, () -> { - try (final ZipPackage pkg = (useStream) - ? new ZipPackage(is, PackageAccess.READ) - : new ZipPackage(xlsSamples.getFile(name), PackageAccess.READ)) { - pkgTest[0] = pkg; - assertNotNull(pkg.getZipArchive()); - assertFalse(pkg.getZipArchive().isClosed()); - pkg.getParts(); - } - }); - } finally { - if (pkgTest[0] != null) { - assertNotNull(pkgTest[0].getZipArchive()); - assertTrue(pkgTest[0].getZipArchive().isClosed()); - } - } - } + private static void openInvalidFile(final String name, final boolean useStream) throws IOException { + ZipPackage[] pkgTest = { null }; + try (final InputStream is = (useStream) ? xlsSamples.openResourceAsStream(name) : null) { + assertThrows(NotOfficeXmlFileException.class, () -> { + try (final ZipPackage pkg = (useStream) + ? new ZipPackage(is, PackageAccess.READ) + : new ZipPackage(xlsSamples.getFile(name), PackageAccess.READ)) { + pkgTest[0] = pkg; + assertNotNull(pkg.getZipArchive()); + assertFalse(pkg.getZipArchive().isClosed()); + pkg.getParts(); + } + }); + } finally { + if (pkgTest[0] != null) { + assertNotNull(pkgTest[0].getZipArchive()); + assertTrue(pkgTest[0].getZipArchive().isClosed()); + } + } + } - @SuppressWarnings("UnstableApiUsage") - @Test - void testBug63029() throws Exception { - File testFile = getSampleFile("sample.docx"); - File tmpFile = getOutputFile("Bug63029.docx"); - Files.copy(testFile, tmpFile); + @SuppressWarnings("UnstableApiUsage") + @Test + void testBug63029() throws Exception { + File testFile = getSampleFile("sample.docx"); + File tmpFile = getOutputFile("Bug63029.docx"); + Files.copy(testFile, tmpFile); - int numPartsBefore = 0; - String md5Before = Files.asByteSource(tmpFile).hash(Hashing.sha256()).toString(); + int numPartsBefore = 0; + String md5Before = Files.asByteSource(tmpFile).hash(Hashing.sha256()).toString(); - try(OPCPackage pkg = OPCPackage.open(tmpFile, PackageAccess.READ_WRITE)) - { - numPartsBefore = pkg.getParts().size(); + try(OPCPackage pkg = OPCPackage.open(tmpFile, PackageAccess.READ_WRITE)) + { + numPartsBefore = pkg.getParts().size(); - // add a marshaller that will throw an exception on save - pkg.addMarshaller("poi/junit", (part, out) -> { - throw new RuntimeException("Bugzilla 63029"); - }); + // add a marshaller that will throw an exception on save + pkg.addMarshaller("poi/junit", (part, out) -> { + throw new RuntimeException("Bugzilla 63029"); + }); - pkg.createPart(createPartName("/poi/test.xml"), "poi/junit"); + pkg.createPart(createPartName("/poi/test.xml"), "poi/junit"); - RuntimeException ex = assertThrows(RuntimeException.class, pkg::close); - // verify there was an exception while closing the file - assertEquals("Fail to save: an error occurs while saving the package : Bugzilla 63029", ex.getMessage()); - } + RuntimeException ex = assertThrows(RuntimeException.class, pkg::close); + // verify there was an exception while closing the file + assertEquals("Fail to save: an error occurs while saving the package : Bugzilla 63029", ex.getMessage()); + } - // assert that md5 after closing is the same, i.e. the source is left intact - String md5After = Files.asByteSource(tmpFile).hash(Hashing.sha256()).toString(); - assertEquals(md5Before, md5After); + // assert that md5 after closing is the same, i.e. the source is left intact + String md5After = Files.asByteSource(tmpFile).hash(Hashing.sha256()).toString(); + assertEquals(md5Before, md5After); - // try to read the source file once again - try ( OPCPackage pkg = OPCPackage.open(tmpFile, PackageAccess.READ_WRITE)){ - // the source is still a valid zip archive. - // prior to the fix this used to throw NotOfficeXmlFileException("archive is not a ZIP archive") + // try to read the source file once again + try ( OPCPackage pkg = OPCPackage.open(tmpFile, PackageAccess.READ_WRITE)){ + // the source is still a valid zip archive. + // prior to the fix this used to throw NotOfficeXmlFileException("archive is not a ZIP archive") - // assert that the number of parts remained the same - assertEquals(pkg.getParts().size(), numPartsBefore); - } + // assert that the number of parts remained the same + assertEquals(pkg.getParts().size(), numPartsBefore); + } - } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java index 6dbfcf0dc9..6ef0bab8f4 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java @@ -47,38 +47,38 @@ import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty; public final class TestPackageCoreProperties { - /** - * Test package core properties getters. - */ + /** + * Test package core properties getters. + */ @Test - void testGetProperties() throws Exception { - // Open the package - @SuppressWarnings("resource") + void testGetProperties() throws Exception { + // Open the package + @SuppressWarnings("resource") OPCPackage p = OPCPackage.open(openSampleStream("TestPackageCoreProperiesGetters.docx")); - compareProperties(p); - p.revert(); - } + compareProperties(p); + p.revert(); + } - /** - * Test package core properties setters. - */ + /** + * Test package core properties setters. + */ @Test void testSetProperties() throws Exception { - String inputPath = getSampleFileName("TestPackageCoreProperiesSetters.docx"); + String inputPath = getSampleFileName("TestPackageCoreProperiesSetters.docx"); - File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx"); + File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx"); - // Open package - @SuppressWarnings("resource") + // Open package + @SuppressWarnings("resource") OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE); - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - Date dateToInsert = df.parse("2007-05-12T08:00:00Z", new ParsePosition(0)); + Date dateToInsert = df.parse("2007-05-12T08:00:00Z", new ParsePosition(0)); SimpleDateFormat msdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT); msdf.setTimeZone(LocaleUtil.TIMEZONE_UTC); - PackageProperties props = p.getPackageProperties(); + PackageProperties props = p.getPackageProperties(); //test various date formats props.setCreatedProperty("2007-05-12T08:00:00Z"); @@ -106,59 +106,59 @@ public final class TestPackageCoreProperties { assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().orElse(null)); props.setCategoryProperty("MyCategory"); - props.setContentStatusProperty("MyContentStatus"); - props.setContentTypeProperty("MyContentType"); - props.setCreatorProperty("MyCreator"); - props.setDescriptionProperty("MyDescription"); - props.setIdentifierProperty("MyIdentifier"); - props.setKeywordsProperty("MyKeywords"); - props.setLanguageProperty("MyLanguage"); - props.setLastModifiedByProperty("Julien Chable"); - props.setLastPrintedProperty(Optional.of(dateToInsert)); - props.setModifiedProperty(Optional.of(dateToInsert)); - props.setRevisionProperty("2"); - props.setTitleProperty("MyTitle"); - props.setSubjectProperty("MySubject"); - props.setVersionProperty("2"); - // Save the package in the output directory - p.save(outputFile); + props.setContentStatusProperty("MyContentStatus"); + props.setContentTypeProperty("MyContentType"); + props.setCreatorProperty("MyCreator"); + props.setDescriptionProperty("MyDescription"); + props.setIdentifierProperty("MyIdentifier"); + props.setKeywordsProperty("MyKeywords"); + props.setLanguageProperty("MyLanguage"); + props.setLastModifiedByProperty("Julien Chable"); + props.setLastPrintedProperty(Optional.of(dateToInsert)); + props.setModifiedProperty(Optional.of(dateToInsert)); + props.setRevisionProperty("2"); + props.setTitleProperty("MyTitle"); + props.setSubjectProperty("MySubject"); + props.setVersionProperty("2"); + // Save the package in the output directory + p.save(outputFile); p.revert(); - // Open the newly created file to check core properties saved values. - @SuppressWarnings("resource") + // Open the newly created file to check core properties saved values. + @SuppressWarnings("resource") OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ); - compareProperties(p2); - p2.revert(); - assertTrue(outputFile.delete()); - } + compareProperties(p2); + p2.revert(); + assertTrue(outputFile.delete()); + } - private void compareProperties(OPCPackage p) throws InvalidFormatException { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - Date expectedDate = df.parse("2007-05-12T08:00:00Z", new ParsePosition(0)); + private void compareProperties(OPCPackage p) throws InvalidFormatException { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); + df.setTimeZone(LocaleUtil.TIMEZONE_UTC); + Date expectedDate = df.parse("2007-05-12T08:00:00Z", new ParsePosition(0)); - // Gets the core properties - PackageProperties props = p.getPackageProperties(); - assertEquals("MyCategory", props.getCategoryProperty().orElse(null)); - assertEquals("MyContentStatus", props.getContentStatusProperty().orElse(null)); - assertEquals("MyContentType", props.getContentTypeProperty().orElse(null)); - assertEquals(expectedDate, props.getCreatedProperty().orElse(null)); - assertEquals("MyCreator", props.getCreatorProperty().orElse(null)); - assertEquals("MyDescription", props.getDescriptionProperty().orElse(null)); - assertEquals("MyIdentifier", props.getIdentifierProperty().orElse(null)); - assertEquals("MyKeywords", props.getKeywordsProperty().orElse(null)); - assertEquals("MyLanguage", props.getLanguageProperty().orElse(null)); - assertEquals("Julien Chable", props.getLastModifiedByProperty().orElse(null)); - assertEquals(expectedDate, props.getLastPrintedProperty().orElse(null)); - assertEquals(expectedDate, props.getModifiedProperty().orElse(null)); - assertEquals("2", props.getRevisionProperty().orElse(null)); - assertEquals("MySubject", props.getSubjectProperty().orElse(null)); - assertEquals("MyTitle", props.getTitleProperty().orElse(null)); - assertEquals("2", props.getVersionProperty().orElse(null)); - } + // Gets the core properties + PackageProperties props = p.getPackageProperties(); + assertEquals("MyCategory", props.getCategoryProperty().orElse(null)); + assertEquals("MyContentStatus", props.getContentStatusProperty().orElse(null)); + assertEquals("MyContentType", props.getContentTypeProperty().orElse(null)); + assertEquals(expectedDate, props.getCreatedProperty().orElse(null)); + assertEquals("MyCreator", props.getCreatorProperty().orElse(null)); + assertEquals("MyDescription", props.getDescriptionProperty().orElse(null)); + assertEquals("MyIdentifier", props.getIdentifierProperty().orElse(null)); + assertEquals("MyKeywords", props.getKeywordsProperty().orElse(null)); + assertEquals("MyLanguage", props.getLanguageProperty().orElse(null)); + assertEquals("Julien Chable", props.getLastModifiedByProperty().orElse(null)); + assertEquals(expectedDate, props.getLastPrintedProperty().orElse(null)); + assertEquals(expectedDate, props.getModifiedProperty().orElse(null)); + assertEquals("2", props.getRevisionProperty().orElse(null)); + assertEquals("MySubject", props.getSubjectProperty().orElse(null)); + assertEquals("MyTitle", props.getTitleProperty().orElse(null)); + assertEquals("2", props.getVersionProperty().orElse(null)); + } - @Test - void testCoreProperties_bug51374() throws Exception { + @Test + void testCoreProperties_bug51374() throws Exception { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); df.setTimeZone(LocaleUtil.TIMEZONE_UTC); String strDate = "2007-05-12T08:00:00Z"; @@ -214,8 +214,8 @@ public final class TestPackageCoreProperties { } } - @Test - void testGetPropertiesLO() throws Exception { + @Test + void testGetPropertiesLO() throws Exception { UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); // Open the package try (OPCPackage pkg1 = OPCPackage.open(openSampleStream("51444.xlsx"))) { @@ -231,8 +231,8 @@ public final class TestPackageCoreProperties { } } - @Test - void testEntitiesInCoreProps_56164() throws Exception { + @Test + void testEntitiesInCoreProps_56164() throws Exception { try (InputStream is = openSampleStream("CorePropertiesHasEntities.ooxml"); OPCPackage p = OPCPackage.open(is)) { @@ -263,8 +263,8 @@ public final class TestPackageCoreProperties { } } - @Test - void testListOfCustomProperties() throws Exception { + @Test + void testListOfCustomProperties() throws Exception { File inp = POIDataSamples.getSpreadSheetInstance().getFile("ExcelWithAttachments.xlsm"); try (OPCPackage pkg = OPCPackage.open(inp, PackageAccess.READ); XSSFWorkbook wb = new XSSFWorkbook(pkg)) { @@ -278,8 +278,8 @@ public final class TestPackageCoreProperties { } } - @Test - void testAlternateCorePropertyTimezones() throws Exception { + @Test + void testAlternateCorePropertyTimezones() throws Exception { // We need predictable dates for testing! SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT); df.setTimeZone(LocaleUtil.TIMEZONE_UTC); @@ -329,5 +329,5 @@ public final class TestPackageCoreProperties { // CoreProperties are stored as xs:dateTime -> no milliseconds are saved! assertEquals("2007-06-21T09:59:00.000Z", df.format(props2.getModifiedProperty().orElse(null))); } - } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackagePartName.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackagePartName.java index 2572aadfad..c38e802e01 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackagePartName.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackagePartName.java @@ -23,14 +23,14 @@ import org.junit.jupiter.api.Test; public final class TestPackagePartName { - /** - * Test method getExtension(). - */ - @Test - void testGetExtension() throws Exception{ - PackagePartName name1 = PackagingURIHelper.createPartName("/doc/props/document.xml"); - PackagePartName name2 = PackagingURIHelper.createPartName("/root/document"); - assertEquals("xml", name1.getExtension()); - assertEquals("", name2.getExtension()); - } + /** + * Test method getExtension(). + */ + @Test + void testGetExtension() throws Exception{ + PackagePartName name1 = PackagingURIHelper.createPartName("/doc/props/document.xml"); + PackagePartName name2 = PackagingURIHelper.createPartName("/root/document"); + assertEquals("xml", name1.getExtension()); + assertEquals("", name2.getExtension()); + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java index e68a92d200..37b2885b5f 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java @@ -31,31 +31,31 @@ import org.junit.jupiter.api.Test; */ public final class TestPackageThumbnail { - /** - * Test package addThumbnail() method. - */ - @Test - void testSetProperties() throws Exception { - String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageThumbnail.docx"); + /** + * Test package addThumbnail() method. + */ + @Test + void testSetProperties() throws Exception { + String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageThumbnail.docx"); - String imagePath = OpenXML4JTestDataSamples.getSampleFileName("thumbnail.jpg"); + String imagePath = OpenXML4JTestDataSamples.getSampleFileName("thumbnail.jpg"); - File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageThumbnailOUTPUT.docx"); + File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageThumbnailOUTPUT.docx"); - // Open package - try (OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE)) { - p.addThumbnail(imagePath); - // Save the package in the output directory - p.save(outputFile); + // Open package + try (OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE)) { + p.addThumbnail(imagePath); + // Save the package in the output directory + p.save(outputFile); - // Open the newly created file to check core properties saved values. - try (OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ)) { - assertNotEquals(0, p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL).size(), - "Thumbnail not added to the package !"); - p2.revert(); - } - p.revert(); - } - assertTrue(outputFile.delete()); - } + // Open the newly created file to check core properties saved values. + try (OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ)) { + assertNotEquals(0, p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL).size(), + "Thumbnail not added to the package !"); + p2.revert(); + } + p.revert(); + } + assertTrue(outputFile.delete()); + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java index d6b81c9a54..ec82a36dd4 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java @@ -36,12 +36,12 @@ import org.junit.jupiter.api.Test; class TestRelationships { - private static final String HYPERLINK_REL_TYPE = - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; - private static final String COMMENTS_REL_TYPE = - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"; - private static final String SHEET_WITH_COMMENTS = - "/xl/worksheets/sheet1.xml"; + private static final String HYPERLINK_REL_TYPE = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; + private static final String COMMENTS_REL_TYPE = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"; + private static final String SHEET_WITH_COMMENTS = + "/xl/worksheets/sheet1.xml"; private static final Logger LOG = LogManager.getLogger(TestPackageCoreProperties.class); @@ -155,72 +155,72 @@ class TestRelationships { */ @Test void testCreateExcelHyperlinkRelations() throws Exception { - String filepath = OpenXML4JTestDataSamples.getSampleFileName("ExcelWithHyperlinks.xlsx"); - OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE); - PackagePart sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - assertNotNull(sheet); + String filepath = OpenXML4JTestDataSamples.getSampleFileName("ExcelWithHyperlinks.xlsx"); + OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE); + PackagePart sheet = pkg.getPart( + PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); + assertNotNull(sheet); - assertEquals(3, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); + assertEquals(3, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); - // Add three new ones - PackageRelationship openxml4j = - sheet.addExternalRelationship("http://www.openxml4j.org/", HYPERLINK_REL_TYPE); - PackageRelationship sf = - sheet.addExternalRelationship("http://openxml4j.sf.net/", HYPERLINK_REL_TYPE); - PackageRelationship file = - sheet.addExternalRelationship("MyDocument.docx", HYPERLINK_REL_TYPE); + // Add three new ones + PackageRelationship openxml4j = + sheet.addExternalRelationship("http://www.openxml4j.org/", HYPERLINK_REL_TYPE); + PackageRelationship sf = + sheet.addExternalRelationship("http://openxml4j.sf.net/", HYPERLINK_REL_TYPE); + PackageRelationship file = + sheet.addExternalRelationship("MyDocument.docx", HYPERLINK_REL_TYPE); - // Check they were added properly - assertNotNull(openxml4j); - assertNotNull(sf); - assertNotNull(file); + // Check they were added properly + assertNotNull(openxml4j); + assertNotNull(sf); + assertNotNull(file); - assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); + assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); - assertEquals("http://www.openxml4j.org/", openxml4j.getTargetURI().toString()); - assertEquals("/xl/worksheets/sheet1.xml", openxml4j.getSourceURI().toString()); - assertEquals(HYPERLINK_REL_TYPE, openxml4j.getRelationshipType()); + assertEquals("http://www.openxml4j.org/", openxml4j.getTargetURI().toString()); + assertEquals("/xl/worksheets/sheet1.xml", openxml4j.getSourceURI().toString()); + assertEquals(HYPERLINK_REL_TYPE, openxml4j.getRelationshipType()); - assertEquals("http://openxml4j.sf.net/", sf.getTargetURI().toString()); - assertEquals("/xl/worksheets/sheet1.xml", sf.getSourceURI().toString()); - assertEquals(HYPERLINK_REL_TYPE, sf.getRelationshipType()); + assertEquals("http://openxml4j.sf.net/", sf.getTargetURI().toString()); + assertEquals("/xl/worksheets/sheet1.xml", sf.getSourceURI().toString()); + assertEquals(HYPERLINK_REL_TYPE, sf.getRelationshipType()); - assertEquals("MyDocument.docx", file.getTargetURI().toString()); - assertEquals("/xl/worksheets/sheet1.xml", file.getSourceURI().toString()); - assertEquals(HYPERLINK_REL_TYPE, file.getRelationshipType()); + assertEquals("MyDocument.docx", file.getTargetURI().toString()); + assertEquals("/xl/worksheets/sheet1.xml", file.getSourceURI().toString()); + assertEquals(HYPERLINK_REL_TYPE, file.getRelationshipType()); - // Will get ids 7, 8 and 9, as we already have 1-6 - assertEquals("rId7", openxml4j.getId()); - assertEquals("rId8", sf.getId()); - assertEquals("rId9", file.getId()); + // Will get ids 7, 8 and 9, as we already have 1-6 + assertEquals("rId7", openxml4j.getId()); + assertEquals("rId8", sf.getId()); + assertEquals("rId9", file.getId()); - // Write out and re-load - UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); - pkg.save(baos); + // Write out and re-load + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); + pkg.save(baos); - // use revert to not re-write the input file + // use revert to not re-write the input file pkg.revert(); - pkg = OPCPackage.open(baos.toInputStream()); + pkg = OPCPackage.open(baos.toInputStream()); - // Check again - sheet = pkg.getPart(PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); + // Check again + sheet = pkg.getPart(PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); + assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); - assertEquals("http://poi.apache.org/", - sheet.getRelationship("rId1").getTargetURI().toString()); - assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", - sheet.getRelationship("rId3").getTargetURI().toString()); + assertEquals("http://poi.apache.org/", + sheet.getRelationship("rId1").getTargetURI().toString()); + assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", + sheet.getRelationship("rId3").getTargetURI().toString()); - assertEquals("http://www.openxml4j.org/", - sheet.getRelationship("rId7").getTargetURI().toString()); - assertEquals("http://openxml4j.sf.net/", - sheet.getRelationship("rId8").getTargetURI().toString()); - assertEquals("MyDocument.docx", - sheet.getRelationship("rId9").getTargetURI().toString()); + assertEquals("http://www.openxml4j.org/", + sheet.getRelationship("rId7").getTargetURI().toString()); + assertEquals("http://openxml4j.sf.net/", + sheet.getRelationship("rId8").getTargetURI().toString()); + assertEquals("MyDocument.docx", + sheet.getRelationship("rId9").getTargetURI().toString()); } @Test @@ -352,9 +352,9 @@ class TestRelationships { @Test void testSelfRelations_bug51187() throws Exception { - UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); PackageRelationship rel1; - try (OPCPackage pkg = OPCPackage.create(baos)) { + try (OPCPackage pkg = OPCPackage.create(baos)) { PackagePart partA = pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain"); @@ -367,7 +367,7 @@ class TestRelationships { // Save, and re-load } - try (OPCPackage pkg = OPCPackage.open(baos.toInputStream())) { + try (OPCPackage pkg = OPCPackage.open(baos.toInputStream())) { PackagePart partA = pkg.getPart(PackagingURIHelper.createPartName("/partA")); diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java index afd498aa12..644aca19b1 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java +++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java @@ -174,12 +174,12 @@ class TestSignatureInfo { private KeyPair keyPair; private X509Certificate x509; - @BeforeAll - public static void setUpClass() { - POITestCase.setImageIOCacheDir(); - } + @BeforeAll + public static void setUpClass() { + POITestCase.setImageIOCacheDir(); + } - @AfterAll + @AfterAll public static void removeUserLocale() { LocaleUtil.resetUserLocale(); } @@ -748,13 +748,13 @@ class TestSignatureInfo { void bug65214() throws Exception { initKeyPair(); - UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); - try (XWPFDocument doc = new XWPFDocument()) { + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); + try (XWPFDocument doc = new XWPFDocument()) { XWPFHyperlinkRun r = doc.createParagraph().createHyperlinkRun("http://poi.apache.org"); - r.setText("Hyperlink"); - r.setUnderline(UnderlinePatterns.SINGLE); - r.setUnderlineColor("0000FF"); - doc.write(bos); + r.setText("Hyperlink"); + r.setUnderline(UnderlinePatterns.SINGLE); + r.setUnderlineColor("0000FF"); + doc.write(bos); } SignatureConfig signatureConfig = new SignatureConfig(); @@ -966,7 +966,7 @@ class TestSignatureInfo { try (OPCPackage pkg = OPCPackage.open(signDoc, PackageAccess.READ)) { SignatureLine line2 = sup.get(); try (POIXMLDocument doc = reinit.init(line2, pkg)) { - assertNotNull(doc); + assertNotNull(doc); line2.parse(); assertEquals(line.getSuggestedSigner(), line2.getSuggestedSigner()); diff --git a/poi-ooxml/src/test/java/org/apache/poi/ss/tests/formula/eval/TestXSSFCircularReferences.java b/poi-ooxml/src/test/java/org/apache/poi/ss/tests/formula/eval/TestXSSFCircularReferences.java index 127c602680..d97c00dacb 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/ss/tests/formula/eval/TestXSSFCircularReferences.java +++ b/poi-ooxml/src/test/java/org/apache/poi/ss/tests/formula/eval/TestXSSFCircularReferences.java @@ -24,7 +24,7 @@ import org.apache.poi.xssf.XSSFITestDataProvider; * Tests XSSFFormulaEvaluator for its handling of cell formula circular references. */ public final class TestXSSFCircularReferences extends BaseTestCircularReferences { - public TestXSSFCircularReferences() { + public TestXSSFCircularReferences() { super(XSSFITestDataProvider.instance); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFSlideShow.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFSlideShow.java index 1d948dc6ee..c606c4a95a 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFSlideShow.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFSlideShow.java @@ -48,94 +48,94 @@ class TestXSLFSlideShow { @BeforeEach void setUp() throws Exception { - pack = OPCPackage.open(slTests.openResourceAsStream("sample.pptx")); - } + pack = OPCPackage.open(slTests.openResourceAsStream("sample.pptx")); + } - @AfterEach - void tearDown() throws IOException { - pack.close(); - } + @AfterEach + void tearDown() throws IOException { + pack.close(); + } @Test - void testContainsMainContentType() throws Exception { - boolean found = false; - for(PackagePart part : pack.getParts()) { - if(part.getContentType().equals(XSLFRelation.MAIN.getContentType())) { - found = true; - } - } - assertTrue(found); - } + void testContainsMainContentType() throws Exception { + boolean found = false; + for(PackagePart part : pack.getParts()) { + if(part.getContentType().equals(XSLFRelation.MAIN.getContentType())) { + found = true; + } + } + assertTrue(found); + } @Test - void testOpen() throws IOException, OpenXML4JException, XmlException { - // With the finalized uri, should be fine - XSLFSlideShow xml = new XSLFSlideShow(pack); - // Check the core - assertNotNull(xml.getPresentation()); + void testOpen() throws IOException, OpenXML4JException, XmlException { + // With the finalized uri, should be fine + XSLFSlideShow xml = new XSLFSlideShow(pack); + // Check the core + assertNotNull(xml.getPresentation()); - // Check it has some slides - assertNotEquals(0, xml.getSlideReferences().sizeOfSldIdArray()); - assertNotEquals(0, xml.getSlideMasterReferences().sizeOfSldMasterIdArray()); + // Check it has some slides + assertNotEquals(0, xml.getSlideReferences().sizeOfSldIdArray()); + assertNotEquals(0, xml.getSlideMasterReferences().sizeOfSldMasterIdArray()); - xml.close(); - } + xml.close(); + } @Test - void testSlideBasics() throws IOException, OpenXML4JException, XmlException { - XSLFSlideShow xml = new XSLFSlideShow(pack); + void testSlideBasics() throws IOException, OpenXML4JException, XmlException { + XSLFSlideShow xml = new XSLFSlideShow(pack); - // Should have 1 master - assertEquals(1, xml.getSlideMasterReferences().sizeOfSldMasterIdArray()); + // Should have 1 master + assertEquals(1, xml.getSlideMasterReferences().sizeOfSldMasterIdArray()); - // Should have three sheets - assertEquals(2, xml.getSlideReferences().sizeOfSldIdArray()); + // Should have three sheets + assertEquals(2, xml.getSlideReferences().sizeOfSldIdArray()); - // Check they're as expected - CTSlideIdListEntry[] slides = xml.getSlideReferences().getSldIdArray(); + // Check they're as expected + CTSlideIdListEntry[] slides = xml.getSlideReferences().getSldIdArray(); - assertEquals(256, slides[0].getId()); - assertEquals(257, slides[1].getId()); - assertEquals("rId2", slides[0].getId2()); - assertEquals("rId3", slides[1].getId2()); + assertEquals(256, slides[0].getId()); + assertEquals(257, slides[1].getId()); + assertEquals("rId2", slides[0].getId2()); + assertEquals("rId3", slides[1].getId2()); - // Now get those objects - assertNotNull(xml.getSlide(slides[0])); - assertNotNull(xml.getSlide(slides[1])); + // Now get those objects + assertNotNull(xml.getSlide(slides[0])); + assertNotNull(xml.getSlide(slides[1])); - // And check they have notes as expected - assertNotNull(xml.getNotes(slides[0])); - assertNotNull(xml.getNotes(slides[1])); + // And check they have notes as expected + assertNotNull(xml.getNotes(slides[0])); + assertNotNull(xml.getNotes(slides[1])); - // And again for the master - CTSlideMasterIdListEntry[] masters = xml.getSlideMasterReferences().getSldMasterIdArray(); + // And again for the master + CTSlideMasterIdListEntry[] masters = xml.getSlideMasterReferences().getSldMasterIdArray(); - // see SlideAtom.USES_MASTER_SLIDE_ID - assertEquals(0x80000000L, masters[0].getId()); - assertEquals("rId1", masters[0].getId2()); - assertNotNull(xml.getSlideMaster(masters[0])); + // see SlideAtom.USES_MASTER_SLIDE_ID + assertEquals(0x80000000L, masters[0].getId()); + assertEquals("rId1", masters[0].getId2()); + assertNotNull(xml.getSlideMaster(masters[0])); - xml.close(); - } + xml.close(); + } @Test - void testMetadataBasics() throws IOException, OpenXML4JException, XmlException { - XSLFSlideShow xml = new XSLFSlideShow(pack); + void testMetadataBasics() throws IOException, OpenXML4JException, XmlException { + XSLFSlideShow xml = new XSLFSlideShow(pack); - assertNotNull(xml.getProperties().getCoreProperties()); - assertNotNull(xml.getProperties().getExtendedProperties()); + assertNotNull(xml.getProperties().getCoreProperties()); + assertNotNull(xml.getProperties().getExtendedProperties()); - CTProperties props = xml.getProperties().getExtendedProperties().getUnderlyingProperties(); - assertEquals("Microsoft Office PowerPoint", props.getApplication()); - assertEquals(0, props.getCharacters()); - assertEquals(0, props.getLines()); + CTProperties props = xml.getProperties().getExtendedProperties().getUnderlyingProperties(); + assertEquals("Microsoft Office PowerPoint", props.getApplication()); + assertEquals(0, props.getCharacters()); + assertEquals(0, props.getLines()); - CoreProperties cprops = xml.getProperties().getCoreProperties(); - assertNull(cprops.getTitle()); - assertFalse(cprops.getUnderlyingProperties().getSubjectProperty().isPresent()); + CoreProperties cprops = xml.getProperties().getCoreProperties(); + assertNull(cprops.getTitle()); + assertFalse(cprops.getUnderlyingProperties().getSubjectProperty().isPresent()); - xml.close(); - } + xml.close(); + } @Test void testMasterBackground() throws IOException { diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java index 5e5f0ed4cb..26c37cc153 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java @@ -42,9 +42,9 @@ import org.junit.jupiter.api.Test; class TestXSLFPowerPointExtractor { private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - /** - * Get text out of the simple file - */ + /** + * Get text out of the simple file + */ @Test void testGetSimpleText() throws IOException { try (XMLSlideShow xmlA = openPPTX("sample.pptx"); @@ -155,7 +155,7 @@ class TestXSLFPowerPointExtractor { text = extractor.getText(); assertEquals("\n1\n\n2\n", text); } - } + } @Test void testGetComments() throws IOException { @@ -176,8 +176,8 @@ class TestXSLFPowerPointExtractor { } @Test - void testGetMasterText() throws Exception { - try (XMLSlideShow xml = openPPTX("WithMaster.pptx"); + void testGetMasterText() throws Exception { + try (XMLSlideShow xml = openPPTX("WithMaster.pptx"); SlideShowExtractor extractor = new SlideShowExtractor<>(xml)) { extractor.setSlidesByDefault(true); extractor.setNotesByDefault(false); @@ -210,10 +210,10 @@ class TestXSLFPowerPointExtractor { "This text comes from the Master Slide\n"; assertEquals(wholeText, text); } - } + } - @Test - void testTable() throws Exception { + @Test + void testTable() throws Exception { try (XMLSlideShow xml = openPPTX("present1.pptx"); SlideShowExtractor extractor = new SlideShowExtractor<>(xml)) { diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFChart.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFChart.java index c9608359bb..4e41ab2e43 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFChart.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFChart.java @@ -147,22 +147,22 @@ class TestXSLFChart { pptx.close(); } - private void fillChartData(XSLFChart chart, XDDFChartData data) { - final int numOfPoints = 3; + private void fillChartData(XSLFChart chart, XDDFChartData data) { + final int numOfPoints = 3; final String[] categories = {"First", "Second", "Third"}; final Integer[] values = {1, 3, 4}; final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0)); final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 1, 1)); - final XDDFChartData.Series series = data.getSeries(0); - final XDDFDataSource categoryData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange); + final XDDFChartData.Series series = data.getSeries(0); + final XDDFDataSource categoryData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange); final XDDFNumericalDataSource valuesData = XDDFDataSourcesFactory.fromArray(values, valuesDataRange); series.replaceData(categoryData, valuesData); final String title = "Apache POI"; series.setTitle(title, chart.setSheetTitle(title, 0)); chart.plot(data); - } + } private XSLFChart findChart(XSLFSlide slide) { // find chart in the slide @@ -188,147 +188,147 @@ class TestXSLFChart { assertEquals(1, data.size()); XDDFChartData firstSeries = data.get(0); - assertNotNull(firstSeries); - if (firstSeries instanceof XDDFScatterChartData) { + assertNotNull(firstSeries); + if (firstSeries instanceof XDDFScatterChartData) { assertNull(firstSeries.getCategoryAxis()); assertEquals(2, firstSeries.getValueAxes().size()); checkAxisOperations(firstSeries.getValueAxes().get(0)); checkAxisOperations(firstSeries.getValueAxes().get(1)); - } else if (!(firstSeries instanceof XDDFPieChartData)) { - assertNotNull(firstSeries.getCategoryAxis()); - assertEquals(1, firstSeries.getValueAxes().size()); - checkAxisOperations(firstSeries.getValueAxes().get(0)); - } + } else if (!(firstSeries instanceof XDDFPieChartData)) { + assertNotNull(firstSeries.getCategoryAxis()); + assertEquals(1, firstSeries.getValueAxes().size()); + checkAxisOperations(firstSeries.getValueAxes().get(0)); + } return data; } - private void checkLegendOperations(XSLFChart chart) { - XDDFChartLegend legend = chart.getOrAddLegend(); + private void checkLegendOperations(XSLFChart chart) { + XDDFChartLegend legend = chart.getOrAddLegend(); assertFalse(legend.isOverlay()); - legend.setOverlay(true); + legend.setOverlay(true); assertTrue(legend.isOverlay()); - legend.setPosition(LegendPosition.TOP_RIGHT); - assertEquals(LegendPosition.TOP_RIGHT, legend.getPosition()); + legend.setPosition(LegendPosition.TOP_RIGHT); + assertEquals(LegendPosition.TOP_RIGHT, legend.getPosition()); - XDDFManualLayout layout = legend.getOrAddManualLayout(); - assertNotNull(layout.getTarget()); - assertNotNull(layout.getXMode()); - assertNotNull(layout.getYMode()); - assertNotNull(layout.getHeightMode()); - assertNotNull(layout.getWidthMode()); - /* - * According to interface, 0.0 should be returned for - * uninitialized double properties. - */ + XDDFManualLayout layout = legend.getOrAddManualLayout(); + assertNotNull(layout.getTarget()); + assertNotNull(layout.getXMode()); + assertNotNull(layout.getYMode()); + assertNotNull(layout.getHeightMode()); + assertNotNull(layout.getWidthMode()); + /* + * According to interface, 0.0 should be returned for + * uninitialized double properties. + */ assertEquals(0.0, layout.getX(), 0.0); assertEquals(0.0, layout.getY(), 0.0); assertEquals(0.0, layout.getWidthRatio(), 0.0); assertEquals(0.0, layout.getHeightRatio(), 0.0); - final double newRatio = 1.1; - final double newCoordinate = 0.3; - final LayoutMode nonDefaultMode = LayoutMode.FACTOR; - final LayoutTarget nonDefaultTarget = LayoutTarget.OUTER; + final double newRatio = 1.1; + final double newCoordinate = 0.3; + final LayoutMode nonDefaultMode = LayoutMode.FACTOR; + final LayoutTarget nonDefaultTarget = LayoutTarget.OUTER; - layout.setWidthRatio(newRatio); + layout.setWidthRatio(newRatio); assertEquals(layout.getWidthRatio(), newRatio, 0.0); - layout.setHeightRatio(newRatio); + layout.setHeightRatio(newRatio); assertEquals(layout.getHeightRatio(), newRatio, 0.0); - layout.setX(newCoordinate); + layout.setX(newCoordinate); assertEquals(layout.getX(), newCoordinate, 0.0); - layout.setY(newCoordinate); + layout.setY(newCoordinate); assertEquals(layout.getY(), newCoordinate, 0.0); - layout.setXMode(nonDefaultMode); + layout.setXMode(nonDefaultMode); assertSame(layout.getXMode(), nonDefaultMode); - layout.setYMode(nonDefaultMode); + layout.setYMode(nonDefaultMode); assertSame(layout.getYMode(), nonDefaultMode); - layout.setWidthMode(nonDefaultMode); + layout.setWidthMode(nonDefaultMode); assertSame(layout.getWidthMode(), nonDefaultMode); - layout.setHeightMode(nonDefaultMode); + layout.setHeightMode(nonDefaultMode); assertSame(layout.getHeightMode(), nonDefaultMode); - layout.setTarget(nonDefaultTarget); + layout.setTarget(nonDefaultTarget); assertSame(layout.getTarget(), nonDefaultTarget); - } + } - private void checkAxisOperations(XDDFValueAxis axis) { - axis.setCrossBetween(AxisCrossBetween.MIDPOINT_CATEGORY); - assertEquals(AxisCrossBetween.MIDPOINT_CATEGORY, axis.getCrossBetween()); + private void checkAxisOperations(XDDFValueAxis axis) { + axis.setCrossBetween(AxisCrossBetween.MIDPOINT_CATEGORY); + assertEquals(AxisCrossBetween.MIDPOINT_CATEGORY, axis.getCrossBetween()); - axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(AxisCrosses.AUTO_ZERO, axis.getCrosses()); + axis.setCrosses(AxisCrosses.AUTO_ZERO); + assertEquals(AxisCrosses.AUTO_ZERO, axis.getCrosses()); - final String numberFormat = "General"; - axis.setNumberFormat(numberFormat); - assertEquals(numberFormat, axis.getNumberFormat()); + final String numberFormat = "General"; + axis.setNumberFormat(numberFormat); + assertEquals(numberFormat, axis.getNumberFormat()); - axis.setPosition(AxisPosition.BOTTOM); - assertEquals(AxisPosition.BOTTOM, axis.getPosition()); + axis.setPosition(AxisPosition.BOTTOM); + assertEquals(AxisPosition.BOTTOM, axis.getPosition()); - axis.setMajorTickMark(AxisTickMark.NONE); - assertEquals(AxisTickMark.NONE, axis.getMajorTickMark()); + axis.setMajorTickMark(AxisTickMark.NONE); + assertEquals(AxisTickMark.NONE, axis.getMajorTickMark()); - axis.setMajorTickMark(AxisTickMark.IN); - assertEquals(AxisTickMark.IN, axis.getMajorTickMark()); + axis.setMajorTickMark(AxisTickMark.IN); + assertEquals(AxisTickMark.IN, axis.getMajorTickMark()); - axis.setMajorTickMark(AxisTickMark.OUT); - assertEquals(AxisTickMark.OUT, axis.getMajorTickMark()); + axis.setMajorTickMark(AxisTickMark.OUT); + assertEquals(AxisTickMark.OUT, axis.getMajorTickMark()); - axis.setMajorTickMark(AxisTickMark.CROSS); - assertEquals(AxisTickMark.CROSS, axis.getMajorTickMark()); + axis.setMajorTickMark(AxisTickMark.CROSS); + assertEquals(AxisTickMark.CROSS, axis.getMajorTickMark()); - axis.setMinorTickMark(AxisTickMark.NONE); - assertEquals(AxisTickMark.NONE, axis.getMinorTickMark()); + axis.setMinorTickMark(AxisTickMark.NONE); + assertEquals(AxisTickMark.NONE, axis.getMinorTickMark()); - axis.setMinorTickMark(AxisTickMark.IN); - assertEquals(AxisTickMark.IN, axis.getMinorTickMark()); + axis.setMinorTickMark(AxisTickMark.IN); + assertEquals(AxisTickMark.IN, axis.getMinorTickMark()); - axis.setMinorTickMark(AxisTickMark.OUT); - assertEquals(AxisTickMark.OUT, axis.getMinorTickMark()); + axis.setMinorTickMark(AxisTickMark.OUT); + assertEquals(AxisTickMark.OUT, axis.getMinorTickMark()); - axis.setMinorTickMark(AxisTickMark.CROSS); - assertEquals(AxisTickMark.CROSS, axis.getMinorTickMark()); + axis.setMinorTickMark(AxisTickMark.CROSS); + assertEquals(AxisTickMark.CROSS, axis.getMinorTickMark()); - axis.setVisible(true); - assertTrue(axis.isVisible()); + axis.setVisible(true); + assertTrue(axis.isVisible()); - axis.setVisible(false); - assertFalse(axis.isVisible()); + axis.setVisible(false); + assertFalse(axis.isVisible()); - final double EPSILON = 1E-7; - axis.setLogBase(Math.E); - assertTrue(Math.abs(axis.getLogBase() - Math.E) < EPSILON); + final double EPSILON = 1E-7; + axis.setLogBase(Math.E); + assertTrue(Math.abs(axis.getLogBase() - Math.E) < EPSILON); - final double newValue = 10.0; + final double newValue = 10.0; - axis.setMinimum(newValue); - assertTrue(Math.abs(axis.getMinimum() - newValue) < EPSILON); + axis.setMinimum(newValue); + assertTrue(Math.abs(axis.getMinimum() - newValue) < EPSILON); - axis.setMaximum(newValue); - assertTrue(Math.abs(axis.getMaximum() - newValue) < EPSILON); + axis.setMaximum(newValue); + assertTrue(Math.abs(axis.getMaximum() - newValue) < EPSILON); - IllegalArgumentException iae = null; - try { - axis.setLogBase(0.0); - } catch (IllegalArgumentException e) { - iae = e; - } - assertNotNull(iae); + IllegalArgumentException iae = null; + try { + axis.setLogBase(0.0); + } catch (IllegalArgumentException e) { + iae = e; + } + assertNotNull(iae); - iae = null; - try { - axis.setLogBase(30000.0); - } catch (IllegalArgumentException e) { - iae = e; - } - assertNotNull(iae); - } + iae = null; + try { + axis.setLogBase(30000.0); + } catch (IllegalArgumentException e) { + iae = e; + } + assertNotNull(iae); + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/TestSheetProtection.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/TestSheetProtection.java index f3459af7dc..303923d33f 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/TestSheetProtection.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/TestSheetProtection.java @@ -28,266 +28,266 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class TestSheetProtection { - private XSSFWorkbook workbook; - private XSSFSheet sheet; + private XSSFWorkbook workbook; + private XSSFSheet sheet; - @BeforeEach - void setUp() { - workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_not_protected.xlsx"); - sheet = workbook.getSheetAt(0); - } + @BeforeEach + void setUp() { + workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_not_protected.xlsx"); + sheet = workbook.getSheetAt(0); + } - @AfterEach - void tearDown() throws IOException { - workbook.close(); - } + @AfterEach + void tearDown() throws IOException { + workbook.close(); + } - @Test - void testShouldReadWorkbookProtection() throws IOException { - assertFalse(sheet.isAutoFilterLocked()); - assertFalse(sheet.isDeleteColumnsLocked()); - assertFalse(sheet.isDeleteRowsLocked()); - assertFalse(sheet.isFormatCellsLocked()); - assertFalse(sheet.isFormatColumnsLocked()); - assertFalse(sheet.isFormatRowsLocked()); - assertFalse(sheet.isInsertColumnsLocked()); - assertFalse(sheet.isInsertHyperlinksLocked()); - assertFalse(sheet.isInsertRowsLocked()); - assertFalse(sheet.isPivotTablesLocked()); - assertFalse(sheet.isSortLocked()); - assertFalse(sheet.isObjectsLocked()); - assertFalse(sheet.isScenariosLocked()); - assertFalse(sheet.isSelectLockedCellsLocked()); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - assertFalse(sheet.isSheetLocked()); + @Test + void testShouldReadWorkbookProtection() throws IOException { + assertFalse(sheet.isAutoFilterLocked()); + assertFalse(sheet.isDeleteColumnsLocked()); + assertFalse(sheet.isDeleteRowsLocked()); + assertFalse(sheet.isFormatCellsLocked()); + assertFalse(sheet.isFormatColumnsLocked()); + assertFalse(sheet.isFormatRowsLocked()); + assertFalse(sheet.isInsertColumnsLocked()); + assertFalse(sheet.isInsertHyperlinksLocked()); + assertFalse(sheet.isInsertRowsLocked()); + assertFalse(sheet.isPivotTablesLocked()); + assertFalse(sheet.isSortLocked()); + assertFalse(sheet.isObjectsLocked()); + assertFalse(sheet.isScenariosLocked()); + assertFalse(sheet.isSelectLockedCellsLocked()); + assertFalse(sheet.isSelectUnlockedCellsLocked()); + assertFalse(sheet.isSheetLocked()); - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx")) { - sheet = workbook.getSheetAt(0); + try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx")) { + sheet = workbook.getSheetAt(0); - assertTrue(sheet.isAutoFilterLocked()); - assertTrue(sheet.isDeleteColumnsLocked()); - assertTrue(sheet.isDeleteRowsLocked()); - assertTrue(sheet.isFormatCellsLocked()); - assertTrue(sheet.isFormatColumnsLocked()); - assertTrue(sheet.isFormatRowsLocked()); - assertTrue(sheet.isInsertColumnsLocked()); - assertTrue(sheet.isInsertHyperlinksLocked()); - assertTrue(sheet.isInsertRowsLocked()); - assertTrue(sheet.isPivotTablesLocked()); - assertTrue(sheet.isSortLocked()); - assertTrue(sheet.isObjectsLocked()); - assertTrue(sheet.isScenariosLocked()); - assertTrue(sheet.isSelectLockedCellsLocked()); - assertTrue(sheet.isSelectUnlockedCellsLocked()); - assertTrue(sheet.isSheetLocked()); - } - } + assertTrue(sheet.isAutoFilterLocked()); + assertTrue(sheet.isDeleteColumnsLocked()); + assertTrue(sheet.isDeleteRowsLocked()); + assertTrue(sheet.isFormatCellsLocked()); + assertTrue(sheet.isFormatColumnsLocked()); + assertTrue(sheet.isFormatRowsLocked()); + assertTrue(sheet.isInsertColumnsLocked()); + assertTrue(sheet.isInsertHyperlinksLocked()); + assertTrue(sheet.isInsertRowsLocked()); + assertTrue(sheet.isPivotTablesLocked()); + assertTrue(sheet.isSortLocked()); + assertTrue(sheet.isObjectsLocked()); + assertTrue(sheet.isScenariosLocked()); + assertTrue(sheet.isSelectLockedCellsLocked()); + assertTrue(sheet.isSelectUnlockedCellsLocked()); + assertTrue(sheet.isSheetLocked()); + } + } - @Test - void testWriteAutoFilter() { - assertFalse(sheet.isAutoFilterLocked()); - sheet.lockAutoFilter(true); - assertFalse(sheet.isAutoFilterLocked()); - sheet.enableLocking(); - assertTrue(sheet.isAutoFilterLocked()); - sheet.lockAutoFilter(false); - assertFalse(sheet.isAutoFilterLocked()); - } + @Test + void testWriteAutoFilter() { + assertFalse(sheet.isAutoFilterLocked()); + sheet.lockAutoFilter(true); + assertFalse(sheet.isAutoFilterLocked()); + sheet.enableLocking(); + assertTrue(sheet.isAutoFilterLocked()); + sheet.lockAutoFilter(false); + assertFalse(sheet.isAutoFilterLocked()); + } - @Test - void testWriteDeleteColumns() { - assertFalse(sheet.isDeleteColumnsLocked()); - sheet.lockDeleteColumns(true); - assertFalse(sheet.isDeleteColumnsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isDeleteColumnsLocked()); - sheet.lockDeleteColumns(false); - assertFalse(sheet.isDeleteColumnsLocked()); - } + @Test + void testWriteDeleteColumns() { + assertFalse(sheet.isDeleteColumnsLocked()); + sheet.lockDeleteColumns(true); + assertFalse(sheet.isDeleteColumnsLocked()); + sheet.enableLocking(); + assertTrue(sheet.isDeleteColumnsLocked()); + sheet.lockDeleteColumns(false); + assertFalse(sheet.isDeleteColumnsLocked()); + } - @Test - void testWriteDeleteRows() { - assertFalse(sheet.isDeleteRowsLocked()); - sheet.lockDeleteRows(true); - assertFalse(sheet.isDeleteRowsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isDeleteRowsLocked()); + @Test + void testWriteDeleteRows() { + assertFalse(sheet.isDeleteRowsLocked()); + sheet.lockDeleteRows(true); + assertFalse(sheet.isDeleteRowsLocked()); + sheet.enableLocking(); + assertTrue(sheet.isDeleteRowsLocked()); sheet.lockDeleteRows(false); assertFalse(sheet.isDeleteRowsLocked()); - } + } - @Test - void testWriteFormatCells() { - assertFalse(sheet.isFormatCellsLocked()); - sheet.lockFormatCells(true); - assertFalse(sheet.isFormatCellsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isFormatCellsLocked()); + @Test + void testWriteFormatCells() { + assertFalse(sheet.isFormatCellsLocked()); + sheet.lockFormatCells(true); + assertFalse(sheet.isFormatCellsLocked()); + sheet.enableLocking(); + assertTrue(sheet.isFormatCellsLocked()); sheet.lockFormatCells(false); assertFalse(sheet.isFormatCellsLocked()); - } + } - @Test - void testWriteFormatColumns() { - assertFalse(sheet.isFormatColumnsLocked()); - sheet.lockFormatColumns(true); - assertFalse(sheet.isFormatColumnsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isFormatColumnsLocked()); + @Test + void testWriteFormatColumns() { + assertFalse(sheet.isFormatColumnsLocked()); + sheet.lockFormatColumns(true); + assertFalse(sheet.isFormatColumnsLocked()); + sheet.enableLocking(); + assertTrue(sheet.isFormatColumnsLocked()); sheet.lockFormatColumns(false); assertFalse(sheet.isFormatColumnsLocked()); - } + } - @Test - void testWriteFormatRows() { - assertFalse(sheet.isFormatRowsLocked()); - sheet.lockFormatRows(true); - assertFalse(sheet.isFormatRowsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isFormatRowsLocked()); + @Test + void testWriteFormatRows() { + assertFalse(sheet.isFormatRowsLocked()); + sheet.lockFormatRows(true); + assertFalse(sheet.isFormatRowsLocked()); + sheet.enableLocking(); + assertTrue(sheet.isFormatRowsLocked()); sheet.lockFormatRows(false); assertFalse(sheet.isFormatRowsLocked()); - } + } - @Test - void testWriteInsertColumns() { - assertFalse(sheet.isInsertColumnsLocked()); - sheet.lockInsertColumns(true); - assertFalse(sheet.isInsertColumnsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isInsertColumnsLocked()); + @Test + void testWriteInsertColumns() { + assertFalse(sheet.isInsertColumnsLocked()); + sheet.lockInsertColumns(true); + assertFalse(sheet.isInsertColumnsLocked()); + sheet.enableLocking(); + assertTrue(sheet.isInsertColumnsLocked()); sheet.lockInsertColumns(false); assertFalse(sheet.isInsertColumnsLocked()); - } + } - @Test - void testWriteInsertHyperlinks() { - assertFalse(sheet.isInsertHyperlinksLocked()); - sheet.lockInsertHyperlinks(true); - assertFalse(sheet.isInsertHyperlinksLocked()); - sheet.enableLocking(); - assertTrue(sheet.isInsertHyperlinksLocked()); + @Test + void testWriteInsertHyperlinks() { + assertFalse(sheet.isInsertHyperlinksLocked()); + sheet.lockInsertHyperlinks(true); + assertFalse(sheet.isInsertHyperlinksLocked()); + sheet.enableLocking(); + assertTrue(sheet.isInsertHyperlinksLocked()); sheet.lockInsertHyperlinks(false); assertFalse(sheet.isInsertHyperlinksLocked()); - } + } - @Test - void testWriteInsertRows() { - assertFalse(sheet.isInsertRowsLocked()); - sheet.lockInsertRows(true); - assertFalse(sheet.isInsertRowsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isInsertRowsLocked()); + @Test + void testWriteInsertRows() { + assertFalse(sheet.isInsertRowsLocked()); + sheet.lockInsertRows(true); + assertFalse(sheet.isInsertRowsLocked()); + sheet.enableLocking(); + assertTrue(sheet.isInsertRowsLocked()); sheet.lockInsertRows(false); assertFalse(sheet.isInsertRowsLocked()); - } + } - @Test - void testWritePivotTables() { - assertFalse(sheet.isPivotTablesLocked()); - sheet.lockPivotTables(true); - assertFalse(sheet.isPivotTablesLocked()); - sheet.enableLocking(); - assertTrue(sheet.isPivotTablesLocked()); + @Test + void testWritePivotTables() { + assertFalse(sheet.isPivotTablesLocked()); + sheet.lockPivotTables(true); + assertFalse(sheet.isPivotTablesLocked()); + sheet.enableLocking(); + assertTrue(sheet.isPivotTablesLocked()); sheet.lockPivotTables(false); assertFalse(sheet.isPivotTablesLocked()); - } + } - @Test - void testWriteSort() { - assertFalse(sheet.isSortLocked()); - sheet.lockSort(true); - assertFalse(sheet.isSortLocked()); - sheet.enableLocking(); - assertTrue(sheet.isSortLocked()); + @Test + void testWriteSort() { + assertFalse(sheet.isSortLocked()); + sheet.lockSort(true); + assertFalse(sheet.isSortLocked()); + sheet.enableLocking(); + assertTrue(sheet.isSortLocked()); sheet.lockSort(false); assertFalse(sheet.isSortLocked()); - } + } - @Test - void testWriteObjects() { - assertFalse(sheet.isObjectsLocked()); - sheet.lockObjects(true); - assertFalse(sheet.isObjectsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isObjectsLocked()); + @Test + void testWriteObjects() { + assertFalse(sheet.isObjectsLocked()); + sheet.lockObjects(true); + assertFalse(sheet.isObjectsLocked()); + sheet.enableLocking(); + assertTrue(sheet.isObjectsLocked()); sheet.lockObjects(false); assertFalse(sheet.isObjectsLocked()); - } + } - @Test - void testWriteScenarios() { - assertFalse(sheet.isScenariosLocked()); - sheet.lockScenarios(true); - assertFalse(sheet.isScenariosLocked()); - sheet.enableLocking(); - assertTrue(sheet.isScenariosLocked()); + @Test + void testWriteScenarios() { + assertFalse(sheet.isScenariosLocked()); + sheet.lockScenarios(true); + assertFalse(sheet.isScenariosLocked()); + sheet.enableLocking(); + assertTrue(sheet.isScenariosLocked()); sheet.lockScenarios(false); assertFalse(sheet.isScenariosLocked()); - } + } - @Test - void testWriteSelectLockedCells() { - assertFalse(sheet.isSelectLockedCellsLocked()); - sheet.lockSelectLockedCells(true); - assertFalse(sheet.isSelectLockedCellsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isSelectLockedCellsLocked()); + @Test + void testWriteSelectLockedCells() { + assertFalse(sheet.isSelectLockedCellsLocked()); + sheet.lockSelectLockedCells(true); + assertFalse(sheet.isSelectLockedCellsLocked()); + sheet.enableLocking(); + assertTrue(sheet.isSelectLockedCellsLocked()); sheet.lockSelectLockedCells(false); assertFalse(sheet.isSelectLockedCellsLocked()); - } + } - @Test - void testWriteSelectUnlockedCells() { - assertFalse(sheet.isSelectUnlockedCellsLocked()); - sheet.lockSelectUnlockedCells(true); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isSelectUnlockedCellsLocked()); + @Test + void testWriteSelectUnlockedCells() { + assertFalse(sheet.isSelectUnlockedCellsLocked()); + sheet.lockSelectUnlockedCells(true); + assertFalse(sheet.isSelectUnlockedCellsLocked()); + sheet.enableLocking(); + assertTrue(sheet.isSelectUnlockedCellsLocked()); sheet.lockSelectUnlockedCells(false); assertFalse(sheet.isSelectUnlockedCellsLocked()); - } + } - @Test - void testWriteSelectEnableLocking() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx")) { - sheet = workbook.getSheetAt(0); + @Test + void testWriteSelectEnableLocking() throws IOException { + try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx")) { + sheet = workbook.getSheetAt(0); - assertTrue(sheet.isAutoFilterLocked()); - assertTrue(sheet.isDeleteColumnsLocked()); - assertTrue(sheet.isDeleteRowsLocked()); - assertTrue(sheet.isFormatCellsLocked()); - assertTrue(sheet.isFormatColumnsLocked()); - assertTrue(sheet.isFormatRowsLocked()); - assertTrue(sheet.isInsertColumnsLocked()); - assertTrue(sheet.isInsertHyperlinksLocked()); - assertTrue(sheet.isInsertRowsLocked()); - assertTrue(sheet.isPivotTablesLocked()); - assertTrue(sheet.isSortLocked()); - assertTrue(sheet.isObjectsLocked()); - assertTrue(sheet.isScenariosLocked()); - assertTrue(sheet.isSelectLockedCellsLocked()); - assertTrue(sheet.isSelectUnlockedCellsLocked()); - assertTrue(sheet.isSheetLocked()); + assertTrue(sheet.isAutoFilterLocked()); + assertTrue(sheet.isDeleteColumnsLocked()); + assertTrue(sheet.isDeleteRowsLocked()); + assertTrue(sheet.isFormatCellsLocked()); + assertTrue(sheet.isFormatColumnsLocked()); + assertTrue(sheet.isFormatRowsLocked()); + assertTrue(sheet.isInsertColumnsLocked()); + assertTrue(sheet.isInsertHyperlinksLocked()); + assertTrue(sheet.isInsertRowsLocked()); + assertTrue(sheet.isPivotTablesLocked()); + assertTrue(sheet.isSortLocked()); + assertTrue(sheet.isObjectsLocked()); + assertTrue(sheet.isScenariosLocked()); + assertTrue(sheet.isSelectLockedCellsLocked()); + assertTrue(sheet.isSelectUnlockedCellsLocked()); + assertTrue(sheet.isSheetLocked()); - sheet.disableLocking(); + sheet.disableLocking(); - assertFalse(sheet.isAutoFilterLocked()); - assertFalse(sheet.isDeleteColumnsLocked()); - assertFalse(sheet.isDeleteRowsLocked()); - assertFalse(sheet.isFormatCellsLocked()); - assertFalse(sheet.isFormatColumnsLocked()); - assertFalse(sheet.isFormatRowsLocked()); - assertFalse(sheet.isInsertColumnsLocked()); - assertFalse(sheet.isInsertHyperlinksLocked()); - assertFalse(sheet.isInsertRowsLocked()); - assertFalse(sheet.isPivotTablesLocked()); - assertFalse(sheet.isSortLocked()); - assertFalse(sheet.isObjectsLocked()); - assertFalse(sheet.isScenariosLocked()); - assertFalse(sheet.isSelectLockedCellsLocked()); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - assertFalse(sheet.isSheetLocked()); - } - } + assertFalse(sheet.isAutoFilterLocked()); + assertFalse(sheet.isDeleteColumnsLocked()); + assertFalse(sheet.isDeleteRowsLocked()); + assertFalse(sheet.isFormatCellsLocked()); + assertFalse(sheet.isFormatColumnsLocked()); + assertFalse(sheet.isFormatRowsLocked()); + assertFalse(sheet.isInsertColumnsLocked()); + assertFalse(sheet.isInsertHyperlinksLocked()); + assertFalse(sheet.isInsertRowsLocked()); + assertFalse(sheet.isPivotTablesLocked()); + assertFalse(sheet.isSortLocked()); + assertFalse(sheet.isObjectsLocked()); + assertFalse(sheet.isScenariosLocked()); + assertFalse(sheet.isSelectLockedCellsLocked()); + assertFalse(sheet.isSelectUnlockedCellsLocked()); + assertFalse(sheet.isSheetLocked()); + } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java index 3d59980c05..6b814589e4 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java @@ -42,7 +42,7 @@ public final class TestReadOnlySharedStringsTable { @Test void testParse() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { List parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml")); assertEquals(1, parts.size()); @@ -60,11 +60,11 @@ public final class TestReadOnlySharedStringsTable { assertEquals(i1.getString(), i2.getString()); } } - } + } - //51519 + //51519 @Test - void testPhoneticRuns() throws Exception { + void testPhoneticRuns() throws Exception { try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("51519.xlsx"))) { List < PackagePart > parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml")); assertEquals(1, parts.size()); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java index 766ebeb0ef..bb7d6e3342 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java @@ -61,7 +61,7 @@ public final class TestXSSFReader { @Test void testGetBits() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { XSSFReader r = new XSSFReader(pkg); @@ -72,11 +72,11 @@ public final class TestXSSFReader { assertNotNull(r.getSharedStringsTable()); assertNotNull(r.getStylesTable()); } - } + } @Test - void testStyles() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { + void testStyles() throws Exception { + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { XSSFReader r = new XSSFReader(pkg); @@ -90,10 +90,10 @@ public final class TestXSSFReader { assertNotNull(r.getStylesData()); assertNotNull(r.getThemesData()); } - } + } @Test - void testStrings() throws Exception { + void testStrings() throws Exception { try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { XSSFReader r = new XSSFReader(pkg); @@ -101,10 +101,10 @@ public final class TestXSSFReader { assertEquals(11, r.getSharedStringsTable().getSharedStringItems().size()); assertEquals("Test spreadsheet", r.getSharedStringsTable().getItemAt(0).toString()); } - } + } @Test - void testSheets() throws Exception { + void testSheets() throws Exception { try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { XSSFReader r = new XSSFReader(pkg); @@ -131,14 +131,14 @@ public final class TestXSSFReader { } assertEquals(3, count); } - } + } - /** - * Check that the sheet iterator returns sheets in the logical order - * (as they are defined in the workbook.xml) - */ + /** + * Check that the sheet iterator returns sheets in the logical order + * (as they are defined in the workbook.xml) + */ @Test - void testOrderOfSheets() throws Exception { + void testOrderOfSheets() throws Exception { try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("reordered_sheets.xlsx"))) { XSSFReader r = new XSSFReader(pkg); @@ -157,10 +157,10 @@ public final class TestXSSFReader { } assertEquals(4, count); } - } + } @Test - void testComments() throws Exception { + void testComments() throws Exception { try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("comments.xlsx")) { XSSFReader r = new XSSFReader(pkg); XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); @@ -182,7 +182,7 @@ public final class TestXSSFReader { } assertEquals(3, count); } - } + } /** * Iterating over a workbook with chart sheets in it, using the diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java index 8cd773a2e9..c5fc21315b 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java @@ -71,10 +71,10 @@ class TestXSSFBEventBasedExcelExtractor { "Nunc\t999\n"; String CHUNK2 = "The quick brown fox jumps over the lazy dog\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n"; + "hello, xssf hello, xssf\n" + + "hello, xssf hello, xssf\n" + + "hello, xssf hello, xssf\n" + + "hello, xssf hello, xssf\n"; assertEquals( CHUNK1 + "at\t4995\n" + diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java index 0de3611bc1..7de9184e85 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java @@ -39,92 +39,92 @@ import org.junit.jupiter.api.Test; * Tests for {@link XSSFEventBasedExcelExtractor} */ class TestXSSFEventBasedExcelExtractor { - protected XSSFEventBasedExcelExtractor getExtractor(String sampleName) throws Exception { + protected XSSFEventBasedExcelExtractor getExtractor(String sampleName) throws Exception { return new XSSFEventBasedExcelExtractor(XSSFTestDataSamples. openSamplePackage(sampleName)); - } + } - /** - * Get text out of the simple file - */ - @Test - void testGetSimpleText() throws Exception { - // a very simple file - XSSFEventBasedExcelExtractor extractor = getExtractor("sample.xlsx"); - extractor.getText(); + /** + * Get text out of the simple file + */ + @Test + void testGetSimpleText() throws Exception { + // a very simple file + XSSFEventBasedExcelExtractor extractor = getExtractor("sample.xlsx"); + extractor.getText(); - String text = extractor.getText(); - assertTrue(text.length() > 0); + String text = extractor.getText(); + assertTrue(text.length() > 0); - // Check sheet names - assertStartsWith(text, "Sheet1"); - assertEndsWith(text, "Sheet3\n"); + // Check sheet names + assertStartsWith(text, "Sheet1"); + assertEndsWith(text, "Sheet3\n"); - // Now without, will have text - extractor.setIncludeSheetNames(false); - text = extractor.getText(); - String CHUNK1 = - "Lorem\t111\n" + - "ipsum\t222\n" + - "dolor\t333\n" + - "sit\t444\n" + - "amet\t555\n" + - "consectetuer\t666\n" + - "adipiscing\t777\n" + - "elit\t888\n" + - "Nunc\t999\n"; - String CHUNK2 = - "The quick brown fox jumps over the lazy dog\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n"; - assertEquals( - CHUNK1 + - "at\t4995\n" + - CHUNK2 - , text); + // Now without, will have text + extractor.setIncludeSheetNames(false); + text = extractor.getText(); + String CHUNK1 = + "Lorem\t111\n" + + "ipsum\t222\n" + + "dolor\t333\n" + + "sit\t444\n" + + "amet\t555\n" + + "consectetuer\t666\n" + + "adipiscing\t777\n" + + "elit\t888\n" + + "Nunc\t999\n"; + String CHUNK2 = + "The quick brown fox jumps over the lazy dog\n" + + "hello, xssf hello, xssf\n" + + "hello, xssf hello, xssf\n" + + "hello, xssf hello, xssf\n" + + "hello, xssf hello, xssf\n"; + assertEquals( + CHUNK1 + + "at\t4995\n" + + CHUNK2 + , text); - // Now get formulas not their values - extractor.setFormulasNotResults(true); - text = extractor.getText(); - assertEquals( - CHUNK1 + - "at\tSUM(B1:B9)\n" + - CHUNK2, text); + // Now get formulas not their values + extractor.setFormulasNotResults(true); + text = extractor.getText(); + assertEquals( + CHUNK1 + + "at\tSUM(B1:B9)\n" + + CHUNK2, text); - // With sheet names too - extractor.setIncludeSheetNames(true); - text = extractor.getText(); - assertEquals( - "Sheet1\n" + - CHUNK1 + - "at\tSUM(B1:B9)\n" + - "rich test\n" + - CHUNK2 + - "Sheet3\n" - , text); + // With sheet names too + extractor.setIncludeSheetNames(true); + text = extractor.getText(); + assertEquals( + "Sheet1\n" + + CHUNK1 + + "at\tSUM(B1:B9)\n" + + "rich test\n" + + CHUNK2 + + "Sheet3\n" + , text); - extractor.close(); - } + extractor.close(); + } @Test - void testGetComplexText() throws Exception { - // A fairly complex file - XSSFEventBasedExcelExtractor extractor = getExtractor("AverageTaxRates.xlsx"); - extractor.getText(); + void testGetComplexText() throws Exception { + // A fairly complex file + XSSFEventBasedExcelExtractor extractor = getExtractor("AverageTaxRates.xlsx"); + extractor.getText(); - String text = extractor.getText(); - assertTrue(text.length() > 0); + String text = extractor.getText(); + assertTrue(text.length() > 0); - // Might not have all formatting it should do! - assertStartsWith(text, - "Avgtxfull\n" + - "(iii) AVERAGE TAX RATES ON ANNUAL" - ); + // Might not have all formatting it should do! + assertStartsWith(text, + "Avgtxfull\n" + + "(iii) AVERAGE TAX RATES ON ANNUAL" + ); - extractor.close(); - } + extractor.close(); + } @Test void testInlineStrings() throws Exception { @@ -141,44 +141,44 @@ class TestXSSFEventBasedExcelExtractor { assertContains(text, "Long Text"); // Inline Strings - assertContains(text, "1st Inline String"); - assertContains(text, "And More"); + assertContains(text, "1st Inline String"); + assertContains(text, "And More"); // Formulas - assertContains(text, "A2"); - assertContains(text, "A5-A$2"); + assertContains(text, "A2"); + assertContains(text, "A5-A$2"); extractor.close(); } - /** - * Test that we return pretty much the same as - * ExcelExtractor does, when we're both passed - * the same file, just saved as xls and xlsx - */ + /** + * Test that we return pretty much the same as + * ExcelExtractor does, when we're both passed + * the same file, just saved as xls and xlsx + */ @Test void testComparedToOLE2() throws Exception { - // A fairly simple file - ooxml - XSSFEventBasedExcelExtractor ooxmlExtractor = getExtractor("SampleSS.xlsx"); + // A fairly simple file - ooxml + XSSFEventBasedExcelExtractor ooxmlExtractor = getExtractor("SampleSS.xlsx"); - ExcelExtractor ole2Extractor = - new ExcelExtractor(HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")); + ExcelExtractor ole2Extractor = + new ExcelExtractor(HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")); - POITextExtractor[] extractors = - new POITextExtractor[] { ooxmlExtractor, ole2Extractor }; - for (POITextExtractor extractor : extractors) { + POITextExtractor[] extractors = + new POITextExtractor[] { ooxmlExtractor, ole2Extractor }; + for (POITextExtractor extractor : extractors) { String text = extractor.getText().replaceAll("[\r\t]", ""); - assertStartsWith(text, "First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n"); - Pattern pattern = Pattern.compile(".*13(\\.0+)?\\s+Sheet3.*", Pattern.DOTALL); - Matcher m = pattern.matcher(text); - assertTrue(m.matches()); - } + assertStartsWith(text, "First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n"); + Pattern pattern = Pattern.compile(".*13(\\.0+)?\\s+Sheet3.*", Pattern.DOTALL); + Matcher m = pattern.matcher(text); + assertTrue(m.matches()); + } - ole2Extractor.close(); - ooxmlExtractor.close(); - } + ole2Extractor.close(); + ooxmlExtractor.close(); + } - /** Test text extraction from text box using getShapes() */ + /** Test text extraction from text box using getShapes() */ @Test void testShapes() throws Exception{ @@ -320,35 +320,35 @@ class TestXSSFEventBasedExcelExtractor { } @Test - void test59021() throws Exception { - XSSFEventBasedExcelExtractor ex = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("59021.xlsx")); - String text = ex.getText(); - assertContains(text, "Abkhazia - Fixed"); - assertContains(text, "10/02/2016"); - ex.close(); - } + void test59021() throws Exception { + XSSFEventBasedExcelExtractor ex = + new XSSFEventBasedExcelExtractor( + XSSFTestDataSamples.openSamplePackage("59021.xlsx")); + String text = ex.getText(); + assertContains(text, "Abkhazia - Fixed"); + assertContains(text, "10/02/2016"); + ex.close(); + } - @Test - void test51519() throws Exception { - //default behavior: include phonetic runs - XSSFEventBasedExcelExtractor ex = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("51519.xlsx")); - String text = ex.getText(); - assertContains(text, "\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3"); - ex.close(); + @Test + void test51519() throws Exception { + //default behavior: include phonetic runs + XSSFEventBasedExcelExtractor ex = + new XSSFEventBasedExcelExtractor( + XSSFTestDataSamples.openSamplePackage("51519.xlsx")); + String text = ex.getText(); + assertContains(text, "\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3"); + ex.close(); - //now try turning them off - ex = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("51519.xlsx")); - ex.setConcatenatePhoneticRuns(false); - text = ex.getText(); - assertFalse(text.contains("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3"), - "should not be able to find appended phonetic run"); - ex.close(); + //now try turning them off + ex = + new XSSFEventBasedExcelExtractor( + XSSFTestDataSamples.openSamplePackage("51519.xlsx")); + ex.setConcatenatePhoneticRuns(false); + text = ex.getText(); + assertFalse(text.contains("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3"), + "should not be able to find appended phonetic run"); + ex.close(); - } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java index 3dd4b83039..0394a0ea63 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java @@ -22,15 +22,15 @@ import org.junit.jupiter.api.AfterEach; class TestXSSFEventBasedExcelExtractorUsingFactory extends TestXSSFEventBasedExcelExtractor { - @Override - protected final XSSFEventBasedExcelExtractor getExtractor(String sampleName) throws Exception { - ExtractorFactory.setAllThreadsPreferEventExtractors(true); - return (XSSFEventBasedExcelExtractor) ExtractorFactory.createExtractor(HSSFTestDataSamples.openSampleFileStream(sampleName)); - } + @Override + protected final XSSFEventBasedExcelExtractor getExtractor(String sampleName) throws Exception { + ExtractorFactory.setAllThreadsPreferEventExtractors(true); + return (XSSFEventBasedExcelExtractor) ExtractorFactory.createExtractor(HSSFTestDataSamples.openSampleFileStream(sampleName)); + } - @AfterEach + @AfterEach void tearDown() { - // reset setting to not affect other tests - ExtractorFactory.setAllThreadsPreferEventExtractors(null); - } + // reset setting to not affect other tests + ExtractorFactory.setAllThreadsPreferEventExtractors(null); + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java index 2068a4a993..7249881e34 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java @@ -41,164 +41,164 @@ import org.junit.jupiter.api.Test; * Tests for {@link XSSFExcelExtractor} */ class TestXSSFExcelExtractor { - protected XSSFExcelExtractor getExtractor(String sampleName) { - return new XSSFExcelExtractor(XSSFTestDataSamples.openSampleWorkbook(sampleName)); - } + protected XSSFExcelExtractor getExtractor(String sampleName) { + return new XSSFExcelExtractor(XSSFTestDataSamples.openSampleWorkbook(sampleName)); + } - /** - * Get text out of the simple file - */ - @Test - void testGetSimpleText() throws IOException { - // a very simple file - XSSFExcelExtractor extractor = getExtractor("sample.xlsx"); + /** + * Get text out of the simple file + */ + @Test + void testGetSimpleText() throws IOException { + // a very simple file + XSSFExcelExtractor extractor = getExtractor("sample.xlsx"); - String text = extractor.getText(); - assertTrue(text.length() > 0); + String text = extractor.getText(); + assertTrue(text.length() > 0); - // Check sheet names - assertStartsWith(text, "Sheet1"); - assertEndsWith(text, "Sheet3\n"); + // Check sheet names + assertStartsWith(text, "Sheet1"); + assertEndsWith(text, "Sheet3\n"); - // Now without, will have text - extractor.setIncludeSheetNames(false); - text = extractor.getText(); - String CHUNK1 = - "Lorem\t111\n" + - "ipsum\t222\n" + - "dolor\t333\n" + - "sit\t444\n" + - "amet\t555\n" + - "consectetuer\t666\n" + - "adipiscing\t777\n" + - "elit\t888\n" + - "Nunc\t999\n"; - String CHUNK2 = - "The quick brown fox jumps over the lazy dog\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n"; - assertEquals( - CHUNK1 + - "at\t4995\n" + - CHUNK2 - , text); + // Now without, will have text + extractor.setIncludeSheetNames(false); + text = extractor.getText(); + String CHUNK1 = + "Lorem\t111\n" + + "ipsum\t222\n" + + "dolor\t333\n" + + "sit\t444\n" + + "amet\t555\n" + + "consectetuer\t666\n" + + "adipiscing\t777\n" + + "elit\t888\n" + + "Nunc\t999\n"; + String CHUNK2 = + "The quick brown fox jumps over the lazy dog\n" + + "hello, xssf hello, xssf\n" + + "hello, xssf hello, xssf\n" + + "hello, xssf hello, xssf\n" + + "hello, xssf hello, xssf\n"; + assertEquals( + CHUNK1 + + "at\t4995\n" + + CHUNK2 + , text); - // Now get formulas not their values - extractor.setFormulasNotResults(true); - text = extractor.getText(); - assertEquals( - CHUNK1 + - "at\tSUM(B1:B9)\n" + - CHUNK2, text); + // Now get formulas not their values + extractor.setFormulasNotResults(true); + text = extractor.getText(); + assertEquals( + CHUNK1 + + "at\tSUM(B1:B9)\n" + + CHUNK2, text); - // With sheet names too - extractor.setIncludeSheetNames(true); - text = extractor.getText(); - assertEquals( - "Sheet1\n" + - CHUNK1 + - "at\tSUM(B1:B9)\n" + - "rich test\n" + - CHUNK2 + - "Sheet3\n" - , text); + // With sheet names too + extractor.setIncludeSheetNames(true); + text = extractor.getText(); + assertEquals( + "Sheet1\n" + + CHUNK1 + + "at\tSUM(B1:B9)\n" + + "rich test\n" + + CHUNK2 + + "Sheet3\n" + , text); - extractor.close(); - } + extractor.close(); + } - @Test - void testGetComplexText() throws IOException { - // A fairly complex file - XSSFExcelExtractor extractor = getExtractor("AverageTaxRates.xlsx"); + @Test + void testGetComplexText() throws IOException { + // A fairly complex file + XSSFExcelExtractor extractor = getExtractor("AverageTaxRates.xlsx"); - String text = extractor.getText(); - assertTrue(text.length() > 0); + String text = extractor.getText(); + assertTrue(text.length() > 0); - // Might not have all formatting it should do! - assertStartsWith(text, - "Avgtxfull\n" + - "\t(iii) AVERAGE TAX RATES ON ANNUAL" - ); + // Might not have all formatting it should do! + assertStartsWith(text, + "Avgtxfull\n" + + "\t(iii) AVERAGE TAX RATES ON ANNUAL" + ); - extractor.close(); - } + extractor.close(); + } - /** - * Test that we return pretty much the same as - * ExcelExtractor does, when we're both passed - * the same file, just saved as xls and xlsx - */ - @Test - void testComparedToOLE2() throws IOException { - // A fairly simple file - ooxml - XSSFExcelExtractor ooxmlExtractor = getExtractor("SampleSS.xlsx"); + /** + * Test that we return pretty much the same as + * ExcelExtractor does, when we're both passed + * the same file, just saved as xls and xlsx + */ + @Test + void testComparedToOLE2() throws IOException { + // A fairly simple file - ooxml + XSSFExcelExtractor ooxmlExtractor = getExtractor("SampleSS.xlsx"); - ExcelExtractor ole2Extractor = - new ExcelExtractor(HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")); + ExcelExtractor ole2Extractor = + new ExcelExtractor(HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")); - Map extractors = new HashMap<>(); - extractors.put("SampleSS.xlsx", ooxmlExtractor); - extractors.put("SampleSS.xls", ole2Extractor); + Map extractors = new HashMap<>(); + extractors.put("SampleSS.xlsx", ooxmlExtractor); + extractors.put("SampleSS.xls", ole2Extractor); - for (final Entry e : extractors.entrySet()) { - String filename = e.getKey(); - POITextExtractor extractor = e.getValue(); - String text = extractor.getText().replaceAll("[\r\t]", ""); - assertStartsWith(filename, text, "First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n"); - Pattern pattern = Pattern.compile(".*13(\\.0+)?\\s+Sheet3.*", Pattern.DOTALL); - Matcher m = pattern.matcher(text); - assertTrue(m.matches(), filename); - } + for (final Entry e : extractors.entrySet()) { + String filename = e.getKey(); + POITextExtractor extractor = e.getValue(); + String text = extractor.getText().replaceAll("[\r\t]", ""); + assertStartsWith(filename, text, "First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n"); + Pattern pattern = Pattern.compile(".*13(\\.0+)?\\s+Sheet3.*", Pattern.DOTALL); + Matcher m = pattern.matcher(text); + assertTrue(m.matches(), filename); + } - ole2Extractor.close(); - ooxmlExtractor.close(); - } + ole2Extractor.close(); + ooxmlExtractor.close(); + } - /** - * From bug #45540 - */ - @Test - void testHeaderFooter() throws IOException { - String[] files = new String[] { - "45540_classic_Header.xlsx", "45540_form_Header.xlsx", - "45540_classic_Footer.xlsx", "45540_form_Footer.xlsx", - }; - for(String sampleName : files) { - XSSFExcelExtractor extractor = getExtractor(sampleName); - String text = extractor.getText(); + /** + * From bug #45540 + */ + @Test + void testHeaderFooter() throws IOException { + String[] files = new String[] { + "45540_classic_Header.xlsx", "45540_form_Header.xlsx", + "45540_classic_Footer.xlsx", "45540_form_Footer.xlsx", + }; + for(String sampleName : files) { + XSSFExcelExtractor extractor = getExtractor(sampleName); + String text = extractor.getText(); - assertContains(sampleName, text, "testdoc"); - assertContains(sampleName, text, "test phrase"); + assertContains(sampleName, text, "testdoc"); + assertContains(sampleName, text, "test phrase"); - extractor.close(); - } - } + extractor.close(); + } + } - /** - * From bug #45544 - */ - @Test - void testComments() throws IOException { - XSSFExcelExtractor extractor = getExtractor("45544.xlsx"); - String text = extractor.getText(); + /** + * From bug #45544 + */ + @Test + void testComments() throws IOException { + XSSFExcelExtractor extractor = getExtractor("45544.xlsx"); + String text = extractor.getText(); - // No comments there yet - assertNotContained(text, "testdoc"); - assertNotContained(text, "test phrase"); + // No comments there yet + assertNotContained(text, "testdoc"); + assertNotContained(text, "test phrase"); - // Turn on comment extraction, will then be - extractor.setIncludeCellComments(true); - text = extractor.getText(); - assertContains(text, "testdoc"); - assertContains(text, "test phrase"); + // Turn on comment extraction, will then be + extractor.setIncludeCellComments(true); + text = extractor.getText(); + assertContains(text, "testdoc"); + assertContains(text, "test phrase"); - extractor.close(); - } + extractor.close(); + } - @Test - void testInlineStrings() throws IOException { + @Test + void testInlineStrings() throws IOException { XSSFExcelExtractor extractor = getExtractor("InlineStrings.xlsx"); extractor.setFormulasNotResults(true); String text = extractor.getText(); @@ -220,13 +220,13 @@ class TestXSSFExcelExtractor { assertContains(text, "A5-A$2"); extractor.close(); - } + } - /** - * Simple test for text box text - */ - @Test - void testTextBoxes() throws IOException { + /** + * Simple test for text box text + */ + @Test + void testTextBoxes() throws IOException { try (XSSFExcelExtractor extractor = getExtractor("WithTextBox.xlsx")) { extractor.setFormulasNotResults(true); String text = extractor.getText(); @@ -234,10 +234,10 @@ class TestXSSFExcelExtractor { assertContains(text, "Line 2"); assertContains(text, "Line 3"); } - } + } - @Test - void testPhoneticRuns() throws Exception { + @Test + void testPhoneticRuns() throws Exception { try (XSSFExcelExtractor extractor = getExtractor("51519.xlsx")) { String text = extractor.getText(); assertContains(text, "\u8C4A\u7530"); @@ -246,5 +246,5 @@ class TestXSSFExcelExtractor { assertNotContained(text, "\u30CB\u30DB\u30F3"); } - } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java index 4ef8030119..4fd6033dd4 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java @@ -25,16 +25,16 @@ import org.junit.jupiter.api.AfterEach; * Tests for {@link XSSFExcelExtractor} */ public final class TestXSSFExcelExtractorUsingFactory extends TestXSSFExcelExtractor { - @Override - protected final XSSFExcelExtractor getExtractor(String sampleName) { - ExtractorFactory.setAllThreadsPreferEventExtractors(false); - ExtractorFactory.setThreadPrefersEventExtractors(false); - try { - return (XSSFExcelExtractor) ExtractorFactory.createExtractor(HSSFTestDataSamples.openSampleFileStream(sampleName)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + @Override + protected final XSSFExcelExtractor getExtractor(String sampleName) { + ExtractorFactory.setAllThreadsPreferEventExtractors(false); + ExtractorFactory.setThreadPrefersEventExtractors(false); + try { + return (XSSFExcelExtractor) ExtractorFactory.createExtractor(HSSFTestDataSamples.openSampleFileStream(sampleName)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } @AfterEach void tearDown() { diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestOutlining.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestOutlining.java index 2132956a66..b8a15b8ea0 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestOutlining.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestOutlining.java @@ -35,48 +35,48 @@ import org.junit.jupiter.api.Test; public final class TestOutlining { @Test - void testSetRowGroupCollapsed() throws IOException { - SXSSFWorkbook wb2 = new SXSSFWorkbook(100); - wb2.setCompressTempFiles(true); - SXSSFSheet sheet2 = wb2.createSheet("new sheet"); + void testSetRowGroupCollapsed() throws IOException { + SXSSFWorkbook wb2 = new SXSSFWorkbook(100); + wb2.setCompressTempFiles(true); + SXSSFSheet sheet2 = wb2.createSheet("new sheet"); - int rowCount = 20; - for (int i = 0; i < rowCount; i++) { - sheet2.createRow(i); - } + int rowCount = 20; + for (int i = 0; i < rowCount; i++) { + sheet2.createRow(i); + } - sheet2.groupRow(4, 9); - sheet2.groupRow(11, 19); + sheet2.groupRow(4, 9); + sheet2.groupRow(11, 19); - sheet2.setRowGroupCollapsed(4, true); + sheet2.setRowGroupCollapsed(4, true); - SXSSFRow r = sheet2.getRow(8); - assertTrue(r.getHidden()); - r = sheet2.getRow(10); - assertTrue(r.getCollapsed()); - r = sheet2.getRow(12); - assertNull(r.getHidden()); - wb2.dispose(); + SXSSFRow r = sheet2.getRow(8); + assertTrue(r.getHidden()); + r = sheet2.getRow(10); + assertTrue(r.getCollapsed()); + r = sheet2.getRow(12); + assertNull(r.getHidden()); + wb2.dispose(); - wb2.close(); - } + wb2.close(); + } @Test void testSetRowGroupCollapsedError() throws IOException { - SXSSFWorkbook wb2 = new SXSSFWorkbook(100); - wb2.setCompressTempFiles(true); - SXSSFSheet sheet2 = wb2.createSheet("new sheet"); + SXSSFWorkbook wb2 = new SXSSFWorkbook(100); + wb2.setCompressTempFiles(true); + SXSSFSheet sheet2 = wb2.createSheet("new sheet"); - int rowCount = 20; - for (int i = 0; i < rowCount; i++) { - sheet2.createRow(i); - } + int rowCount = 20; + for (int i = 0; i < rowCount; i++) { + sheet2.createRow(i); + } - sheet2.groupRow(4, 9); - sheet2.groupRow(11, 19); + sheet2.groupRow(4, 9); + sheet2.groupRow(11, 19); IllegalArgumentException e; - e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(3, true)); + e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(3, true)); assertTrue(e.getMessage().contains("row (3)")); e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(10, true)); @@ -88,17 +88,17 @@ public final class TestOutlining { e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(20, true)); assertTrue(e.getMessage().contains("Row does not exist"), "Had: " + e.getMessage()); - SXSSFRow r = sheet2.getRow(8); - assertNotNull(r); - assertNull(r.getHidden()); - r = sheet2.getRow(10); - assertNull(r.getCollapsed()); - r = sheet2.getRow(12); - assertNull(r.getHidden()); - wb2.dispose(); + SXSSFRow r = sheet2.getRow(8); + assertNotNull(r); + assertNull(r.getHidden()); + r = sheet2.getRow(10); + assertNull(r.getCollapsed()); + r = sheet2.getRow(12); + assertNull(r.getHidden()); + wb2.dispose(); - wb2.close(); - } + wb2.close(); + } @Test void testOutlineGettersHSSF() throws IOException { diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java index 88bf9b417d..982c5e7373 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java @@ -98,23 +98,23 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { @Test void existingWorkbook() throws IOException { - XSSFWorkbook xssfWb1 = new XSSFWorkbook(); - xssfWb1.createSheet("S1"); + XSSFWorkbook xssfWb1 = new XSSFWorkbook(); + xssfWb1.createSheet("S1"); SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1); - XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); - assertTrue(wb1.dispose()); + XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); + assertTrue(wb1.dispose()); SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2); - assertEquals(1, wb2.getNumberOfSheets()); - Sheet sheet = wb2.getSheetAt(0); - assertNotNull(sheet); - assertEquals("S1", sheet.getSheetName()); - assertTrue(wb2.dispose()); - xssfWb2.close(); - xssfWb1.close(); + assertEquals(1, wb2.getNumberOfSheets()); + Sheet sheet = wb2.getSheetAt(0); + assertNotNull(sheet); + assertEquals("S1", sheet.getSheetName()); + assertTrue(wb2.dispose()); + xssfWb2.close(); + xssfWb1.close(); - wb2.close(); - wb1.close(); + wb2.close(); + wb1.close(); } @Test @@ -157,76 +157,76 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { @Test void addToExistingWorkbook() throws IOException { - XSSFWorkbook xssfWb1 = new XSSFWorkbook(); - xssfWb1.createSheet("S1"); - Sheet sheet = xssfWb1.createSheet("S2"); - Row row = sheet.createRow(1); - Cell cell = row.createCell(1); - cell.setCellValue("value 2_1_1"); + XSSFWorkbook xssfWb1 = new XSSFWorkbook(); + xssfWb1.createSheet("S1"); + Sheet sheet = xssfWb1.createSheet("S2"); + Row row = sheet.createRow(1); + Cell cell = row.createCell(1); + cell.setCellValue("value 2_1_1"); SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1); - XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); + XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); assertTrue(wb1.dispose()); xssfWb1.close(); SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2); - // Add a row to the existing empty sheet - Sheet sheet1 = wb2.getSheetAt(0); - Row row1_1 = sheet1.createRow(1); - Cell cell1_1_1 = row1_1.createCell(1); - cell1_1_1.setCellValue("value 1_1_1"); + // Add a row to the existing empty sheet + Sheet sheet1 = wb2.getSheetAt(0); + Row row1_1 = sheet1.createRow(1); + Cell cell1_1_1 = row1_1.createCell(1); + cell1_1_1.setCellValue("value 1_1_1"); - // Add a row to the existing non-empty sheet - Sheet sheet2 = wb2.getSheetAt(1); - Row row2_2 = sheet2.createRow(2); - Cell cell2_2_1 = row2_2.createCell(1); - cell2_2_1.setCellValue("value 2_2_1"); + // Add a row to the existing non-empty sheet + Sheet sheet2 = wb2.getSheetAt(1); + Row row2_2 = sheet2.createRow(2); + Cell cell2_2_1 = row2_2.createCell(1); + cell2_2_1.setCellValue("value 2_2_1"); - // Add a sheet with one row - Sheet sheet3 = wb2.createSheet("S3"); - Row row3_1 = sheet3.createRow(1); - Cell cell3_1_1 = row3_1.createCell(1); - cell3_1_1.setCellValue("value 3_1_1"); + // Add a sheet with one row + Sheet sheet3 = wb2.createSheet("S3"); + Row row3_1 = sheet3.createRow(1); + Cell cell3_1_1 = row3_1.createCell(1); + cell3_1_1.setCellValue("value 3_1_1"); - XSSFWorkbook xssfWb3 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb2); - wb2.close(); + XSSFWorkbook xssfWb3 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb2); + wb2.close(); - assertEquals(3, xssfWb3.getNumberOfSheets()); - // Verify sheet 1 - sheet1 = xssfWb3.getSheetAt(0); - assertEquals("S1", sheet1.getSheetName()); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - row1_1 = sheet1.getRow(1); - assertNotNull(row1_1); - cell1_1_1 = row1_1.getCell(1); - assertNotNull(cell1_1_1); - assertEquals("value 1_1_1", cell1_1_1.getStringCellValue()); - // Verify sheet 2 - sheet2 = xssfWb3.getSheetAt(1); - assertEquals("S2", sheet2.getSheetName()); - assertEquals(2, sheet2.getPhysicalNumberOfRows()); - Row row2_1 = sheet2.getRow(1); - assertNotNull(row2_1); - Cell cell2_1_1 = row2_1.getCell(1); - assertNotNull(cell2_1_1); - assertEquals("value 2_1_1", cell2_1_1.getStringCellValue()); - row2_2 = sheet2.getRow(2); - assertNotNull(row2_2); - cell2_2_1 = row2_2.getCell(1); - assertNotNull(cell2_2_1); - assertEquals("value 2_2_1", cell2_2_1.getStringCellValue()); - // Verify sheet 3 - sheet3 = xssfWb3.getSheetAt(2); - assertEquals("S3", sheet3.getSheetName()); - assertEquals(1, sheet3.getPhysicalNumberOfRows()); - row3_1 = sheet3.getRow(1); - assertNotNull(row3_1); - cell3_1_1 = row3_1.getCell(1); - assertNotNull(cell3_1_1); - assertEquals("value 3_1_1", cell3_1_1.getStringCellValue()); + assertEquals(3, xssfWb3.getNumberOfSheets()); + // Verify sheet 1 + sheet1 = xssfWb3.getSheetAt(0); + assertEquals("S1", sheet1.getSheetName()); + assertEquals(1, sheet1.getPhysicalNumberOfRows()); + row1_1 = sheet1.getRow(1); + assertNotNull(row1_1); + cell1_1_1 = row1_1.getCell(1); + assertNotNull(cell1_1_1); + assertEquals("value 1_1_1", cell1_1_1.getStringCellValue()); + // Verify sheet 2 + sheet2 = xssfWb3.getSheetAt(1); + assertEquals("S2", sheet2.getSheetName()); + assertEquals(2, sheet2.getPhysicalNumberOfRows()); + Row row2_1 = sheet2.getRow(1); + assertNotNull(row2_1); + Cell cell2_1_1 = row2_1.getCell(1); + assertNotNull(cell2_1_1); + assertEquals("value 2_1_1", cell2_1_1.getStringCellValue()); + row2_2 = sheet2.getRow(2); + assertNotNull(row2_2); + cell2_2_1 = row2_2.getCell(1); + assertNotNull(cell2_2_1); + assertEquals("value 2_2_1", cell2_2_1.getStringCellValue()); + // Verify sheet 3 + sheet3 = xssfWb3.getSheetAt(2); + assertEquals("S3", sheet3.getSheetName()); + assertEquals(1, sheet3.getPhysicalNumberOfRows()); + row3_1 = sheet3.getRow(1); + assertNotNull(row3_1); + cell3_1_1 = row3_1.getCell(1); + assertNotNull(cell3_1_1); + assertEquals("value 3_1_1", cell3_1_1.getStringCellValue()); xssfWb2.close(); - xssfWb3.close(); - wb1.close(); + xssfWb3.close(); + wb1.close(); } @Test @@ -358,7 +358,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { @Disabled("Crashes the JVM because of documented JVM behavior with concurrent writing/reading of zip-files, " + "see http://www.oracle.com/technetwork/java/javase/documentation/overview-156328.html") - @Test + @Test void bug53515a() throws Exception { File out = new File("Test.xlsx"); assertTrue(!out.exists() || out.delete()); @@ -529,7 +529,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { } @Disabled("not implemented") - @Test + @Test void changeSheetNameWithSharedFormulas() { } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSheetDataWriter.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSheetDataWriter.java index 864ec3bc0d..a452073f35 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSheetDataWriter.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSheetDataWriter.java @@ -43,7 +43,7 @@ public final class TestSheetDataWriter { + "\uD835\uDF76\uD835\uDF77\uD835\uDF78\uD835\uDF79\uD835\uDF7A"; @Test - void testReplaceWithQuestionMark() { + void testReplaceWithQuestionMark() { for(int i = 0; i < unicodeSurrogates.length(); i++) { assertFalse(SheetDataWriter.replaceWithQuestionMark(unicodeSurrogates.charAt(i))); } @@ -52,7 +52,7 @@ public final class TestSheetDataWriter { assertTrue(SheetDataWriter.replaceWithQuestionMark('\u0000')); assertTrue(SheetDataWriter.replaceWithQuestionMark('\u000F')); assertTrue(SheetDataWriter.replaceWithQuestionMark('\u001F')); - } + } @Test void testWriteUnicodeSurrogates() throws IOException { diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java index 600ce5c31d..b0aa931052 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java @@ -61,20 +61,20 @@ import org.junit.jupiter.params.provider.MethodSource; public final class TestFormulaEvaluatorOnXSSF { private static final Logger LOG = LogManager.getLogger(TestFormulaEvaluatorOnXSSF.class); - private static XSSFWorkbook workbook; + private static XSSFWorkbook workbook; private static Sheet sheet; private static FormulaEvaluator evaluator; private static Locale userLocale; - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - private interface SS { + /** + * This class defines constants for navigating around the test data spreadsheet used for these tests. + */ + private interface SS { - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - String FILENAME = "FormulaEvalTestData_Copy.xlsx"; + /** + * Name of the test spreadsheet (found in the standard test data folder) + */ + String FILENAME = "FormulaEvalTestData_Copy.xlsx"; /** * Row (zero-based) in the test spreadsheet where the operator examples start. */ @@ -102,7 +102,7 @@ public final class TestFormulaEvaluatorOnXSSF { * Each function takes 4 rows in the test spreadsheet */ int NUMBER_OF_ROWS_PER_FUNCTION = 4; - } + } @AfterAll public static void closeResource() throws Exception { @@ -167,100 +167,100 @@ public final class TestFormulaEvaluatorOnXSSF { } - @ParameterizedTest - @MethodSource("data") - void processFunctionRow(String targetFunctionName, int formulasRowIdx, int expectedValuesRowIdx) { - Row formulasRow = sheet.getRow(formulasRowIdx); - Row expectedValuesRow = sheet.getRow(expectedValuesRowIdx); + @ParameterizedTest + @MethodSource("data") + void processFunctionRow(String targetFunctionName, int formulasRowIdx, int expectedValuesRowIdx) { + Row formulasRow = sheet.getRow(formulasRowIdx); + Row expectedValuesRow = sheet.getRow(expectedValuesRowIdx); - short endcolnum = formulasRow.getLastCellNum(); + short endcolnum = formulasRow.getLastCellNum(); - // iterate across the row for all the evaluation cases - for (short colnum=SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++) { - Cell c = formulasRow.getCell(colnum); - assumeTrue(c != null); - assumeTrue(c.getCellType() == CellType.FORMULA); - ignoredFormulaTestCase(c.getCellFormula()); + // iterate across the row for all the evaluation cases + for (short colnum=SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++) { + Cell c = formulasRow.getCell(colnum); + assumeTrue(c != null); + assumeTrue(c.getCellType() == CellType.FORMULA); + ignoredFormulaTestCase(c.getCellFormula()); - CellValue actValue = evaluator.evaluate(c); - Cell expValue = (expectedValuesRow == null) ? null : expectedValuesRow.getCell(colnum); + CellValue actValue = evaluator.evaluate(c); + Cell expValue = (expectedValuesRow == null) ? null : expectedValuesRow.getCell(colnum); - String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" - , targetFunctionName, c.getCellFormula(), formulasRow.getRowNum(), colnum); + String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" + , targetFunctionName, c.getCellFormula(), formulasRow.getRowNum(), colnum); - assertNotNull(expValue, msg + " - Bad setup data expected value is null"); - assertNotNull(actValue, msg + " - actual value was null"); + assertNotNull(expValue, msg + " - Bad setup data expected value is null"); + assertNotNull(actValue, msg + " - actual value was null"); - final CellType expectedCellType = expValue.getCellType(); - switch (expectedCellType) { - case BLANK: - assertEquals(CellType.BLANK, actValue.getCellType(), msg); - break; - case BOOLEAN: - assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); - assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); - break; - case ERROR: - assertEquals(CellType.ERROR, actValue.getCellType(), msg); -// if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values -// assertEquals(msg, expValue.getErrorCellValue(), actValue.getErrorValue()); -// } - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - fail("Cannot expect formula as result of formula evaluation: " + msg); - case NUMERIC: - assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); - BaseTestNumeric.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); -// double delta = Math.abs(expValue.getNumericCellValue()-actValue.getNumberValue()); -// double pctExpValue = Math.abs(0.00001*expValue.getNumericCellValue()); -// assertTrue(msg, delta <= pctExpValue); - break; - case STRING: - assertEquals(CellType.STRING, actValue.getCellType(), msg); - assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); - break; - default: - fail("Unexpected cell type: " + expectedCellType); - } - } - } + final CellType expectedCellType = expValue.getCellType(); + switch (expectedCellType) { + case BLANK: + assertEquals(CellType.BLANK, actValue.getCellType(), msg); + break; + case BOOLEAN: + assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); + assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); + break; + case ERROR: + assertEquals(CellType.ERROR, actValue.getCellType(), msg); +// if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values +// assertEquals(msg, expValue.getErrorCellValue(), actValue.getErrorValue()); +// } + break; + case FORMULA: // will never be used, since we will call method after formula evaluation + fail("Cannot expect formula as result of formula evaluation: " + msg); + case NUMERIC: + assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); + BaseTestNumeric.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); +// double delta = Math.abs(expValue.getNumericCellValue()-actValue.getNumberValue()); +// double pctExpValue = Math.abs(0.00001*expValue.getNumericCellValue()); +// assertTrue(msg, delta <= pctExpValue); + break; + case STRING: + assertEquals(CellType.STRING, actValue.getCellType(), msg); + assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); + break; + default: + fail("Unexpected cell type: " + expectedCellType); + } + } + } - /* - * TODO - these are all formulas which currently (Apr-2008) break on ooxml - */ - private static void ignoredFormulaTestCase(String cellFormula) { + /* + * TODO - these are all formulas which currently (Apr-2008) break on ooxml + */ + private static void ignoredFormulaTestCase(String cellFormula) { // full row ranges are not parsed properly yet. // These cases currently work in svn trunk because of another bug which causes the // formula to get rendered as COLUMN($A$1:$IV$2) or ROW($A$2:$IV$3) - assumeFalse("COLUMN(1:2)".equals(cellFormula)); - assumeFalse("ROW(2:3)".equals(cellFormula)); + assumeFalse("COLUMN(1:2)".equals(cellFormula)); + assumeFalse("ROW(2:3)".equals(cellFormula)); // currently throws NPE because unknown function "currentcell" causes name lookup // Name lookup requires some equivalent object of the Workbook within xSSFWorkbook. - assumeFalse("ISREF(currentcell())".equals(cellFormula)); - } + assumeFalse("ISREF(currentcell())".equals(cellFormula)); + } - /** - * @return null if cell is missing, empty or blank - */ - private static String getTargetFunctionName(Row r) { - if(r == null) { + /** + * @return null if cell is missing, empty or blank + */ + private static String getTargetFunctionName(Row r) { + if(r == null) { LOG.atWarn().log("Given null row, can't figure out function name"); - return null; - } - Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME); - if(cell == null) { - LOG.atWarn().log("Row {} has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name", box(r.getRowNum())); - return null; - } - if(cell.getCellType() == CellType.BLANK) { - return null; - } - if(cell.getCellType() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } + return null; + } + Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME); + if(cell == null) { + LOG.atWarn().log("Row {} has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name", box(r.getRowNum())); + return null; + } + if(cell.getCellType() == CellType.BLANK) { + return null; + } + if(cell.getCellType() == CellType.STRING) { + return cell.getRichStringCellValue().getString(); + } - fail("Bad cell type for 'function name' column: ("+cell.getColumnIndex()+") row ("+(r.getRowNum()+1)+")"); - return null; - } + fail("Bad cell type for 'function name' column: ("+cell.getColumnIndex()+") row ("+(r.getRowNum()+1)+")"); + return null; + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java index 4c458ea42b..a6fb4aebbf 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java @@ -54,49 +54,49 @@ import org.junit.jupiter.params.provider.MethodSource; public final class TestMultiSheetFormulaEvaluatorOnXSSF { private static final Logger LOG = LogManager.getLogger(TestMultiSheetFormulaEvaluatorOnXSSF.class); - private static XSSFWorkbook workbook; + private static XSSFWorkbook workbook; private static Sheet sheet; private static FormulaEvaluator evaluator; - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - interface SS { + /** + * This class defines constants for navigating around the test data spreadsheet used for these tests. + */ + interface SS { - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - String FILENAME = "FormulaSheetRange.xlsx"; - /** - * Row (zero-based) in the test spreadsheet where the function examples start. - */ - int START_FUNCTIONS_ROW_INDEX = 10; // Row '11' - /** - * Index of the column that contains the function names - */ - int COLUMN_INDEX_FUNCTION_NAME = 0; // Column 'A' - /** - * Index of the column that contains the test names - */ - int COLUMN_INDEX_TEST_NAME = 1; // Column 'B' - /** - * Used to indicate when there are no more functions left - */ - String FUNCTION_NAMES_END_SENTINEL = ""; + /** + * Name of the test spreadsheet (found in the standard test data folder) + */ + String FILENAME = "FormulaSheetRange.xlsx"; + /** + * Row (zero-based) in the test spreadsheet where the function examples start. + */ + int START_FUNCTIONS_ROW_INDEX = 10; // Row '11' + /** + * Index of the column that contains the function names + */ + int COLUMN_INDEX_FUNCTION_NAME = 0; // Column 'A' + /** + * Index of the column that contains the test names + */ + int COLUMN_INDEX_TEST_NAME = 1; // Column 'B' + /** + * Used to indicate when there are no more functions left + */ + String FUNCTION_NAMES_END_SENTINEL = ""; - /** - * Index of the column where the test expected value is present - */ - short COLUMN_INDEX_EXPECTED_VALUE = 2; // Column 'C' - /** - * Index of the column where the test actual value is present - */ - short COLUMN_INDEX_ACTUAL_VALUE = 3; // Column 'D' - /** - * Test sheet name (sheet with all test formulae) - */ - String TEST_SHEET_NAME = "test"; - } + /** + * Index of the column where the test expected value is present + */ + short COLUMN_INDEX_EXPECTED_VALUE = 2; // Column 'C' + /** + * Index of the column where the test actual value is present + */ + short COLUMN_INDEX_ACTUAL_VALUE = 3; // Column 'D' + /** + * Test sheet name (sheet with all test formulae) + */ + String TEST_SHEET_NAME = "test"; + } @AfterAll @@ -130,7 +130,7 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { String targetFunctionName = getTargetFunctionName(r); assertNotNull(targetFunctionName, - "Test spreadsheet cell empty on row (" + "Test spreadsheet cell empty on row (" + (rowIndex+1) + "). Expected function name or '" + SS.FUNCTION_NAMES_END_SENTINEL + "'"); @@ -145,7 +145,7 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { // expected results are on the row below Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); assertNotNull(expectedValueCell, - "Missing expected values cell for function '" + "Missing expected values cell for function '" + targetFunctionName + ", test" + targetTestName + " (row " + rowIndex + 1 + ")"); @@ -155,13 +155,13 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { } @ParameterizedTest - @MethodSource("data") + @MethodSource("data") void processFunctionRow(String targetTestName, String targetFunctionName, int formulasRowIdx) { Row r = sheet.getRow(formulasRowIdx); Cell expValue = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); assertNotNull(expValue, - "Missing expected values cell for function '" + "Missing expected values cell for function '" + targetFunctionName + ", test" + targetTestName + " (row " + formulasRowIdx + 1 + ")"); @@ -195,7 +195,7 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { fail("Cannot expect formula as result of formula evaluation: " + msg); case NUMERIC: assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); - BaseTestNumeric.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); + BaseTestNumeric.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); // double delta = Math.abs(expected.getNumericCellValue()-actual.getNumberValue()); // double pctExpected = Math.abs(0.00001*expected.getNumericCellValue()); // assertTrue(msg, delta <= pctExpected); @@ -210,43 +210,43 @@ public final class TestMultiSheetFormulaEvaluatorOnXSSF { } /** - * @return null if cell is missing, empty or blank - */ - private static String getTargetFunctionName(Row r) { - if(r == null) { - LOG.atWarn().log("Given null row, can't figure out function name"); - return null; - } - Cell cell = r.getCell(COLUMN_INDEX_FUNCTION_NAME); - if(cell == null) { - LOG.atWarn().log("Row {} has no cell " + COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name", box(r.getRowNum())); - return null; - } + * @return null if cell is missing, empty or blank + */ + private static String getTargetFunctionName(Row r) { + if(r == null) { + LOG.atWarn().log("Given null row, can't figure out function name"); + return null; + } + Cell cell = r.getCell(COLUMN_INDEX_FUNCTION_NAME); + if(cell == null) { + LOG.atWarn().log("Row {} has no cell " + COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name", box(r.getRowNum())); + return null; + } - CellType ct = cell.getCellType(); - assertTrue(ct == CellType.BLANK || ct == CellType.STRING, - "Bad cell type for 'function name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); + CellType ct = cell.getCellType(); + assertTrue(ct == CellType.BLANK || ct == CellType.STRING, + "Bad cell type for 'function name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null; - } + return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null; + } - /** - * @return null if cell is missing, empty or blank - */ - private static String getTargetTestName(Row r) { - if(r == null) { + /** + * @return null if cell is missing, empty or blank + */ + private static String getTargetTestName(Row r) { + if(r == null) { LOG.atWarn().log("Given null row, can't figure out test name"); - return null; - } - Cell cell = r.getCell(COLUMN_INDEX_TEST_NAME); - if(cell == null) { - LOG.atWarn().log("Row {} has no cell " + COLUMN_INDEX_TEST_NAME + ", can't figure out test name", box(r.getRowNum())); - return null; - } - CellType ct = cell.getCellType(); - assertTrue(ct == CellType.BLANK || ct == CellType.STRING, - "Bad cell type for 'test name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); + return null; + } + Cell cell = r.getCell(COLUMN_INDEX_TEST_NAME); + if(cell == null) { + LOG.atWarn().log("Row {} has no cell " + COLUMN_INDEX_TEST_NAME + ", can't figure out test name", box(r.getRowNum())); + return null; + } + CellType ct = cell.getCellType(); + assertTrue(ct == CellType.BLANK || ct == CellType.STRING, + "Bad cell type for 'test name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null; - } + return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null; + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java index 508362e820..450f02b7af 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java @@ -2242,7 +2242,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { // List fills = table.getFills(); // System.out.println("Having " + fills.size() + " fills"); // for(XSSFCellFill fill : fills) { -// System.out.println("Fill: " + fill.getFillBackgroundColor() + "/" + fill.getFillForegroundColor()); +// System.out.println("Fill: " + fill.getFillBackgroundColor() + "/" + fill.getFillForegroundColor()); // } xlsToAppendWorkbook.close(); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCell.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCell.java index f677b5cc0f..54dd5c0b46 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCell.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCell.java @@ -488,7 +488,7 @@ public final class TestXSSFCell extends BaseTestXCell { StringBuilder sb = new StringBuilder(); // test all possible characters for(int i = 0; i < Character.MAX_VALUE; i++) { - sb.append((char)i); + sb.append((char)i); } String strAll = sb.toString(); @@ -496,7 +496,7 @@ public final class TestXSSFCell extends BaseTestXCell { // process in chunks as we have a limit on size of column now int pos = 0; while(pos < strAll.length()) { - String str = strAll.substring(pos, Math.min(strAll.length(), pos+SpreadsheetVersion.EXCEL2007.getMaxTextLength())); + String str = strAll.substring(pos, Math.min(strAll.length(), pos+SpreadsheetVersion.EXCEL2007.getMaxTextLength())); Workbook wb = HSSFITestDataProvider.instance.createWorkbook(); Cell cell = wb.createSheet().createRow(0).createCell(0); @@ -507,31 +507,31 @@ public final class TestXSSFCell extends BaseTestXCell { Workbook swb = SXSSFITestDataProvider.instance.createWorkbook(); Cell sCell = swb.createSheet().createRow(0).createCell(0); - cell.setCellValue(str); - assertEquals(str, cell.getStringCellValue()); - xCell.setCellValue(str); - assertEquals(str, xCell.getStringCellValue()); - sCell.setCellValue(str); - assertEquals(str, sCell.getStringCellValue()); + cell.setCellValue(str); + assertEquals(str, cell.getStringCellValue()); + xCell.setCellValue(str); + assertEquals(str, xCell.getStringCellValue()); + sCell.setCellValue(str); + assertEquals(str, sCell.getStringCellValue()); - Workbook wbBack = HSSFITestDataProvider.instance.writeOutAndReadBack(wb); - Workbook xwbBack = XSSFITestDataProvider.instance.writeOutAndReadBack(xwb); - Workbook swbBack = SXSSFITestDataProvider.instance.writeOutAndReadBack(swb); - cell = wbBack.getSheetAt(0).createRow(0).createCell(0); - xCell = xwbBack.getSheetAt(0).createRow(0).createCell(0); - sCell = swbBack.getSheetAt(0).createRow(0).createCell(0); + Workbook wbBack = HSSFITestDataProvider.instance.writeOutAndReadBack(wb); + Workbook xwbBack = XSSFITestDataProvider.instance.writeOutAndReadBack(xwb); + Workbook swbBack = SXSSFITestDataProvider.instance.writeOutAndReadBack(swb); + cell = wbBack.getSheetAt(0).createRow(0).createCell(0); + xCell = xwbBack.getSheetAt(0).createRow(0).createCell(0); + sCell = swbBack.getSheetAt(0).createRow(0).createCell(0); - assertEquals(cell.getStringCellValue(), xCell.getStringCellValue()); - assertEquals(cell.getStringCellValue(), sCell.getStringCellValue()); + assertEquals(cell.getStringCellValue(), xCell.getStringCellValue()); + assertEquals(cell.getStringCellValue(), sCell.getStringCellValue()); - pos += SpreadsheetVersion.EXCEL97.getMaxTextLength(); + pos += SpreadsheetVersion.EXCEL97.getMaxTextLength(); - swbBack.close(); - xwbBack.close(); - wbBack.close(); - swb.close(); - xwb.close(); - wb.close(); + swbBack.close(); + xwbBack.close(); + wbBack.close(); + swb.close(); + xwb.close(); + wb.close(); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java index cefac9bb24..727f399ea8 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java @@ -60,54 +60,54 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType; import org.openxmlformats.schemas.spreadsheetml.x2006.main.STVerticalAlignment; class TestXSSFCellStyle { - private StylesTable stylesTable; + private StylesTable stylesTable; private XSSFCellStyle cellStyle; @BeforeEach - void setUp() { - stylesTable = new StylesTable(); + void setUp() { + stylesTable = new StylesTable(); CTStylesheet ctStylesheet = stylesTable.getCTStylesheet(); CTBorder ctBorderA = CTBorder.Factory.newInstance(); - XSSFCellBorder borderA = new XSSFCellBorder(ctBorderA); - long borderId = stylesTable.putBorder(borderA); - assertEquals(0, borderId); + XSSFCellBorder borderA = new XSSFCellBorder(ctBorderA); + long borderId = stylesTable.putBorder(borderA); + assertEquals(0, borderId); - XSSFCellBorder borderB = new XSSFCellBorder(); - assertEquals(0, stylesTable.putBorder(borderB)); + XSSFCellBorder borderB = new XSSFCellBorder(); + assertEquals(0, stylesTable.putBorder(borderB)); CTFill ctFill = CTFill.Factory.newInstance(); - XSSFCellFill fill = new XSSFCellFill(ctFill, null); - long fillId = stylesTable.putFill(fill); - assertEquals(2, fillId); + XSSFCellFill fill = new XSSFCellFill(ctFill, null); + long fillId = stylesTable.putFill(fill); + assertEquals(2, fillId); CTFont ctFont = CTFont.Factory.newInstance(); - XSSFFont font = new XSSFFont(ctFont); - long fontId = stylesTable.putFont(font); - assertEquals(1, fontId); + XSSFFont font = new XSSFFont(ctFont); + long fontId = stylesTable.putFont(font); + assertEquals(1, fontId); CTXf cellStyleXf = ctStylesheet.addNewCellStyleXfs().addNewXf(); - cellStyleXf.setBorderId(1); - cellStyleXf.setFillId(1); - cellStyleXf.setFontId(1); + cellStyleXf.setBorderId(1); + cellStyleXf.setFillId(1); + cellStyleXf.setFontId(1); CTCellXfs cellXfs = ctStylesheet.addNewCellXfs(); CTXf cellXf = cellXfs.addNewXf(); - cellXf.setXfId(1); - cellXf.setBorderId(1); - cellXf.setFillId(1); - cellXf.setFontId(1); - assertEquals(2, stylesTable.putCellStyleXf(cellStyleXf)); - assertEquals(2, stylesTable.putCellXf(cellXf)); - cellStyle = new XSSFCellStyle(1, 1, stylesTable, null); + cellXf.setXfId(1); + cellXf.setBorderId(1); + cellXf.setFillId(1); + cellXf.setFontId(1); + assertEquals(2, stylesTable.putCellStyleXf(cellStyleXf)); + assertEquals(2, stylesTable.putCellXf(cellXf)); + cellStyle = new XSSFCellStyle(1, 1, stylesTable, null); - assertNotNull(stylesTable.getFillAt(1).getCTFill().getPatternFill()); - assertEquals(STPatternType.INT_DARK_GRAY, stylesTable.getFillAt(1).getCTFill().getPatternFill().getPatternType().intValue()); - } + assertNotNull(stylesTable.getFillAt(1).getCTFill().getPatternFill()); + assertEquals(STPatternType.INT_DARK_GRAY, stylesTable.getFillAt(1).getCTFill().getPatternFill().getPatternType().intValue()); + } - @Test - void testGetSetBorderBottom() { + @Test + void testGetSetBorderBottom() { //default values assertEquals(BorderStyle.NONE, cellStyle.getBorderBottom()); @@ -144,7 +144,7 @@ class TestXSSFCellStyle { assertEquals(ctBorder.getBottom().getStyle(), STBorderStyle.NONE); } - @Test + @Test void testGetSetBorderRight() { //default values assertEquals(BorderStyle.NONE, cellStyle.getBorderRight()); @@ -182,7 +182,7 @@ class TestXSSFCellStyle { assertEquals(ctBorder.getRight().getStyle(), STBorderStyle.NONE); } - @Test + @Test void testGetSetBorderLeft() { //default values assertEquals(BorderStyle.NONE, cellStyle.getBorderLeft()); @@ -218,9 +218,9 @@ class TestXSSFCellStyle { //assertFalse(ctBorder.isSetLeft()); //replacement: assertEquals(ctBorder.getLeft().getStyle(), STBorderStyle.NONE); - } + } - @Test + @Test void testGetSetBorderTop() { //default values assertEquals(BorderStyle.NONE, cellStyle.getBorderTop()); @@ -393,7 +393,7 @@ class TestXSSFCellStyle { assertNull(cellStyle.getBottomBorderXSSFColor()); } - @Test + @Test void testGetSetTopBorderColor() { //defaults assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getTopBorderColor()); @@ -432,9 +432,9 @@ class TestXSSFCellStyle { //passing null unsets the color cellStyle.setTopBorderColor(null); assertNull(cellStyle.getTopBorderXSSFColor()); - } + } - @Test + @Test void testGetSetLeftBorderColor() { //defaults assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getLeftBorderColor()); @@ -473,9 +473,9 @@ class TestXSSFCellStyle { //passing null unsets the color cellStyle.setLeftBorderColor(null); assertNull(cellStyle.getLeftBorderXSSFColor()); - } + } - @Test + @Test void testGetSetRightBorderColor() { //defaults assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getRightBorderColor()); @@ -514,9 +514,9 @@ class TestXSSFCellStyle { //passing null unsets the color cellStyle.setRightBorderColor(null); assertNull(cellStyle.getRightBorderXSSFColor()); - } + } - @Test + @Test void testGetSetFillBackgroundColor() { assertEquals(IndexedColors.AUTOMATIC.getIndex(), cellStyle.getFillBackgroundColor()); @@ -556,14 +556,14 @@ class TestXSSFCellStyle { cellStyle.setFillBackgroundColor(null); assertNull(cellStyle.getFillBackgroundXSSFColor()); assertEquals(IndexedColors.AUTOMATIC.getIndex(), cellStyle.getFillBackgroundColor()); - } + } @Test void testDefaultStyles() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); + XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFCellStyle style1 = wb1.createCellStyle(); + XSSFCellStyle style1 = wb1.createCellStyle(); assertEquals(IndexedColors.AUTOMATIC.getIndex(), style1.getFillBackgroundColor()); assertNull(style1.getFillBackgroundXSSFColor()); @@ -588,7 +588,7 @@ class TestXSSFCellStyle { assertEquals(style2.getBorderRight(), style1.getBorderRight()); assertEquals(style2.getBorderTop(), style1.getBorderTop()); wb2.close(); - } + } @Test void testGetFillForegroundColor() throws IOException { @@ -654,62 +654,62 @@ class TestXSSFCellStyle { fillId = (int)cellStyle.getCoreXf().getFillId(); ctFill2 = stylesTable.getFillAt(fillId).getCTFill(); assertNull(ctFill2.getPatternFill()); - } + } - @Test + @Test void testGetFont() { - assertNotNull(cellStyle.getFont()); - } + assertNotNull(cellStyle.getFont()); + } - @Test + @Test void testGetSetHidden() { - assertFalse(cellStyle.getHidden()); - cellStyle.setHidden(true); - assertTrue(cellStyle.getHidden()); - cellStyle.setHidden(false); - assertFalse(cellStyle.getHidden()); - } + assertFalse(cellStyle.getHidden()); + cellStyle.setHidden(true); + assertTrue(cellStyle.getHidden()); + cellStyle.setHidden(false); + assertFalse(cellStyle.getHidden()); + } - @Test + @Test void testGetSetLocked() { - assertTrue(cellStyle.getLocked()); - cellStyle.setLocked(true); - assertTrue(cellStyle.getLocked()); - cellStyle.setLocked(false); - assertFalse(cellStyle.getLocked()); - } + assertTrue(cellStyle.getLocked()); + cellStyle.setLocked(true); + assertTrue(cellStyle.getLocked()); + cellStyle.setLocked(false); + assertFalse(cellStyle.getLocked()); + } - @Test + @Test void testGetSetIndent() { - assertEquals((short)0, cellStyle.getIndention()); - cellStyle.setIndention((short)3); - assertEquals((short)3, cellStyle.getIndention()); - cellStyle.setIndention((short) 13); - assertEquals((short)13, cellStyle.getIndention()); - } + assertEquals((short)0, cellStyle.getIndention()); + cellStyle.setIndention((short)3); + assertEquals((short)3, cellStyle.getIndention()); + cellStyle.setIndention((short) 13); + assertEquals((short)13, cellStyle.getIndention()); + } @Test void testGetSetAlignment() { - assertNull(cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - assertEquals(HorizontalAlignment.GENERAL, cellStyle.getAlignment()); + assertNull(cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); + assertEquals(HorizontalAlignment.GENERAL, cellStyle.getAlignment()); - cellStyle.setAlignment(HorizontalAlignment.LEFT); - assertEquals(HorizontalAlignment.LEFT, cellStyle.getAlignment()); - assertEquals(STHorizontalAlignment.LEFT, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); + cellStyle.setAlignment(HorizontalAlignment.LEFT); + assertEquals(HorizontalAlignment.LEFT, cellStyle.getAlignment()); + assertEquals(STHorizontalAlignment.LEFT, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - cellStyle.setAlignment(HorizontalAlignment.JUSTIFY); - assertEquals(HorizontalAlignment.JUSTIFY, cellStyle.getAlignment()); - assertEquals(STHorizontalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); + cellStyle.setAlignment(HorizontalAlignment.JUSTIFY); + assertEquals(HorizontalAlignment.JUSTIFY, cellStyle.getAlignment()); + assertEquals(STHorizontalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - cellStyle.setAlignment(HorizontalAlignment.CENTER); - assertEquals(HorizontalAlignment.CENTER, cellStyle.getAlignment()); - assertEquals(STHorizontalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - } + cellStyle.setAlignment(HorizontalAlignment.CENTER); + assertEquals(HorizontalAlignment.CENTER, cellStyle.getAlignment()); + assertEquals(STHorizontalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); + } - @Test + @Test void testGetSetReadingOrder() { - assertEquals(ReadingOrder.CONTEXT, cellStyle.getReadingOrder()); - assertEquals(ReadingOrder.CONTEXT.getCode(), cellStyle.getCellAlignment().getCTCellAlignment().getReadingOrder()); + assertEquals(ReadingOrder.CONTEXT, cellStyle.getReadingOrder()); + assertEquals(ReadingOrder.CONTEXT.getCode(), cellStyle.getCellAlignment().getCTCellAlignment().getReadingOrder()); cellStyle.setReadingOrder(ReadingOrder.LEFT_TO_RIGHT); assertEquals(ReadingOrder.LEFT_TO_RIGHT, cellStyle.getReadingOrder()); @@ -726,32 +726,32 @@ class TestXSSFCellStyle { @Test void testGetSetVerticalAlignment() { - assertEquals(VerticalAlignment.BOTTOM, cellStyle.getVerticalAlignment()); - assertFalse(cellStyle.getCellAlignment().getCTCellAlignment().isSetVertical()); - assertEquals(STVerticalAlignment.BOTTOM, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); + assertEquals(VerticalAlignment.BOTTOM, cellStyle.getVerticalAlignment()); + assertFalse(cellStyle.getCellAlignment().getCTCellAlignment().isSetVertical()); + assertEquals(STVerticalAlignment.BOTTOM, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); - cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); - assertEquals(VerticalAlignment.CENTER, cellStyle.getVerticalAlignment()); - assertEquals(STVerticalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); + cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); + assertEquals(VerticalAlignment.CENTER, cellStyle.getVerticalAlignment()); + assertEquals(STVerticalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); - cellStyle.setVerticalAlignment(VerticalAlignment.JUSTIFY); - assertEquals(VerticalAlignment.JUSTIFY, cellStyle.getVerticalAlignment()); - assertEquals(STVerticalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); - } + cellStyle.setVerticalAlignment(VerticalAlignment.JUSTIFY); + assertEquals(VerticalAlignment.JUSTIFY, cellStyle.getVerticalAlignment()); + assertEquals(STVerticalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); + } - @Test + @Test void testGetSetWrapText() { - assertFalse(cellStyle.getWrapText()); - cellStyle.setWrapText(true); - assertTrue(cellStyle.getWrapText()); - cellStyle.setWrapText(false); assertFalse(cellStyle.getWrapText()); - } + cellStyle.setWrapText(true); + assertTrue(cellStyle.getWrapText()); + cellStyle.setWrapText(false); + assertFalse(cellStyle.getWrapText()); + } - /** - * Cloning one XSSFCellStyle onto Another, same XSSFWorkbook - */ - @Test + /** + * Cloning one XSSFCellStyle onto Another, same XSSFWorkbook + */ + @Test void testCloneStyleSameWB() throws IOException { XSSFWorkbook wb = new XSSFWorkbook(); assertEquals(1, wb.getNumberOfFonts()); @@ -785,7 +785,7 @@ class TestXSSFCellStyle { wb2.close(); wb.close(); - } + } /** * Cloning one XSSFCellStyle onto Another, different XSSFWorkbooks @@ -882,7 +882,7 @@ class TestXSSFCellStyle { * Avoid ArrayIndexOutOfBoundsException when creating cell style * in a workbook that has an empty xf table. */ - @Test + @Test void testBug52348() throws IOException { XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("52348.xlsx"); StylesTable st = workbook.getStylesSource(); @@ -901,7 +901,7 @@ class TestXSSFCellStyle { * Avoid ArrayIndexOutOfBoundsException when getting cell style * in a workbook that has an empty xf table. */ - @Test + @Test void testBug55650() throws IOException { XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("52348.xlsx"); StylesTable st = workbook.getStylesSource(); @@ -918,47 +918,47 @@ class TestXSSFCellStyle { workbook.close(); } - @Test + @Test void testShrinkToFit() throws IOException { - // Existing file - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("ShrinkToFit.xlsx"); - Sheet s = wb1.getSheetAt(0); - Row r = s.getRow(0); - CellStyle cs = r.getCell(0).getCellStyle(); + // Existing file + XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("ShrinkToFit.xlsx"); + Sheet s = wb1.getSheetAt(0); + Row r = s.getRow(0); + CellStyle cs = r.getCell(0).getCellStyle(); assertTrue(cs.getShrinkToFit()); - // New file - XSSFWorkbook wb2 = new XSSFWorkbook(); - s = wb2.createSheet(); - r = s.createRow(0); + // New file + XSSFWorkbook wb2 = new XSSFWorkbook(); + s = wb2.createSheet(); + r = s.createRow(0); - cs = wb2.createCellStyle(); - cs.setShrinkToFit(false); - r.createCell(0).setCellStyle(cs); + cs = wb2.createCellStyle(); + cs.setShrinkToFit(false); + r.createCell(0).setCellStyle(cs); - cs = wb2.createCellStyle(); - cs.setShrinkToFit(true); - r.createCell(1).setCellStyle(cs); + cs = wb2.createCellStyle(); + cs.setShrinkToFit(true); + r.createCell(1).setCellStyle(cs); - // Write out, read, and check - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - s = wb3.getSheetAt(0); - r = s.getRow(0); + // Write out, read, and check + XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); + s = wb3.getSheetAt(0); + r = s.getRow(0); assertFalse(r.getCell(0).getCellStyle().getShrinkToFit()); assertTrue(r.getCell(1).getCellStyle().getShrinkToFit()); - XSSFWorkbook wb4 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - assertNotNull(wb4); - wb4.close(); + XSSFWorkbook wb4 = XSSFTestDataSamples.writeOutAndReadBack(wb2); + assertNotNull(wb4); + wb4.close(); - XSSFWorkbook wb5 = XSSFTestDataSamples.writeOutAndReadBack(wb3); - assertNotNull(wb5); - wb5.close(); + XSSFWorkbook wb5 = XSSFTestDataSamples.writeOutAndReadBack(wb3); + assertNotNull(wb5); + wb5.close(); - wb3.close(); - wb2.close(); - wb1.close(); + wb3.close(); + wb2.close(); + wb1.close(); } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFChart.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFChart.java index 7f6978683f..2945243902 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFChart.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFChart.java @@ -72,8 +72,8 @@ public final class TestXSSFChart { } @Test - void testAddChartsToNewWorkbook() throws Exception { - try (XSSFWorkbook wb = new XSSFWorkbook()) { + void testAddChartsToNewWorkbook() throws Exception { + try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet s1 = wb.createSheet(); XSSFDrawing d1 = s1.createDrawingPatriarch(); XSSFClientAnchor a1 = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30); @@ -91,5 +91,5 @@ public final class TestXSSFChart { assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); } - } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java index 227dc3627b..18eb1cc0da 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java @@ -43,16 +43,16 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; */ class TestXSSFColGrouping { - private static final Logger LOG = LogManager.getLogger(TestXSSFColGrouping.class); + private static final Logger LOG = LogManager.getLogger(TestXSSFColGrouping.class); /** * Tests that POI doesn't produce "col" elements without "width" attribute. * POI-52186 */ - @Test + @Test void testNoColsWithoutWidthWhenGrouping() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { XSSFSheet sheet = wb1.createSheet("test"); sheet.setColumnWidth(4, 5000); @@ -78,9 +78,9 @@ class TestXSSFColGrouping { * Tests that POI doesn't produce "col" elements without "width" attribute. * POI-52186 */ - @Test - void testNoColsWithoutWidthWhenGroupingAndCollapsing() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + @Test + void testNoColsWithoutWidthWhenGroupingAndCollapsing() throws IOException { + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { XSSFSheet sheet = wb1.createSheet("test"); sheet.setColumnWidth(4, 5000); @@ -110,9 +110,9 @@ class TestXSSFColGrouping { /** * Test the cols element is correct in case of NumericRanges.OVERLAPS_2_WRAPS */ - @Test + @Test void testMergingOverlappingCols_OVERLAPS_2_WRAPS() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { XSSFSheet sheet = wb1.createSheet("test"); CTCols cols = sheet.getCTWorksheet().getColsArray(0); @@ -158,9 +158,9 @@ class TestXSSFColGrouping { /** * Test the cols element is correct in case of NumericRanges.OVERLAPS_1_WRAPS */ - @Test + @Test void testMergingOverlappingCols_OVERLAPS_1_WRAPS() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { XSSFSheet sheet = wb1.createSheet("test"); CTCols cols = sheet.getCTWorksheet().getColsArray(0); @@ -206,9 +206,9 @@ class TestXSSFColGrouping { /** * Test the cols element is correct in case of NumericRanges.OVERLAPS_1_MINOR */ - @Test + @Test void testMergingOverlappingCols_OVERLAPS_1_MINOR() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { XSSFSheet sheet = wb1.createSheet("test"); CTCols cols = sheet.getCTWorksheet().getColsArray(0); @@ -255,9 +255,9 @@ class TestXSSFColGrouping { /** * Test the cols element is correct in case of NumericRanges.OVERLAPS_2_MINOR */ - @Test + @Test void testMergingOverlappingCols_OVERLAPS_2_MINOR() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { XSSFSheet sheet = wb1.createSheet("test"); CTCols cols = sheet.getCTWorksheet().getColsArray(0); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFComment.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFComment.java index aea85b4cc1..e1b57d56e1 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFComment.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFComment.java @@ -257,7 +257,7 @@ public final class TestXSSFComment extends BaseTestCellComment { @Test void testBug55814() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55814.xlsx")) { + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55814.xlsx")) { int oldsheetIndex = wb.getSheetIndex("example"); Sheet oldsheet = wb.getSheetAt(oldsheetIndex); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java index b9e2474309..5147e1f843 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java @@ -40,14 +40,14 @@ import org.junit.jupiter.api.Test; */ public final class TestXSSFDataFormat extends BaseTestDataFormat { - public TestXSSFDataFormat() { - super(XSSFITestDataProvider.instance); - } + public TestXSSFDataFormat() { + super(XSSFITestDataProvider.instance); + } /** * [Bug 58778] Built-in number formats can be overridden with XSSFDataFormat.putFormat(int id, String fmt) */ - @Test + @Test void test58778() throws IOException { try (XSSFWorkbook wb1 = new XSSFWorkbook()) { Cell cell = wb1.createSheet("bug58778").createRow(0).createCell(0); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java index 18f4d51d5d..d72cf493b1 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java @@ -58,9 +58,9 @@ class TestXSSFDataValidation extends BaseTestDataValidation { // application of a single validation definition to multiple cells. // // For list ( 3 validations for explicit and 3 for formula ) - // - one validation that allows blank. - // - one that does not allow blank. - // - one that does not show the drop down arrow. + // - one validation that allows blank. + // - one that does not allow blank. + // - one that does not show the drop down arrow. // = 2 // // For number validations ( integer/decimal and text length ) with 8 different types of operators. diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java index f85f0411ed..d0029c62ef 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java @@ -34,12 +34,12 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDialogsheet; class TestXSSFDialogSheet { @Test - void testCreateDialogSheet() throws IOException { + void testCreateDialogSheet() throws IOException { XSSFWorkbook workbook = new XSSFWorkbook(); Sheet dialogsheet = workbook.createDialogsheet("Dialogsheet 1", CTDialogsheet.Factory.newInstance()); assertNotNull(dialogsheet); workbook.close(); - } + } @Test void testGetDialog() throws IOException { @@ -50,14 +50,14 @@ class TestXSSFDialogSheet { } @Test - void testAddRow() throws IOException { + void testAddRow() throws IOException { XSSFWorkbook workbook = new XSSFWorkbook(); Sheet dialogsheet = workbook.createDialogsheet("Dialogsheet 1", CTDialogsheet.Factory.newInstance()); assertNotNull(dialogsheet); Row row = dialogsheet.createRow(0); assertNull(row); workbook.close(); - } + } @Test void testGetSetAutoBreaks() throws IOException { diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java index c072013404..807a6bc3df 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java @@ -304,7 +304,7 @@ class TestXSSFDrawing { */ @Test void testRichTextFontAndColor() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); + XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); XSSFDrawing drawing = sheet.createDrawingPatriarch(); @@ -335,7 +335,7 @@ class TestXSSFDrawing { */ @Test void testSetTextSingleParagraph() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); + XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); XSSFDrawing drawing = sheet.createDrawingPatriarch(); @@ -371,7 +371,7 @@ class TestXSSFDrawing { */ @Test void testAddNewTextParagraph() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); + XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); XSSFDrawing drawing = sheet.createDrawingPatriarch(); @@ -381,7 +381,7 @@ class TestXSSFDrawing { para.addNewTextRun().setText("Line 1"); List paras = shape.getTextParagraphs(); - assertEquals(2, paras.size()); // this should be 2 as XSSFSimpleShape creates a default paragraph (no text), and then we add a string to that. + assertEquals(2, paras.size()); // this should be 2 as XSSFSimpleShape creates a default paragraph (no text), and then we add a string to that. List runs = para.getTextRuns(); assertEquals(1, runs.size()); @@ -396,7 +396,7 @@ class TestXSSFDrawing { */ @Test void testAddNewTextParagraphWithRTS() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); + XSSFWorkbook wb1 = new XSSFWorkbook(); XSSFSheet sheet = wb1.createSheet(); XSSFDrawing drawing = sheet.createDrawingPatriarch(); @@ -410,7 +410,7 @@ class TestXSSFDrawing { XSSFFont midfont = wb1.createFont(); midfont.setColor(new XSSFColor(new Color(0, 255, 0), wb1.getStylesSource().getIndexedColors())); - rt.applyFont(5, 14, midfont); // set the text "Rich Text" to be green and the default font + rt.applyFont(5, 14, midfont); // set the text "Rich Text" to be green and the default font XSSFTextParagraph para = shape.addNewTextParagraph(rt); @@ -429,7 +429,7 @@ class TestXSSFDrawing { XSSFSimpleShape sshape = (XSSFSimpleShape) shapes.get(0); List paras = sshape.getTextParagraphs(); - assertEquals(2, paras.size()); // this should be 2 as XSSFSimpleShape creates a default paragraph (no text), and then we add a string to that. + assertEquals(2, paras.size()); // this should be 2 as XSSFSimpleShape creates a default paragraph (no text), and then we add a string to that. List runs = para.getTextRuns(); assertEquals(3, runs.size()); @@ -469,7 +469,7 @@ class TestXSSFDrawing { */ @Test void testAddMultipleParagraphs() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); + XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); XSSFDrawing drawing = sheet.createDrawingPatriarch(); @@ -485,7 +485,7 @@ class TestXSSFDrawing { para.addNewTextRun().setText("Line 3"); List paras = shape.getTextParagraphs(); - assertEquals(4, paras.size()); // this should be 4 as XSSFSimpleShape creates a default paragraph (no text), and then we added 3 paragraphs + assertEquals(4, paras.size()); // this should be 4 as XSSFSimpleShape creates a default paragraph (no text), and then we added 3 paragraphs assertEquals("Line 1\nLine 2\nLine 3", shape.getText()); checkRewrite(wb); @@ -497,7 +497,7 @@ class TestXSSFDrawing { */ @Test void testSetAddMultipleParagraphs() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); + XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); XSSFDrawing drawing = sheet.createDrawingPatriarch(); @@ -512,7 +512,7 @@ class TestXSSFDrawing { para.addNewTextRun().setText("Line 3"); List paras = shape.getTextParagraphs(); - assertEquals(3, paras.size()); // this should be 3 as we overwrote the default paragraph with setText, then added 2 new paragraphs + assertEquals(3, paras.size()); // this should be 3 as we overwrote the default paragraph with setText, then added 2 new paragraphs assertEquals("Line 1\nLine 2\nLine 3", shape.getText()); checkRewrite(wb); @@ -588,9 +588,9 @@ class TestXSSFDrawing { List paras = textbox.getTextParagraphs(); assertEquals(3, paras.size()); - assertEquals("Line 2", paras.get(1).getText()); // check content of second paragraph + assertEquals("Line 2", paras.get(1).getText()); // check content of second paragraph - assertEquals("Line 1\nLine 2\nLine 3", textbox.getText()); // check content of entire textbox + assertEquals("Line 1\nLine 2\nLine 3", textbox.getText()); // check content of entire textbox // check attributes of paragraphs assertEquals(TextAlign.LEFT, paras.get(0).getTextAlign()); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFExternalFunctions.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFExternalFunctions.java index 219b8423cc..63f2c20d0b 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFExternalFunctions.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFExternalFunctions.java @@ -24,7 +24,7 @@ import org.apache.poi.xssf.XSSFITestDataProvider; * Tests setting and evaluating user-defined functions in HSSF */ public final class TestXSSFExternalFunctions extends BaseTestExternalFunctions { - public TestXSSFExternalFunctions() { - super(XSSFITestDataProvider.instance, "atp.xlsx"); - } + public TestXSSFExternalFunctions() { + super(XSSFITestDataProvider.instance, "atp.xlsx"); + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFFont.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFFont.java index 6ec3eb8aaa..f5e81dbdb9 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFFont.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFFont.java @@ -53,52 +53,52 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.STUnderlineValues; public final class TestXSSFFont extends BaseTestFont{ - public TestXSSFFont() { - super(XSSFITestDataProvider.instance); - } + public TestXSSFFont() { + super(XSSFITestDataProvider.instance); + } - @SuppressWarnings("unused") - public static Stream defaultFont() { - return Stream.of(Arguments.of("Calibri", (short) 220, IndexedColors.BLACK.getIndex())); - } + @SuppressWarnings("unused") + public static Stream defaultFont() { + return Stream.of(Arguments.of("Calibri", (short) 220, IndexedColors.BLACK.getIndex())); + } - @Test - void testConstructor() { - XSSFFont xssfFont=new XSSFFont(); - assertNotNull(xssfFont.getCTFont()); - } + @Test + void testConstructor() { + XSSFFont xssfFont=new XSSFFont(); + assertNotNull(xssfFont.getCTFont()); + } - @Test - void testBold() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTBooleanProperty bool=ctFont.addNewB(); - bool.setVal(false); - ctFont.setBArray(0,bool); - XSSFFont xssfFont=new XSSFFont(ctFont); + @Test + void testBold() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTBooleanProperty bool=ctFont.addNewB(); + bool.setVal(false); + ctFont.setBArray(0,bool); + XSSFFont xssfFont=new XSSFFont(ctFont); assertFalse(xssfFont.getBold()); - xssfFont.setBold(true); - assertEquals(ctFont.sizeOfBArray(),1); + xssfFont.setBold(true); + assertEquals(ctFont.sizeOfBArray(),1); assertTrue(ctFont.getBArray(0).getVal()); - } + } - @SuppressWarnings("deprecation") - @Test - void testCharSetWithDeprecatedFontCharset() throws IOException { - CTFont ctFont=CTFont.Factory.newInstance(); - CTIntProperty prop=ctFont.addNewCharset(); - prop.setVal(org.apache.poi.ss.usermodel.FontCharset.ANSI.getValue()); + @SuppressWarnings("deprecation") + @Test + void testCharSetWithDeprecatedFontCharset() throws IOException { + CTFont ctFont=CTFont.Factory.newInstance(); + CTIntProperty prop=ctFont.addNewCharset(); + prop.setVal(org.apache.poi.ss.usermodel.FontCharset.ANSI.getValue()); - ctFont.setCharsetArray(0,prop); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(Font.ANSI_CHARSET,xssfFont.getCharSet()); + ctFont.setCharsetArray(0,prop); + XSSFFont xssfFont=new XSSFFont(ctFont); + assertEquals(Font.ANSI_CHARSET,xssfFont.getCharSet()); - xssfFont.setCharSet(org.apache.poi.ss.usermodel.FontCharset.DEFAULT); - assertEquals(org.apache.poi.ss.usermodel.FontCharset.DEFAULT.getValue(),ctFont.getCharsetArray(0).getVal()); + xssfFont.setCharSet(org.apache.poi.ss.usermodel.FontCharset.DEFAULT); + assertEquals(org.apache.poi.ss.usermodel.FontCharset.DEFAULT.getValue(),ctFont.getCharsetArray(0).getVal()); - // Try with a few less usual ones: - // Set with the Charset itself + // Try with a few less usual ones: + // Set with the Charset itself xssfFont.setCharSet(org.apache.poi.ss.usermodel.FontCharset.RUSSIAN); assertEquals(org.apache.poi.ss.usermodel.FontCharset.RUSSIAN.getValue(), xssfFont.getCharSet()); // And set with the Charset index @@ -110,269 +110,269 @@ public final class TestXSSFFont extends BaseTestFont{ // This one isn't allowed assertNull(org.apache.poi.ss.usermodel.FontCharset.valueOf(9999)); assertThrows(POIXMLException.class, () -> xssfFont.setCharSet(9999), - "Shouldn't be able to set an invalid charset"); + "Shouldn't be able to set an invalid charset"); - // Now try with a few sample files + // Now try with a few sample files - // Normal charset + // Normal charset try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx")) { - assertEquals(0, - wb1.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - } + assertEquals(0, + wb1.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() + ); + } - // GB2312 charset + // GB2312 charset try (XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("49273.xlsx")) { - assertEquals(134, - wb2.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - } - } + assertEquals(134, + wb2.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() + ); + } + } - @Test - void testCharSet() throws IOException { - CTFont ctFont=CTFont.Factory.newInstance(); - CTIntProperty prop=ctFont.addNewCharset(); - prop.setVal(FontCharset.ANSI.getNativeId()); + @Test + void testCharSet() throws IOException { + CTFont ctFont=CTFont.Factory.newInstance(); + CTIntProperty prop=ctFont.addNewCharset(); + prop.setVal(FontCharset.ANSI.getNativeId()); - ctFont.setCharsetArray(0,prop); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(Font.ANSI_CHARSET,xssfFont.getCharSet()); + ctFont.setCharsetArray(0,prop); + XSSFFont xssfFont=new XSSFFont(ctFont); + assertEquals(Font.ANSI_CHARSET,xssfFont.getCharSet()); - xssfFont.setCharSet(FontCharset.DEFAULT); - assertEquals(FontCharset.DEFAULT.getNativeId(),ctFont.getCharsetArray(0).getVal()); + xssfFont.setCharSet(FontCharset.DEFAULT); + assertEquals(FontCharset.DEFAULT.getNativeId(),ctFont.getCharsetArray(0).getVal()); - // Try with a few less usual ones: - // Set with the Charset itself - xssfFont.setCharSet(FontCharset.RUSSIAN); - assertEquals(FontCharset.RUSSIAN.getNativeId(), xssfFont.getCharSet()); - // And set with the Charset index - xssfFont.setCharSet(FontCharset.ARABIC.getNativeId()); - assertEquals(FontCharset.ARABIC.getNativeId(), xssfFont.getCharSet()); - xssfFont.setCharSet((byte)(FontCharset.ARABIC.getNativeId())); - assertEquals(FontCharset.ARABIC.getNativeId(), xssfFont.getCharSet()); + // Try with a few less usual ones: + // Set with the Charset itself + xssfFont.setCharSet(FontCharset.RUSSIAN); + assertEquals(FontCharset.RUSSIAN.getNativeId(), xssfFont.getCharSet()); + // And set with the Charset index + xssfFont.setCharSet(FontCharset.ARABIC.getNativeId()); + assertEquals(FontCharset.ARABIC.getNativeId(), xssfFont.getCharSet()); + xssfFont.setCharSet((byte)(FontCharset.ARABIC.getNativeId())); + assertEquals(FontCharset.ARABIC.getNativeId(), xssfFont.getCharSet()); - // This one isn't allowed - assertNull(FontCharset.valueOf(9999)); - assertThrows(POIXMLException.class, () -> xssfFont.setCharSet(9999), "Shouldn't be able to set an invalid charset"); + // This one isn't allowed + assertNull(FontCharset.valueOf(9999)); + assertThrows(POIXMLException.class, () -> xssfFont.setCharSet(9999), "Shouldn't be able to set an invalid charset"); - // Now try with a few sample files + // Now try with a few sample files - // Normal charset - try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx")) { - assertEquals(0, - wb1.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - } + // Normal charset + try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx")) { + assertEquals(0, + wb1.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() + ); + } - // GB2312 charset - try (XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("49273.xlsx")) { - assertEquals(134, - wb2.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - } - } + // GB2312 charset + try (XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("49273.xlsx")) { + assertEquals(134, + wb2.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() + ); + } + } - @Test - void testFontName() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontName fname=ctFont.addNewName(); - fname.setVal("Arial"); - ctFont.setNameArray(0,fname); + @Test + void testFontName() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTFontName fname=ctFont.addNewName(); + fname.setVal("Arial"); + ctFont.setNameArray(0,fname); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals("Arial", xssfFont.getFontName()); + XSSFFont xssfFont=new XSSFFont(ctFont); + assertEquals("Arial", xssfFont.getFontName()); - xssfFont.setFontName("Courier"); - assertEquals("Courier",ctFont.getNameArray(0).getVal()); - } + xssfFont.setFontName("Courier"); + assertEquals("Courier",ctFont.getNameArray(0).getVal()); + } - @Test - void testItalic() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTBooleanProperty bool=ctFont.addNewI(); - bool.setVal(false); - ctFont.setIArray(0,bool); + @Test + void testItalic() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTBooleanProperty bool=ctFont.addNewI(); + bool.setVal(false); + ctFont.setIArray(0,bool); - XSSFFont xssfFont=new XSSFFont(ctFont); + XSSFFont xssfFont=new XSSFFont(ctFont); assertFalse(xssfFont.getItalic()); - xssfFont.setItalic(true); - assertEquals(ctFont.sizeOfIArray(),1); + xssfFont.setItalic(true); + assertEquals(ctFont.sizeOfIArray(),1); assertTrue(ctFont.getIArray(0).getVal()); assertTrue(ctFont.getIArray(0).getVal()); - } + } - @Test - void testStrikeout() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTBooleanProperty bool=ctFont.addNewStrike(); - bool.setVal(false); - ctFont.setStrikeArray(0,bool); + @Test + void testStrikeout() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTBooleanProperty bool=ctFont.addNewStrike(); + bool.setVal(false); + ctFont.setStrikeArray(0,bool); - XSSFFont xssfFont=new XSSFFont(ctFont); + XSSFFont xssfFont=new XSSFFont(ctFont); assertFalse(xssfFont.getStrikeout()); - xssfFont.setStrikeout(true); - assertEquals(ctFont.sizeOfStrikeArray(),1); + xssfFont.setStrikeout(true); + assertEquals(ctFont.sizeOfStrikeArray(),1); assertTrue(ctFont.getStrikeArray(0).getVal()); assertTrue(ctFont.getStrikeArray(0).getVal()); - } + } - @Test - void testFontHeight() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontSize size=ctFont.addNewSz(); - size.setVal(11); - ctFont.setSzArray(0,size); + @Test + void testFontHeight() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTFontSize size=ctFont.addNewSz(); + size.setVal(11); + ctFont.setSzArray(0,size); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(11,xssfFont.getFontHeightInPoints()); + XSSFFont xssfFont=new XSSFFont(ctFont); + assertEquals(11,xssfFont.getFontHeightInPoints()); - xssfFont.setFontHeight(20); - assertEquals(20.0, ctFont.getSzArray(0).getVal(), 0.0); - } + xssfFont.setFontHeight(20); + assertEquals(20.0, ctFont.getSzArray(0).getVal(), 0.0); + } - @Test - void testFontHeightInPoint() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontSize size=ctFont.addNewSz(); - size.setVal(14); - ctFont.setSzArray(0,size); + @Test + void testFontHeightInPoint() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTFontSize size=ctFont.addNewSz(); + size.setVal(14); + ctFont.setSzArray(0,size); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(14,xssfFont.getFontHeightInPoints()); + XSSFFont xssfFont=new XSSFFont(ctFont); + assertEquals(14,xssfFont.getFontHeightInPoints()); - xssfFont.setFontHeightInPoints((short)20); - assertEquals(20.0, ctFont.getSzArray(0).getVal(), 0.0); - } + xssfFont.setFontHeightInPoints((short)20); + assertEquals(20.0, ctFont.getSzArray(0).getVal(), 0.0); + } - @Test - void testUnderline() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTUnderlineProperty underlinePropr=ctFont.addNewU(); - underlinePropr.setVal(STUnderlineValues.SINGLE); - ctFont.setUArray(0,underlinePropr); + @Test + void testUnderline() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTUnderlineProperty underlinePropr=ctFont.addNewU(); + underlinePropr.setVal(STUnderlineValues.SINGLE); + ctFont.setUArray(0,underlinePropr); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(Font.U_SINGLE, xssfFont.getUnderline()); + XSSFFont xssfFont=new XSSFFont(ctFont); + assertEquals(Font.U_SINGLE, xssfFont.getUnderline()); - xssfFont.setUnderline(Font.U_DOUBLE); - assertEquals(ctFont.sizeOfUArray(),1); - assertEquals(STUnderlineValues.DOUBLE,ctFont.getUArray(0).getVal()); + xssfFont.setUnderline(Font.U_DOUBLE); + assertEquals(ctFont.sizeOfUArray(),1); + assertEquals(STUnderlineValues.DOUBLE,ctFont.getUArray(0).getVal()); - xssfFont.setUnderline(FontUnderline.DOUBLE_ACCOUNTING); - assertEquals(ctFont.sizeOfUArray(),1); - assertEquals(STUnderlineValues.DOUBLE_ACCOUNTING,ctFont.getUArray(0).getVal()); - } + xssfFont.setUnderline(FontUnderline.DOUBLE_ACCOUNTING); + assertEquals(ctFont.sizeOfUArray(),1); + assertEquals(STUnderlineValues.DOUBLE_ACCOUNTING,ctFont.getUArray(0).getVal()); + } - @Test - void testColor() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTColor color=ctFont.addNewColor(); - color.setIndexed(XSSFFont.DEFAULT_FONT_COLOR); - ctFont.setColorArray(0,color); + @Test + void testColor() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTColor color=ctFont.addNewColor(); + color.setIndexed(XSSFFont.DEFAULT_FONT_COLOR); + ctFont.setColorArray(0,color); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(IndexedColors.BLACK.getIndex(),xssfFont.getColor()); + XSSFFont xssfFont=new XSSFFont(ctFont); + assertEquals(IndexedColors.BLACK.getIndex(),xssfFont.getColor()); - xssfFont.setColor(IndexedColors.RED.getIndex()); - assertEquals(IndexedColors.RED.getIndex(), ctFont.getColorArray(0).getIndexed()); - } + xssfFont.setColor(IndexedColors.RED.getIndex()); + assertEquals(IndexedColors.RED.getIndex(), ctFont.getColorArray(0).getIndexed()); + } - @Test - void testRgbColor() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTColor color=ctFont.addNewColor(); + @Test + void testRgbColor() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTColor color=ctFont.addNewColor(); - color.setRgb(Integer.toHexString(0xFFFFFF).getBytes(LocaleUtil.CHARSET_1252)); - ctFont.setColorArray(0,color); + color.setRgb(Integer.toHexString(0xFFFFFF).getBytes(LocaleUtil.CHARSET_1252)); + ctFont.setColorArray(0,color); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(ctFont.getColorArray(0).getRgb()[0],xssfFont.getXSSFColor().getRGB()[0]); - assertEquals(ctFont.getColorArray(0).getRgb()[1],xssfFont.getXSSFColor().getRGB()[1]); - assertEquals(ctFont.getColorArray(0).getRgb()[2],xssfFont.getXSSFColor().getRGB()[2]); - assertEquals(ctFont.getColorArray(0).getRgb()[3],xssfFont.getXSSFColor().getRGB()[3]); + XSSFFont xssfFont=new XSSFFont(ctFont); + assertEquals(ctFont.getColorArray(0).getRgb()[0],xssfFont.getXSSFColor().getRGB()[0]); + assertEquals(ctFont.getColorArray(0).getRgb()[1],xssfFont.getXSSFColor().getRGB()[1]); + assertEquals(ctFont.getColorArray(0).getRgb()[2],xssfFont.getXSSFColor().getRGB()[2]); + assertEquals(ctFont.getColorArray(0).getRgb()[3],xssfFont.getXSSFColor().getRGB()[3]); - xssfFont.setColor((short)23); + xssfFont.setColor((short)23); - byte[] bytes = Integer.toHexString(0xF1F1F1).getBytes(LocaleUtil.CHARSET_1252); + byte[] bytes = Integer.toHexString(0xF1F1F1).getBytes(LocaleUtil.CHARSET_1252); color.setRgb(bytes); - XSSFColor newColor=XSSFColor.from(color, null); - xssfFont.setColor(newColor); - assertEquals(ctFont.getColorArray(0).getRgb()[2],newColor.getRGB()[2]); + XSSFColor newColor=XSSFColor.from(color, null); + xssfFont.setColor(newColor); + assertEquals(ctFont.getColorArray(0).getRgb()[2],newColor.getRGB()[2]); - assertArrayEquals(bytes, xssfFont.getXSSFColor().getRGB()); - assertEquals(0, xssfFont.getColor()); - } + assertArrayEquals(bytes, xssfFont.getXSSFColor().getRGB()); + assertEquals(0, xssfFont.getColor()); + } - @Test - void testThemeColor() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTColor color=ctFont.addNewColor(); - color.setTheme(1); - ctFont.setColorArray(0,color); + @Test + void testThemeColor() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTColor color=ctFont.addNewColor(); + color.setTheme(1); + ctFont.setColorArray(0,color); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(ctFont.getColorArray(0).getTheme(),xssfFont.getThemeColor()); + XSSFFont xssfFont=new XSSFFont(ctFont); + assertEquals(ctFont.getColorArray(0).getTheme(),xssfFont.getThemeColor()); - xssfFont.setThemeColor(IndexedColors.RED.getIndex()); - assertEquals(IndexedColors.RED.getIndex(),ctFont.getColorArray(0).getTheme()); - } + xssfFont.setThemeColor(IndexedColors.RED.getIndex()); + assertEquals(IndexedColors.RED.getIndex(),ctFont.getColorArray(0).getTheme()); + } - @Test - void testFamily() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontFamily family=ctFont.addNewFamily(); - family.setVal(FontFamily.MODERN.getValue()); - ctFont.setFamilyArray(0,family); + @Test + void testFamily() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTFontFamily family=ctFont.addNewFamily(); + family.setVal(FontFamily.MODERN.getValue()); + ctFont.setFamilyArray(0,family); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(FontFamily.MODERN.getValue(),xssfFont.getFamily()); - } + XSSFFont xssfFont=new XSSFFont(ctFont); + assertEquals(FontFamily.MODERN.getValue(),xssfFont.getFamily()); + } - @Test - void testScheme() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontScheme scheme=ctFont.addNewScheme(); - scheme.setVal(STFontScheme.MAJOR); - ctFont.setSchemeArray(0,scheme); + @Test + void testScheme() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTFontScheme scheme=ctFont.addNewScheme(); + scheme.setVal(STFontScheme.MAJOR); + ctFont.setSchemeArray(0,scheme); - XSSFFont font=new XSSFFont(ctFont); - assertEquals(FontScheme.MAJOR,font.getScheme()); + XSSFFont font=new XSSFFont(ctFont); + assertEquals(FontScheme.MAJOR,font.getScheme()); - font.setScheme(FontScheme.NONE); - assertEquals(STFontScheme.NONE,ctFont.getSchemeArray(0).getVal()); - } + font.setScheme(FontScheme.NONE); + assertEquals(STFontScheme.NONE,ctFont.getSchemeArray(0).getVal()); + } - @Test - void testTypeOffset() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTVerticalAlignFontProperty valign=ctFont.addNewVertAlign(); - valign.setVal(STVerticalAlignRun.BASELINE); - ctFont.setVertAlignArray(0,valign); + @Test + void testTypeOffset() { + CTFont ctFont=CTFont.Factory.newInstance(); + CTVerticalAlignFontProperty valign=ctFont.addNewVertAlign(); + valign.setVal(STVerticalAlignRun.BASELINE); + ctFont.setVertAlignArray(0,valign); - XSSFFont font=new XSSFFont(ctFont); - assertEquals(Font.SS_NONE,font.getTypeOffset()); + XSSFFont font=new XSSFFont(ctFont); + assertEquals(Font.SS_NONE,font.getTypeOffset()); - font.setTypeOffset(XSSFFont.SS_SUPER); - assertEquals(STVerticalAlignRun.SUPERSCRIPT,ctFont.getVertAlignArray(0).getVal()); - } - - // store test from TestSheetUtil here as it uses XSSF - @Test - void testCanComputeWidthXSSF() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - - // cannot check on result because on some machines we get back false here! - SheetUtil.canComputeColumnWidth(wb.getFontAt(0)); - - } + font.setTypeOffset(XSSFFont.SS_SUPER); + assertEquals(STVerticalAlignRun.SUPERSCRIPT,ctFont.getVertAlignArray(0).getVal()); } // store test from TestSheetUtil here as it uses XSSF - @Test - void testCanComputeWidthInvalidFont() { + @Test + void testCanComputeWidthXSSF() throws IOException { + try (Workbook wb = new XSSFWorkbook()) { + + // cannot check on result because on some machines we get back false here! + SheetUtil.canComputeColumnWidth(wb.getFontAt(0)); + + } + } + + // store test from TestSheetUtil here as it uses XSSF + @Test + void testCanComputeWidthInvalidFont() { Font font = new XSSFFont(CTFont.Factory.newInstance()); font.setFontName("some non existing font name"); @@ -380,120 +380,120 @@ public final class TestXSSFFont extends BaseTestFont{ SheetUtil.canComputeColumnWidth(font); } - /** - * Test that fonts get added properly - */ - @Test - void testFindFont() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - assertEquals(1, wb.getNumberOfFonts()); + /** + * Test that fonts get added properly + */ + @Test + void testFindFont() throws IOException { + try (XSSFWorkbook wb = new XSSFWorkbook()) { + assertEquals(1, wb.getNumberOfFonts()); - XSSFSheet s = wb.createSheet(); - s.createRow(0); - s.createRow(1); - s.getRow(0).createCell(0); - s.getRow(1).createCell(0); + XSSFSheet s = wb.createSheet(); + s.createRow(0); + s.createRow(1); + s.getRow(0).createCell(0); + s.getRow(1).createCell(0); - assertEquals(1, wb.getNumberOfFonts()); + assertEquals(1, wb.getNumberOfFonts()); - XSSFFont f1 = wb.getFontAt(0); - assertFalse(f1.getBold()); + XSSFFont f1 = wb.getFontAt(0); + assertFalse(f1.getBold()); - // Check that asking for the same font - // multiple times gives you the same thing. - // Otherwise, our tests wouldn't work! - assertSame(wb.getFontAt(0), wb.getFontAt(0)); - assertEquals( - wb.getFontAt(0), - wb.getFontAt(0) - ); + // Check that asking for the same font + // multiple times gives you the same thing. + // Otherwise, our tests wouldn't work! + assertSame(wb.getFontAt(0), wb.getFontAt(0)); + assertEquals( + wb.getFontAt(0), + wb.getFontAt(0) + ); - // Look for a new font we have - // yet to add - assertNull( - wb.findFont( - false, IndexedColors.INDIGO.getIndex(), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - assertNull( - wb.getStylesSource().findFont( - false, new XSSFColor(IndexedColors.INDIGO, new DefaultIndexedColorMap()), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); + // Look for a new font we have + // yet to add + assertNull( + wb.findFont( + false, IndexedColors.INDIGO.getIndex(), (short) 22, + "Thingy", false, true, (short) 2, (byte) 2 + ) + ); + assertNull( + wb.getStylesSource().findFont( + false, new XSSFColor(IndexedColors.INDIGO, new DefaultIndexedColorMap()), (short) 22, + "Thingy", false, true, (short) 2, (byte) 2 + ) + ); - XSSFFont nf = wb.createFont(); - assertEquals(2, wb.getNumberOfFonts()); + XSSFFont nf = wb.createFont(); + assertEquals(2, wb.getNumberOfFonts()); - assertEquals(1, nf.getIndex()); - assertEquals(nf, wb.getFontAt(1)); + assertEquals(1, nf.getIndex()); + assertEquals(nf, wb.getFontAt(1)); - nf.setBold(false); - nf.setColor(IndexedColors.INDIGO.getIndex()); - nf.setFontHeight((short) 22); - nf.setFontName("Thingy"); - nf.setItalic(false); - nf.setStrikeout(true); - nf.setTypeOffset((short) 2); - nf.setUnderline((byte) 2); + nf.setBold(false); + nf.setColor(IndexedColors.INDIGO.getIndex()); + nf.setFontHeight((short) 22); + nf.setFontName("Thingy"); + nf.setItalic(false); + nf.setStrikeout(true); + nf.setTypeOffset((short) 2); + nf.setUnderline((byte) 2); - assertEquals(2, wb.getNumberOfFonts()); - assertEquals(nf, wb.getFontAt(1)); + assertEquals(2, wb.getNumberOfFonts()); + assertEquals(nf, wb.getFontAt(1)); - assertNotSame(wb.getFontAt(0), wb.getFontAt(1)); + assertNotSame(wb.getFontAt(0), wb.getFontAt(1)); - // Find it now - assertNotNull( - wb.findFont( - false, IndexedColors.INDIGO.getIndex(), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - assertNotNull( - wb.getStylesSource().findFont( - false, new XSSFColor(IndexedColors.INDIGO, new DefaultIndexedColorMap()), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); + // Find it now + assertNotNull( + wb.findFont( + false, IndexedColors.INDIGO.getIndex(), (short) 22, + "Thingy", false, true, (short) 2, (byte) 2 + ) + ); + assertNotNull( + wb.getStylesSource().findFont( + false, new XSSFColor(IndexedColors.INDIGO, new DefaultIndexedColorMap()), (short) 22, + "Thingy", false, true, (short) 2, (byte) 2 + ) + ); - XSSFFont font = wb.findFont( - false, IndexedColors.INDIGO.getIndex(), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ); - assertNotNull(font); - assertEquals( - 1, - font.getIndex() - ); - assertEquals(nf, - wb.findFont( - false, IndexedColors.INDIGO.getIndex(), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - assertEquals(nf, - wb.getStylesSource().findFont( - false, new XSSFColor(IndexedColors.INDIGO, new DefaultIndexedColorMap()), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); + XSSFFont font = wb.findFont( + false, IndexedColors.INDIGO.getIndex(), (short) 22, + "Thingy", false, true, (short) 2, (byte) 2 + ); + assertNotNull(font); + assertEquals( + 1, + font.getIndex() + ); + assertEquals(nf, + wb.findFont( + false, IndexedColors.INDIGO.getIndex(), (short) 22, + "Thingy", false, true, (short) 2, (byte) 2 + ) + ); + assertEquals(nf, + wb.getStylesSource().findFont( + false, new XSSFColor(IndexedColors.INDIGO, new DefaultIndexedColorMap()), (short) 22, + "Thingy", false, true, (short) 2, (byte) 2 + ) + ); - } - } + } + } - @Test - void testEquals() { - XSSFFont font = new XSSFFont(); - XSSFFont equ = new XSSFFont(); - XSSFFont notequ = new XSSFFont(); - notequ.setItalic(true); + @Test + void testEquals() { + XSSFFont font = new XSSFFont(); + XSSFFont equ = new XSSFFont(); + XSSFFont notequ = new XSSFFont(); + notequ.setItalic(true); - assertEquals(equ, font); - assertNotEquals(font, notequ); + assertEquals(equ, font); + assertNotEquals(font, notequ); - notequ.setItalic(false); - notequ.setThemeColor((short)123); - assertNotEquals(font, notequ); - } + notequ.setItalic(false); + notequ.setThemeColor((short)123); + assertNotEquals(font, notequ); + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXDDFChartLegend.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXDDFChartLegend.java index bbd1ee0981..8f7bab8b41 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXDDFChartLegend.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXDDFChartLegend.java @@ -37,28 +37,28 @@ import org.junit.jupiter.api.Test; */ public final class TestXDDFChartLegend { @Test - void testLegendPositionAccessMethods() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFChartLegend legend = chart.getOrAddLegend(); + void testLegendPositionAccessMethods() throws IOException { + XSSFWorkbook wb = new XSSFWorkbook(); + XSSFSheet sheet = wb.createSheet(); + XSSFDrawing drawing = sheet.createDrawingPatriarch(); + XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); + XSSFChart chart = drawing.createChart(anchor); + XDDFChartLegend legend = chart.getOrAddLegend(); - legend.setPosition(LegendPosition.TOP_RIGHT); - assertEquals(LegendPosition.TOP_RIGHT, legend.getPosition()); + legend.setPosition(LegendPosition.TOP_RIGHT); + assertEquals(LegendPosition.TOP_RIGHT, legend.getPosition()); - wb.close(); - } + wb.close(); + } @Test void test_setOverlay_defaultChartLegend_expectOverlayInitialValueSetToFalse() throws IOException { // Arrange - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); + XSSFWorkbook wb = new XSSFWorkbook(); + XSSFSheet sheet = wb.createSheet(); + XSSFDrawing drawing = sheet.createDrawingPatriarch(); + XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); + XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); // Act @@ -72,19 +72,19 @@ public final class TestXDDFChartLegend { @Test void test_setOverlay_chartLegendSetToTrue_expectOverlayInitialValueSetToTrue() throws IOException { // Arrange - XSSFWorkbook wb = new XSSFWorkbook(); + XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFChartLegend legend = chart.getOrAddLegend(); + XSSFDrawing drawing = sheet.createDrawingPatriarch(); + XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); + XSSFChart chart = drawing.createChart(anchor); + XDDFChartLegend legend = chart.getOrAddLegend(); // Act - legend.setOverlay(true); + legend.setOverlay(true); // Assert assertTrue(legend.isOverlay()); wb.close(); - } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXDDFManualLayout.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXDDFManualLayout.java index 5954ffe7b3..422e2a0e9c 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXDDFManualLayout.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXDDFManualLayout.java @@ -55,64 +55,64 @@ public final class TestXDDFManualLayout { wb.close(); } - /* - * Accessor methods are not trivial. They use lazy underlying bean - * initialization so there can be some errors (NPE, for example). - */ + /* + * Accessor methods are not trivial. They use lazy underlying bean + * initialization so there can be some errors (NPE, for example). + */ @Test void testAccessorMethods() { - final double newRatio = 1.1; - final double newCoordinate = 0.3; - final LayoutMode nonDefaultMode = LayoutMode.FACTOR; - final LayoutTarget nonDefaultTarget = LayoutTarget.OUTER; + final double newRatio = 1.1; + final double newCoordinate = 0.3; + final LayoutMode nonDefaultMode = LayoutMode.FACTOR; + final LayoutTarget nonDefaultTarget = LayoutTarget.OUTER; - layout.setWidthRatio(newRatio); + layout.setWidthRatio(newRatio); assertEquals(layout.getWidthRatio(), newRatio, 0.0); - layout.setHeightRatio(newRatio); + layout.setHeightRatio(newRatio); assertEquals(layout.getHeightRatio(), newRatio, 0.0); - layout.setX(newCoordinate); + layout.setX(newCoordinate); assertEquals(layout.getX(), newCoordinate, 0.0); - layout.setY(newCoordinate); + layout.setY(newCoordinate); assertEquals(layout.getY(), newCoordinate, 0.0); - layout.setXMode(nonDefaultMode); + layout.setXMode(nonDefaultMode); assertSame(layout.getXMode(), nonDefaultMode); - layout.setYMode(nonDefaultMode); + layout.setYMode(nonDefaultMode); assertSame(layout.getYMode(), nonDefaultMode); - layout.setWidthMode(nonDefaultMode); + layout.setWidthMode(nonDefaultMode); assertSame(layout.getWidthMode(), nonDefaultMode); - layout.setHeightMode(nonDefaultMode); + layout.setHeightMode(nonDefaultMode); assertSame(layout.getHeightMode(), nonDefaultMode); - layout.setTarget(nonDefaultTarget); + layout.setTarget(nonDefaultTarget); assertSame(layout.getTarget(), nonDefaultTarget); - } + } - /* - * Layout must have reasonable default values and must not throw - * any exceptions. - */ + /* + * Layout must have reasonable default values and must not throw + * any exceptions. + */ @Test void testDefaultValues() { - assertNotNull(layout.getTarget()); - assertNotNull(layout.getXMode()); - assertNotNull(layout.getYMode()); - assertNotNull(layout.getHeightMode()); - assertNotNull(layout.getWidthMode()); - /* - * According to interface, 0.0 should be returned for - * uninitialized double properties. - */ + assertNotNull(layout.getTarget()); + assertNotNull(layout.getXMode()); + assertNotNull(layout.getYMode()); + assertNotNull(layout.getHeightMode()); + assertNotNull(layout.getWidthMode()); + /* + * According to interface, 0.0 should be returned for + * uninitialized double properties. + */ assertEquals(0.0, layout.getX(), 0.0); assertEquals(0.0, layout.getY(), 0.0); assertEquals(0.0, layout.getWidthRatio(), 0.0); assertEquals(0.0, layout.getHeightRatio(), 0.0); - } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java index 87d793958e..312bc8c57b 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java @@ -30,19 +30,19 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.jupiter.api.Test; public final class TestXSSFCategoryAxis { - @Test - void testAccessMethods() throws Exception { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFCategoryAxis axis = chart.createCategoryAxis(AxisPosition.BOTTOM); + @Test + void testAccessMethods() throws Exception { + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet(); + XSSFDrawing drawing = sheet.createDrawingPatriarch(); + XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); + XSSFChart chart = drawing.createChart(anchor); + XDDFCategoryAxis axis = chart.createCategoryAxis(AxisPosition.BOTTOM); - axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); + axis.setCrosses(AxisCrosses.AUTO_ZERO); + assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); - assertEquals(chart.getAxes().size(), 1); - } - } + assertEquals(chart.getAxes().size(), 1); + } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java index e98bfc1296..12ac3912b1 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java @@ -40,124 +40,124 @@ import org.junit.jupiter.api.Test; public final class TestXSSFChartAxis { - private static final double EPSILON = 1E-7; - private XSSFWorkbook wb; - private XDDFChartAxis axis; + private static final double EPSILON = 1E-7; + private XSSFWorkbook wb; + private XDDFChartAxis axis; - @BeforeEach - void setup() { - wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - axis = chart.createValueAxis(AxisPosition.BOTTOM); - } + @BeforeEach + void setup() { + wb = new XSSFWorkbook(); + XSSFSheet sheet = wb.createSheet(); + XSSFDrawing drawing = sheet.createDrawingPatriarch(); + XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); + XSSFChart chart = drawing.createChart(anchor); + axis = chart.createValueAxis(AxisPosition.BOTTOM); + } - @AfterEach - void teardown() throws IOException { - wb.close(); - wb = null; - axis = null; - } + @AfterEach + void teardown() throws IOException { + wb.close(); + wb = null; + axis = null; + } - @Test - void testLogBaseIllegalArgument() { - IllegalArgumentException iae = null; - try { - axis.setLogBase(0.0); - } catch (IllegalArgumentException e) { - iae = e; - } - assertNotNull(iae); + @Test + void testLogBaseIllegalArgument() { + IllegalArgumentException iae = null; + try { + axis.setLogBase(0.0); + } catch (IllegalArgumentException e) { + iae = e; + } + assertNotNull(iae); - iae = null; - try { - axis.setLogBase(30000.0); - } catch (IllegalArgumentException e) { - iae = e; - } - assertNotNull(iae); - } + iae = null; + try { + axis.setLogBase(30000.0); + } catch (IllegalArgumentException e) { + iae = e; + } + assertNotNull(iae); + } - @Test - void testLogBaseLegalArgument() { - axis.setLogBase(Math.E); - assertTrue(Math.abs(axis.getLogBase() - Math.E) < EPSILON); - } + @Test + void testLogBaseLegalArgument() { + axis.setLogBase(Math.E); + assertTrue(Math.abs(axis.getLogBase() - Math.E) < EPSILON); + } - @Test - void testNumberFormat() { - final String numberFormat = "General"; - axis.setNumberFormat(numberFormat); - assertEquals(numberFormat, axis.getNumberFormat()); - } + @Test + void testNumberFormat() { + final String numberFormat = "General"; + axis.setNumberFormat(numberFormat); + assertEquals(numberFormat, axis.getNumberFormat()); + } - @Test - void testMaxAndMinAccessMethods() { - final double newValue = 10.0; + @Test + void testMaxAndMinAccessMethods() { + final double newValue = 10.0; - axis.setMinimum(newValue); - assertTrue(Math.abs(axis.getMinimum() - newValue) < EPSILON); + axis.setMinimum(newValue); + assertTrue(Math.abs(axis.getMinimum() - newValue) < EPSILON); - axis.setMaximum(newValue); - assertTrue(Math.abs(axis.getMaximum() - newValue) < EPSILON); - } + axis.setMaximum(newValue); + assertTrue(Math.abs(axis.getMaximum() - newValue) < EPSILON); + } - @Test - void testVisibleAccessMethods() { - axis.setVisible(true); - assertTrue(axis.isVisible()); + @Test + void testVisibleAccessMethods() { + axis.setVisible(true); + assertTrue(axis.isVisible()); - axis.setVisible(false); - assertFalse(axis.isVisible()); - } + axis.setVisible(false); + assertFalse(axis.isVisible()); + } - @Test - void testMajorTickMarkAccessMethods() { - axis.setMajorTickMark(AxisTickMark.NONE); - assertEquals(AxisTickMark.NONE, axis.getMajorTickMark()); + @Test + void testMajorTickMarkAccessMethods() { + axis.setMajorTickMark(AxisTickMark.NONE); + assertEquals(AxisTickMark.NONE, axis.getMajorTickMark()); - axis.setMajorTickMark(AxisTickMark.IN); - assertEquals(AxisTickMark.IN, axis.getMajorTickMark()); + axis.setMajorTickMark(AxisTickMark.IN); + assertEquals(AxisTickMark.IN, axis.getMajorTickMark()); - axis.setMajorTickMark(AxisTickMark.OUT); - assertEquals(AxisTickMark.OUT, axis.getMajorTickMark()); + axis.setMajorTickMark(AxisTickMark.OUT); + assertEquals(AxisTickMark.OUT, axis.getMajorTickMark()); - axis.setMajorTickMark(AxisTickMark.CROSS); - assertEquals(AxisTickMark.CROSS, axis.getMajorTickMark()); - } + axis.setMajorTickMark(AxisTickMark.CROSS); + assertEquals(AxisTickMark.CROSS, axis.getMajorTickMark()); + } - @Test - void testMinorTickMarkAccessMethods() { - axis.setMinorTickMark(AxisTickMark.NONE); - assertEquals(AxisTickMark.NONE, axis.getMinorTickMark()); + @Test + void testMinorTickMarkAccessMethods() { + axis.setMinorTickMark(AxisTickMark.NONE); + assertEquals(AxisTickMark.NONE, axis.getMinorTickMark()); - axis.setMinorTickMark(AxisTickMark.IN); - assertEquals(AxisTickMark.IN, axis.getMinorTickMark()); + axis.setMinorTickMark(AxisTickMark.IN); + assertEquals(AxisTickMark.IN, axis.getMinorTickMark()); - axis.setMinorTickMark(AxisTickMark.OUT); - assertEquals(AxisTickMark.OUT, axis.getMinorTickMark()); + axis.setMinorTickMark(AxisTickMark.OUT); + assertEquals(AxisTickMark.OUT, axis.getMinorTickMark()); - axis.setMinorTickMark(AxisTickMark.CROSS); - assertEquals(AxisTickMark.CROSS, axis.getMinorTickMark()); - } + axis.setMinorTickMark(AxisTickMark.CROSS); + assertEquals(AxisTickMark.CROSS, axis.getMinorTickMark()); + } - @Test - void testGetChartAxisBug57362() throws IOException { - //Load existing excel with some chart on it having primary and secondary axis. - try (final XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57362.xlsx")) { - final XSSFSheet sh = workbook.getSheetAt(0); - final XSSFDrawing drawing = sh.createDrawingPatriarch(); - final XSSFChart chart = drawing.getCharts().get(0); + @Test + void testGetChartAxisBug57362() throws IOException { + //Load existing excel with some chart on it having primary and secondary axis. + try (final XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57362.xlsx")) { + final XSSFSheet sh = workbook.getSheetAt(0); + final XSSFDrawing drawing = sh.createDrawingPatriarch(); + final XSSFChart chart = drawing.getCharts().get(0); - final List axisList = chart.getAxes(); + final List axisList = chart.getAxes(); - assertEquals(4, axisList.size()); - assertNotNull(axisList.get(0)); - assertNotNull(axisList.get(1)); - assertNotNull(axisList.get(2)); - assertNotNull(axisList.get(3)); - } - } + assertEquals(4, axisList.size()); + assertNotNull(axisList.get(0)); + assertNotNull(axisList.get(1)); + assertNotNull(axisList.get(2)); + assertNotNull(axisList.get(3)); + } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java index c69af22ce4..72f3ff5ad4 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java @@ -54,8 +54,8 @@ import org.junit.jupiter.api.Test; */ class TestXSSFChartTitle { private XSSFWorkbook createWorkbookWithChart() { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("linechart"); + XSSFWorkbook wb = new XSSFWorkbook(); + XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java index 34acba6286..0175cddae2 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java @@ -31,19 +31,19 @@ import org.junit.jupiter.api.Test; public final class TestXSSFDateAxis { - @Test - void testAccessMethods() throws Exception { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFDateAxis axis = chart.createDateAxis(AxisPosition.BOTTOM); + @Test + void testAccessMethods() throws Exception { + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet(); + XSSFDrawing drawing = sheet.createDrawingPatriarch(); + XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); + XSSFChart chart = drawing.createChart(anchor); + XDDFDateAxis axis = chart.createDateAxis(AxisPosition.BOTTOM); - axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); + axis.setCrosses(AxisCrosses.AUTO_ZERO); + assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); - assertEquals(chart.getAxes().size(), 1); - } - } + assertEquals(chart.getAxes().size(), 1); + } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java index 16f0fa68fe..c6ce428fd6 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java @@ -53,8 +53,8 @@ public final class TestXSSFScatterChartData { @Test void testOneSeriePlot() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, plotData).build(); + XSSFWorkbook wb = new XSSFWorkbook(); + XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, plotData).build(); XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); XSSFChart chart = drawing.createChart(anchor); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java index bc1d6f2c50..d87057526d 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java @@ -32,22 +32,22 @@ import org.junit.jupiter.api.Test; public final class TestXSSFValueAxis { - @Test - void testAccessMethods() throws Exception { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFValueAxis axis = chart.createValueAxis(AxisPosition.BOTTOM); + @Test + void testAccessMethods() throws Exception { + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet(); + XSSFDrawing drawing = sheet.createDrawingPatriarch(); + XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); + XSSFChart chart = drawing.createChart(anchor); + XDDFValueAxis axis = chart.createValueAxis(AxisPosition.BOTTOM); - axis.setCrossBetween(AxisCrossBetween.MIDPOINT_CATEGORY); - assertEquals(axis.getCrossBetween(), AxisCrossBetween.MIDPOINT_CATEGORY); + axis.setCrossBetween(AxisCrossBetween.MIDPOINT_CATEGORY); + assertEquals(axis.getCrossBetween(), AxisCrossBetween.MIDPOINT_CATEGORY); - axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); + axis.setCrosses(AxisCrosses.AUTO_ZERO); + assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); - assertEquals(chart.getAxes().size(), 1); - } - } + assertEquals(chart.getAxes().size(), 1); + } + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java index 5f905d8e7d..820e27604d 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java @@ -30,27 +30,27 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle; class TestXSSFBorder { - @Test - void testGetBorderStyle() { - CTStylesheet stylesheet = CTStylesheet.Factory.newInstance(); - CTBorder border = stylesheet.addNewBorders().addNewBorder(); - CTBorderPr top = border.addNewTop(); - CTBorderPr right = border.addNewRight(); - CTBorderPr bottom = border.addNewBottom(); + @Test + void testGetBorderStyle() { + CTStylesheet stylesheet = CTStylesheet.Factory.newInstance(); + CTBorder border = stylesheet.addNewBorders().addNewBorder(); + CTBorderPr top = border.addNewTop(); + CTBorderPr right = border.addNewRight(); + CTBorderPr bottom = border.addNewBottom(); - top.setStyle(STBorderStyle.DASH_DOT); - right.setStyle(STBorderStyle.NONE); - bottom.setStyle(STBorderStyle.THIN); + top.setStyle(STBorderStyle.DASH_DOT); + right.setStyle(STBorderStyle.NONE); + bottom.setStyle(STBorderStyle.THIN); - XSSFCellBorder cellBorderStyle = new XSSFCellBorder(border); - assertEquals("DASH_DOT", cellBorderStyle.getBorderStyle(BorderSide.TOP).toString()); + XSSFCellBorder cellBorderStyle = new XSSFCellBorder(border); + assertEquals("DASH_DOT", cellBorderStyle.getBorderStyle(BorderSide.TOP).toString()); - assertEquals("NONE", cellBorderStyle.getBorderStyle(BorderSide.RIGHT).toString()); - assertEquals(BorderStyle.NONE.ordinal(), cellBorderStyle.getBorderStyle(BorderSide.RIGHT).ordinal()); + assertEquals("NONE", cellBorderStyle.getBorderStyle(BorderSide.RIGHT).toString()); + assertEquals(BorderStyle.NONE.ordinal(), cellBorderStyle.getBorderStyle(BorderSide.RIGHT).ordinal()); - assertEquals("THIN", cellBorderStyle.getBorderStyle(BorderSide.BOTTOM).toString()); + assertEquals("THIN", cellBorderStyle.getBorderStyle(BorderSide.BOTTOM).toString()); - assertEquals(BorderStyle.THIN.ordinal(), cellBorderStyle.getBorderStyle(BorderSide.BOTTOM).ordinal()); - } + assertEquals(BorderStyle.THIN.ordinal(), cellBorderStyle.getBorderStyle(BorderSide.BOTTOM).ordinal()); + } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/TestDocumentProtection.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/TestDocumentProtection.java index 4aac209eb9..1f7aca347f 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/TestDocumentProtection.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/TestDocumentProtection.java @@ -83,7 +83,7 @@ class TestDocumentProtection { @Test void testShouldEnforceForReadOnly() throws IOException { - // XWPFDocument document = createDocumentFromSampleFile("test-data/document/documentProtection_no_protection.docx"); + // XWPFDocument document = createDocumentFromSampleFile("test-data/document/documentProtection_no_protection.docx"); XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); assertFalse(document.isEnforcedReadonlyProtection()); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java index db1b969b58..887f53dbd7 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java @@ -454,21 +454,21 @@ public final class TestXWPFDocument { doc.close(); } - @Test - void testEnforcedWith() throws IOException { + @Test + void testEnforcedWith() throws IOException { try (XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("EnforcedWith.docx")) { assertTrue(docx.isEnforcedProtection()); } } - @Test - @Disabled("XWPF should be able to write to a new Stream when opened Read-Only") - void testWriteFromReadOnlyOPC() throws Exception { - OPCPackage opc = OPCPackage.open( - POIDataSamples.getDocumentInstance().getFile("SampleDoc.docx"), - PackageAccess.READ - ); - XWPFDocument doc = new XWPFDocument(opc); + @Test + @Disabled("XWPF should be able to write to a new Stream when opened Read-Only") + void testWriteFromReadOnlyOPC() throws Exception { + OPCPackage opc = OPCPackage.open( + POIDataSamples.getDocumentInstance().getFile("SampleDoc.docx"), + PackageAccess.READ + ); + XWPFDocument doc = new XWPFDocument(opc); final String origText; try (XWPFWordExtractor ext = new XWPFWordExtractor(doc)) { diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java index adee241f69..5c3b3d593a 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java @@ -47,19 +47,19 @@ public final class TestXWPFHeadings { doc.createTOC(); /* // TODO - finish this test - if (false) { - CTStyles styles = doc.getStyle(); - CTStyle style = styles.addNewStyle(); - style.setType(STStyleType.PARAGRAPH); - style.setStyleId("Heading1"); - } + if (false) { + CTStyles styles = doc.getStyle(); + CTStyle style = styles.addNewStyle(); + style.setType(STStyleType.PARAGRAPH); + style.setStyleId("Heading1"); + } - if (false) { - File file = TempFile.createTempFile("testHeaders", ".docx"); - OutputStream out = new FileOutputStream(file); - doc.write(out); - out.close(); - } + if (false) { + File file = TempFile.createTempFile("testHeaders", ".docx"); + OutputStream out = new FileOutputStream(file); + doc.write(out); + out.close(); + } */ } }