aboutsummaryrefslogtreecommitdiffstats
path: root/src/ooxml/testcases/org/apache/poi/openxml4j
diff options
context:
space:
mode:
authorAndreas Beeker <kiwiwings@apache.org>2021-03-27 14:03:16 +0000
committerAndreas Beeker <kiwiwings@apache.org>2021-03-27 14:03:16 +0000
commit37791e4bdfc706aa5684745594260f243b4be7ee (patch)
treea8dd8d0976fc478074d52cd3de79e0e6b5e6a33a /src/ooxml/testcases/org/apache/poi/openxml4j
parent2bb3839bfe3e3bacff79f8157465633e311239ce (diff)
downloadpoi-37791e4bdfc706aa5684745594260f243b4be7ee.tar.gz
poi-37791e4bdfc706aa5684745594260f243b4be7ee.zip
65206 - Migrate ant / maven to gradle build
update gradle files and project structure along https://github.com/centic9/poi/tree/gradle_build remove eclipse IDE project files remove obsolete record generator files git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1888111 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'src/ooxml/testcases/org/apache/poi/openxml4j')
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java58
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java227
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java58
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java104
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java1102
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java323
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java36
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java61
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java146
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java442
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java163
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java300
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java167
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java223
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java196
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java72
-rw-r--r--src/ooxml/testcases/org/apache/poi/openxml4j/util/TestZipSecureFile.java50
17 files changed, 0 insertions, 3728 deletions
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java b/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java
deleted file mode 100644
index 1c6b942a58..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.util.TempFile;
-
-import java.io.File;
-import java.io.InputStream;
-import java.io.IOException;
-
-/**
- * Centralises logic for finding/opening sample files for ooxml4j unit tests
- */
-public final class OpenXML4JTestDataSamples {
- private static final POIDataSamples _samples = POIDataSamples.getOpenXML4JInstance();
-
- 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 File getSampleFile(String sampleFileName) {
- return _samples.getFile(sampleFileName);
- }
-
- public static File getOutputFile(String outputFileName) throws IOException {
- String suffix = outputFileName.substring(outputFileName.lastIndexOf('.'));
- return TempFile.createTempFile(outputFileName, suffix);
- }
-
-
- public static InputStream openComplianceSampleStream(String sampleFileName) {
- return _samples.openResourceAsStream(sampleFileName);
- }
-
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java
deleted file mode 100644
index 7847507017..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc;
-
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import java.io.InputStream;
-
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.openxml4j.opc.internal.ContentType;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.ValueSource;
-
-/**
- * Tests for content type (ContentType class).
- */
-public final class TestContentType {
-
- private static final String FEATURE_DISALLOW_DOCTYPE_DECL = "http://apache.org/xml/features/disallow-doctype-decl";
-
- /**
- * Check rule M1.13: Package implementers shall only create and only
- * recognize parts with a content type; format designers shall specify a
- * content type for each part included in the format. Content types for
- * package parts shall fit the definition and syntax for media types as
- * specified in RFC 2616, \u00A73.7.
- */
- @ParameterizedTest
- @ValueSource(strings = {"text/xml", "application/pgp-key", "application/vnd.hp-PCLXL", "application/vnd.lotus-1-2-3"})
- void testContentTypeValidation(String contentType) throws InvalidFormatException {
- assertDoesNotThrow(() -> new ContentType(contentType));
- }
-
- /**
- * Check rule M1.13 : Package implementers shall only create and only
- * recognize parts with a content type; format designers shall specify a
- * content type for each part included in the format. Content types for
- * package parts shall fit the definition and syntax for media types as
- * specified in RFC 2616, \u00A3.7.
- * <p>
- * Check rule M1.14: Content types shall not use linear white space either
- * between the type and subtype or between an attribute and its value.
- * Content types also shall not have leading or trailing white spaces.
- * Package implementers shall create only such content types and shall
- * require such content types when retrieving a part from a package; format
- * designers shall specify only such content types for inclusion in the
- * format.
- */
- @ParameterizedTest
- @ValueSource(strings = {"text/xml/app", "",
- "test", "text(xml/xml", "text)xml/xml", "text<xml/xml",
- "text>/xml", "text@/xml", "text,/xml", "text;/xml",
- "text:/xml", "text\\/xml", "t/ext/xml", "t\"ext/xml",
- "text[/xml", "text]/xml", "text?/xml", "tex=t/xml",
- "te{xt/xml", "tex}t/xml", "te xt/xml",
- "text\u0009/xml", "text xml", " text/xml "})
- void testContentTypeValidationFailure(String contentType) {
- assertThrows(InvalidFormatException.class, () -> new ContentType(contentType),
- "Must have fail for content type: '" + contentType + "' !");
- }
-
- /**
- * Parameters are allowed, provides that they meet the
- * criteria of rule [01.2]
- * Invalid parameters are verified as incorrect in
- * {@link #testContentTypeParameterFailure()}
- */
- @ParameterizedTest
- @ValueSource(strings = {"mail/toto;titi=tata",
- "text/xml;a=b;c=d", "text/xml;key1=param1;key2=param2",
- "application/pgp-key;version=\"2\"",
- "application/x-resqml+xml;version=2.0;type=obj_global2dCrs"})
- void testContentTypeParam(String contentType) {
- assertDoesNotThrow(() -> new ContentType(contentType));
- }
-
- /**
- * Check rule [O1.2]: Format designers might restrict the usage of
- * parameters for content types.
- */
- @ParameterizedTest
- @ValueSource(strings = {
- "mail/toto;\"titi=tata\"", // quotes not allowed like that
- "mail/toto;titi = tata", // spaces not allowed
- "text/\u0080" // characters above ASCII are not allowed
- })
- void testContentTypeParameterFailure(String contentType) {
- assertThrows(InvalidFormatException.class, () -> new ContentType(contentType),
- "Must have fail for content type: '" + contentType + "' !");
- }
-
- /**
- * Check 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.
- */
- @ParameterizedTest
- @ValueSource(strings = {"text/xml(comment)"})
- void testContentTypeCommentFailure(String contentType) {
- assertThrows(InvalidFormatException.class, () -> new ContentType(contentType),
- "Must have fail for content type: '" + contentType + "' !");
- }
-
- /**
- * OOXML content types don't need entities and we shouldn't
- * barf if we get one from a third party system that added them
- * (expected = InvalidFormatException.class)
- */
- @Test
- void testFileWithContentTypeEntities() throws Exception {
- try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("ContentTypeHasEntities.ooxml")) {
- if (isOldXercesActive()) {
- OPCPackage.open(is);
- } else {
- assertThrows(InvalidFormatException.class, () -> OPCPackage.open(is));
- }
- }
- }
-
- /**
- * Check that we can open a file where there are valid
- * parameters on a content type
- */
- @Test
- void testFileWithContentTypeParams() throws Exception {
- try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("ContentTypeHasParameters.ooxml");
- OPCPackage p = OPCPackage.open(is)) {
-
- final String typeResqml = "application/x-resqml+xml";
-
- // Check the types on everything
- for (PackagePart part : p.getParts()) {
- final String contentType = part.getContentType();
- final ContentType details = part.getContentTypeDetails();
- final int length = details.getParameterKeys().length;
- final boolean hasParameters = details.hasParameters();
-
- // _rels type doesn't have any params
- if (part.isRelationshipPart()) {
- assertEquals(ContentTypes.RELATIONSHIPS_PART, contentType);
- assertEquals(ContentTypes.RELATIONSHIPS_PART, details.toString());
- assertFalse(hasParameters);
- assertEquals(0, length);
- }
- // Core type doesn't have any params
- else if (part.getPartName().toString().equals("/docProps/core.xml")) {
- assertEquals(ContentTypes.CORE_PROPERTIES_PART, contentType);
- assertEquals(ContentTypes.CORE_PROPERTIES_PART, details.toString());
- assertFalse(hasParameters);
- assertEquals(0, length);
- }
- // Global Crs types do have params
- else if (part.getPartName().toString().equals("/global1dCrs.xml")) {
- assertTrue(part.getContentType().startsWith(typeResqml));
- assertEquals(typeResqml, details.toString(false));
- assertTrue(hasParameters);
- assertContains("version=2.0", details.toString());
- assertContains("type=obj_global1dCrs", details.toString());
- assertEquals(2, length);
- assertEquals("2.0", details.getParameter("version"));
- assertEquals("obj_global1dCrs", details.getParameter("type"));
- } else if (part.getPartName().toString().equals("/global2dCrs.xml")) {
- assertTrue(part.getContentType().startsWith(typeResqml));
- assertEquals(typeResqml, details.toString(false));
- assertTrue(hasParameters);
- assertContains("version=2.0", details.toString());
- assertContains("type=obj_global2dCrs", details.toString());
- assertEquals(2, length);
- assertEquals("2.0", details.getParameter("version"));
- assertEquals("obj_global2dCrs", details.getParameter("type"));
- }
- // Other thingy
- else if (part.getPartName().toString().equals("/myTestingGuid.xml")) {
- assertTrue(part.getContentType().startsWith(typeResqml));
- assertEquals(typeResqml, details.toString(false));
- assertTrue(hasParameters);
- assertContains("version=2.0", details.toString());
- assertContains("type=obj_tectonicBoundaryFeature", details.toString());
- assertEquals(2, length);
- assertEquals("2.0", details.getParameter("version"));
- assertEquals("obj_tectonicBoundaryFeature", details.getParameter("type"));
- }
- // That should be it!
- else {
- fail("Unexpected part " + part);
- }
- }
- }
- }
-
- private static void assertContains(String needle, String haystack) {
- assertTrue(haystack.contains(needle));
- }
-
- public static boolean isOldXercesActive() {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- try {
- dbf.setFeature(FEATURE_DISALLOW_DOCTYPE_DECL, true);
- return false;
- } catch (Exception|AbstractMethodError ignored) {}
- return true;
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java
deleted file mode 100644
index 7a5d012fed..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.File;
-import java.util.TreeMap;
-
-import org.apache.poi.openxml4j.opc.internal.FileHelper;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test TestFileHelper class.
- *
- * @author Julien Chable
- */
-public final class TestFileHelper {
-
- /**
- * TODO - use simple JDK methods on {@link File} instead:<br>
- * {@link File#getParentFile()} instead of {@link FileHelper#getDirectory(File)
- * {@link File#getName()} instead of {@link FileHelper#getFilename(File)
- */
- @Test
- void testGetDirectory() {
- TreeMap<String, String> 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));
-
-// 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/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java
deleted file mode 100644
index 481ce98620..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.TreeMap;
-
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-public final class TestListParts {
- private static final Logger LOG = LogManager.getLogger(TestListParts.class);
-
- private TreeMap<PackagePartName, String> expectedValues;
-
- private TreeMap<PackagePartName, String> values;
-
- @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");
-
- 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)) {
-
- 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));
- }
- }
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java
deleted file mode 100644
index 9f297f66c6..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java
+++ /dev/null
@@ -1,1102 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc;
-
-import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getOutputFile;
-import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFile;
-import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFileName;
-import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream;
-import static org.apache.poi.openxml4j.opc.PackagingURIHelper.createPartName;
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PushbackInputStream;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.TreeMap;
-import java.util.function.BiConsumer;
-import java.util.regex.Pattern;
-import java.util.stream.Stream;
-
-import com.google.common.hash.Hashing;
-import com.google.common.io.Files;
-import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
-import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
-import org.apache.commons.compress.archivers.zip.ZipFile;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.POITestCase;
-import org.apache.poi.extractor.ExtractorFactory;
-import org.apache.poi.extractor.POITextExtractor;
-import org.apache.poi.ooxml.POIXMLException;
-import org.apache.poi.ooxml.util.DocumentHelper;
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
-import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException;
-import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
-import org.apache.poi.openxml4j.opc.internal.FileHelper;
-import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
-import org.apache.poi.openxml4j.opc.internal.ZipHelper;
-import org.apache.poi.openxml4j.util.ZipSecureFile;
-import org.apache.poi.sl.usermodel.SlideShow;
-import org.apache.poi.sl.usermodel.SlideShowFactory;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.ss.usermodel.WorkbookFactory;
-import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.TempFile;
-import org.apache.poi.xssf.XSSFTestDataSamples;
-import org.apache.poi.xssf.streaming.SXSSFWorkbook;
-import org.apache.poi.xssf.usermodel.XSSFRelation;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import org.apache.poi.xwpf.usermodel.XWPFRelation;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.function.Executable;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.CsvSource;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-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();
-
- @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");
-
- try (OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE)) {
- 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();
- }
- }
- }
-
- /**
- * Test that when we create a new Package, we give it
- * the correct default content types
- */
- @Test
- 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");
-
- // Zap the target file, in case of an earlier run
- if(targetFile.exists()) {
- assertTrue(targetFile.delete());
- }
-
- // Create a package
- OPCPackage pkg = OPCPackage.create(targetFile);
- PackagePartName corePartName = createPartName("/word/document.xml");
-
- pkg.addRelationship(corePartName, TargetMode.INTERNAL,
- PackageRelationshipTypes.CORE_DOCUMENT, "rId1");
-
- PackagePart corePart = pkg.createPart(corePartName, XWPFRelation.DOCUMENT.getContentType());
-
- 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");
- elDocument.appendChild(elBody);
- Element elParagraph = doc.createElementNS(NS_OOXML_WP_MAIN, "w:p");
- elBody.appendChild(elParagraph);
- Element elRun = doc.createElementNS(NS_OOXML_WP_MAIN, "w:r");
- elParagraph.appendChild(elRun);
- Element elText = doc.createElementNS(NS_OOXML_WP_MAIN, "w:t");
- elRun.appendChild(elText);
- elText.setTextContent("Hello Open XML !");
-
- StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
- pkg.close();
-
- 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
- */
- @Test
- void createPackageWithCoreDocument() throws IOException, InvalidFormatException, URISyntaxException, SAXException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- 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("<dummy-xml />".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);
-
- PackagePart part = pkg.createPart(sheetPartName, XSSFRelation.WORKSHEET.getContentType());
- assertNotNull(part);
-
- // Dummy content again
- try (OutputStream coreOut = corePart.getOutputStream()) {
- coreOut.write("<dummy-xml2 />".getBytes(StandardCharsets.UTF_8));
- }
-
- //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));
- }
-
-
- // Save and re-load
- File tmp = TempFile.createTempFile("testCreatePackageWithCoreDocument", ".zip");
- 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);
- assertEquals(1, coreRels.size());
- PackageRelationship coreRel = coreRels.getRelationship(0);
-
- assertNotNull(coreRel);
- assertEquals("/", coreRel.getSourceURI().toString());
- assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString());
- 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);
- assertEquals("Sheet1!A1", rel.getTargetURI().getRawFragment());
-
- assertMSCompatibility(pkg);
- }
- }
-
- private void assertMSCompatibility(OPCPackage pkg) throws IOException, InvalidFormatException, SAXException {
- PackagePartName relName = createPartName(PackageRelationship.getContainerPartRelationship());
- PackagePart relPart = pkg.getPart(relName);
-
- Document xmlRelationshipsDoc = DocumentHelper.readDocument(relPart.getInputStream());
-
- Element root = xmlRelationshipsDoc.getDocumentElement();
- NodeList nodeList = root.getElementsByTagName(PackageRelationship.RELATIONSHIP_TAG_NAME);
- int nodeCount = nodeList.getLength();
- for (int i = 0; i < nodeCount; i++) {
- Element element = (Element) nodeList.item(i);
- String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME);
- assertTrue(value.charAt(0) != '/', "Root target must not start with a leading slash ('/'): " + value);
- }
-
- }
-
- /**
- * Test package opening.
- */
- @Test
- void openPackage() throws IOException, InvalidFormatException {
- File targetFile = getOutputFile("TestOpenPackageTMP.docx");
-
- File inputFile = getSampleFile("TestOpenPackageINPUT.docx");
-
- File expectedFile = getSampleFile("TestOpenPackageOUTPUT.docx");
-
- // Copy the input file in the output directory
- FileHelper.copyFile(inputFile, targetFile);
-
- // Create a package
- OPCPackage pkg = OPCPackage.open(targetFile.getAbsolutePath());
-
- // Modify core part
- PackagePartName corePartName = createPartName("/word/document.xml");
-
- 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())));
- }
-
- // 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");
- elDocument.appendChild(elBody);
- Element elParagraph = doc.createElementNS(NS_OOXML_WP_MAIN, "w:p");
- elBody.appendChild(elParagraph);
- Element elRun = doc.createElementNS(NS_OOXML_WP_MAIN, "w:r");
- elParagraph.appendChild(elRun);
- Element elText = doc.createElementNS(NS_OOXML_WP_MAIN, "w:t");
- elRun.appendChild(elText);
- elText.setTextContent("Hello Open XML !");
-
- StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
-
- // Save and close
- assertDoesNotThrow(pkg::close);
-
- 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
- */
- @Test
- 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);
- }
-
- // 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
- */
- @Test
- 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());
-
- // Check it has the usual bits
- assertTrue(p.hasRelationships());
- assertTrue(p.containPart(createPartName("/_rels/.rels")));
- } finally {
- p.revert();
- }
- }
- }
-
- /**
- * TODO: fix and enable
- */
- @Test
- @Disabled
- void removePartRecursive() throws IOException, InvalidFormatException, URISyntaxException {
- 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());
-
- // 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<PackagePartName, String> expectedValues = new TreeMap<>();
- final TreeMap<PackagePartName, String> 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());
-
- 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"));
-
- 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();
- }
- }
- }
-
- @Test
- void deletePartRecursive() throws InvalidFormatException, IOException {
- final TreeMap<PackagePartName, String> expectedValues = new TreeMap<>();
- final TreeMap<PackagePartName, String> 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);
-
- 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"));
-
- 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();
- }
- }
- }
-
- /**
- * Test that we can open a file by path, and then
- * write changes to it.
- */
- @Test
- 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);
- }
- // 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");
- }
- // 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);
- }
- assertTrue(tempFile.delete());
- }
-
- /**
- * Test that we can open a file by path, save it
- * to another file, then delete both
- */
- @Test
- void openFileThenSaveDelete() throws IOException, InvalidFormatException {
- File tempFile = TempFile.createTempFile("poiTesting","tmp");
- File tempFile2 = TempFile.createTempFile("poiTesting","tmp");
- File origFile = getSampleFile("TestPackageCommon.docx");
- 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);
- }
-
- // 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");
- }
-
- @Test
- void getPartsByName() throws InvalidFormatException, IOException {
- String filepath = getSampleFileName("sample.docx");
-
- try (OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE)) {
- try {
- List<PackagePart> rs = pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml"));
- HashMap<String, PackagePart> selected = new HashMap<>();
-
- 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();
- }
- }
- }
-
- @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());
- }
-
- // 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);
-
- 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();
- }
- }
- }
-
- @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<? extends Exception> exClazz = (Class<? extends Exception>)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)));
- }
- }
- }
-
- /**
- * Zip bomb handling test
- *
- * see bug #50090 / #56865
- */
- @Test
- void zipBombCreateAndHandle()
- throws IOException, EncryptedDocumentException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream(2500000);
-
- try (ZipFile zipFile = ZipHelper.openZipFile(getSampleFile("sample.xlsx"));
- ZipArchiveOutputStream append = new ZipArchiveOutputStream(bos)) {
- assertNotNull(zipFile);
-
- // first, copy contents from existing war
- Enumeration<? extends ZipArchiveEntry> 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 (eOut.getName().equals("[Content_Types].xml")) {
- ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
- IOUtils.copy(is, bos2);
- long size = bos2.size() - "</Types>".length();
- append.write(bos2.toByteArray(), 0, (int) size);
- byte[] spam = new byte[0x7FFF];
- Arrays.fill(spam, (byte) ' ');
- // 0x7FFF0000 is the maximum for 32-bit zips, but less still works
- while (size < 0x7FFF00) {
- append.write(spam);
- size += spam.length;
- }
- append.write("</Types>".getBytes(StandardCharsets.UTF_8));
- size += 8;
- eOut.setSize(size);
- } else {
- IOUtils.copy(is, append);
- }
- }
- }
- append.closeArchiveEntry();
- }
- }
-
- IOException ex = assertThrows(
- IOException.class,
- () -> WorkbookFactory.create(new ByteArrayInputStream(bos.toByteArray()))
- );
- 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 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 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 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());
- });
- }
-
- @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()"));
- }
-
- private void getZipStatsAndConsume(BiConsumer<Long,Double> 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<? extends ZipArchiveEntry> 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);
- }
- }
-
- @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());
- }
-
- try (ZipSecureFile zipFile = new ZipSecureFile(file.getAbsolutePath())) {
- assertNotNull(zipFile.getName());
- }
- }
-
- @Test
- void testMaxTextSize() {
- long before = ZipSecureFile.getMaxTextSize();
- try {
- ZipSecureFile.setMaxTextSize(12345);
- assertEquals(12345, ZipSecureFile.getMaxTextSize());
- } finally {
- ZipSecureFile.setMaxTextSize(before);
- }
- }
-
- // bug 60128
- @Test
- void testCorruptFile() {
- File file = getSampleFile("invalid.xlsx");
- 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());
- }
- }
- }
- }
-
- @Test
- void testBug56479() throws Exception {
- try (InputStream is = openSampleStream("dcterms_bug_56479.zip");
- OPCPackage p = OPCPackage.open(is)) {
-
- // 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 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));
- }
- }
-
- @Test
- void testClosingStreamOnException() throws IOException {
- File tmp = File.createTempFile("poi-test-truncated-zip", "");
-
- // 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);
- }
-
- // 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 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");
- }
-
- /**
- * 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 testTidyStreamOnInvalidFile2() throws Exception {
- openInvalidFile("SampleSS.ods", true);
- }
-
- @Test
- void testTidyStreamOnInvalidFile3() throws Exception {
- openInvalidFile("SampleSS.txt", false);
- }
-
- @Test
- void testTidyStreamOnInvalidFile4() throws Exception {
- openInvalidFile("SampleSS.txt", true);
- }
-
- @Test
- void testBug62592() throws Exception {
- try (InputStream is = openSampleStream("62592.thmx")) {
- assertThrows(InvalidFormatException.class, () -> OPCPackage.open(is));
- }
- }
-
- @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 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) {
- }
-
- @Override
- public void close() {
- fail("close should not be called here");
- }
- };
-
- 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());
- }
- }
- }
-
- @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();
-
- 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");
- });
-
- 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());
- }
-
- // 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")
-
- // assert that the number of parts remained the same
- assertEquals(pkg.getParts().size(), numPartsBefore);
- }
-
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java
deleted file mode 100644
index 317d1009a0..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.InputStream;
-import java.text.ParsePosition;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Locale;
-import java.util.Optional;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
-import org.apache.poi.util.LocaleUtil;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import org.junit.jupiter.api.Test;
-import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty;
-
-import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive;
-import static org.junit.jupiter.api.Assertions.*;
-
-public final class TestPackageCoreProperties {
- /**
- * Test package core properties getters.
- */
- @Test
- void testGetProperties() throws Exception {
- // Open the package
- @SuppressWarnings("resource")
- OPCPackage p = OPCPackage.open(OpenXML4JTestDataSamples.openSampleStream("TestPackageCoreProperiesGetters.docx"));
- compareProperties(p);
- p.revert();
- }
-
- /**
- * Test package core properties setters.
- */
- @Test
- void testSetProperties() throws Exception {
- String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCoreProperiesSetters.docx");
-
- File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx");
-
- // 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);
- df.setTimeZone(LocaleUtil.TIMEZONE_UTC);
- 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();
-
- //test various date formats
- props.setCreatedProperty("2007-05-12T08:00:00Z");
- assertEquals(dateToInsert, props.getCreatedProperty().get());
-
- props.setCreatedProperty("2007-05-12T08:00:00"); //no Z, assume Z
- assertEquals(dateToInsert, props.getCreatedProperty().get());
-
- props.setCreatedProperty("2007-05-12T08:00:00.123Z");//millis
- assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().get());
-
- props.setCreatedProperty("2007-05-12T10:00:00+0200");
- assertEquals(dateToInsert, props.getCreatedProperty().get());
-
- props.setCreatedProperty("2007-05-12T10:00:00+02:00");//colon in tz
- assertEquals(dateToInsert, props.getCreatedProperty().get());
-
- props.setCreatedProperty("2007-05-12T06:00:00-0200");
- assertEquals(dateToInsert, props.getCreatedProperty().get());
-
- props.setCreatedProperty("2015-07-27");
- assertEquals(msdf.parse("2015-07-27T00:00:00.000Z"), props.getCreatedProperty().get());
-
- props.setCreatedProperty("2007-05-12T10:00:00.123+0200");
- assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().get());
-
- 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);
- p.revert();
-
- // 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();
- 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));
-
- // Gets the core properties
- PackageProperties props = p.getPackageProperties();
- assertEquals("MyCategory", props.getCategoryProperty().get());
- assertEquals("MyContentStatus", props.getContentStatusProperty().get());
- assertEquals("MyContentType", props.getContentTypeProperty().get());
- assertEquals(expectedDate, props.getCreatedProperty().get());
- assertEquals("MyCreator", props.getCreatorProperty().get());
- assertEquals("MyDescription", props.getDescriptionProperty().get());
- assertEquals("MyIdentifier", props.getIdentifierProperty().get());
- assertEquals("MyKeywords", props.getKeywordsProperty().get());
- assertEquals("MyLanguage", props.getLanguageProperty().get());
- assertEquals("Julien Chable", props.getLastModifiedByProperty().get());
- assertEquals(expectedDate, props.getLastPrintedProperty().get());
- assertEquals(expectedDate, props.getModifiedProperty().get());
- assertEquals("2", props.getRevisionProperty().get());
- assertEquals("MySubject", props.getSubjectProperty().get());
- assertEquals("MyTitle", props.getTitleProperty().get());
- assertEquals("2", props.getVersionProperty().get());
- }
-
- @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";
- Date date = df.parse(strDate);
-
- OPCPackage pkg = new ZipPackage();
- PackagePropertiesPart props = (PackagePropertiesPart)pkg.getPackageProperties();
-
- // created
- assertEquals("", props.getCreatedPropertyString());
- assertFalse(props.getCreatedProperty().isPresent());
- props.setCreatedProperty((String)null);
- assertEquals("", props.getCreatedPropertyString());
- assertFalse(props.getCreatedProperty().isPresent());
- props.setCreatedProperty(Optional.empty());
- assertEquals("", props.getCreatedPropertyString());
- assertFalse(props.getCreatedProperty().isPresent());
- props.setCreatedProperty(Optional.of(date));
- assertEquals(strDate, props.getCreatedPropertyString());
- assertEquals(date, props.getCreatedProperty().get());
- props.setCreatedProperty(strDate);
- assertEquals(strDate, props.getCreatedPropertyString());
- assertEquals(date, props.getCreatedProperty().get());
-
- // lastPrinted
- assertEquals("", props.getLastPrintedPropertyString());
- assertFalse(props.getLastPrintedProperty().isPresent());
- props.setLastPrintedProperty((String)null);
- assertEquals("", props.getLastPrintedPropertyString());
- assertFalse(props.getLastPrintedProperty().isPresent());
- props.setLastPrintedProperty(Optional.empty());
- assertEquals("", props.getLastPrintedPropertyString());
- assertFalse(props.getLastPrintedProperty().isPresent());
- props.setLastPrintedProperty(Optional.of(date));
- assertEquals(strDate, props.getLastPrintedPropertyString());
- assertEquals(date, props.getLastPrintedProperty().get());
- props.setLastPrintedProperty(strDate);
- assertEquals(strDate, props.getLastPrintedPropertyString());
- assertEquals(date, props.getLastPrintedProperty().get());
-
- // modified
- assertFalse(props.getModifiedProperty().isPresent());
- props.setModifiedProperty((String)null);
- assertFalse(props.getModifiedProperty().isPresent());
- props.setModifiedProperty(Optional.empty());
- assertFalse(props.getModifiedProperty().isPresent());
- props.setModifiedProperty(Optional.of(date));
- assertEquals(strDate, props.getModifiedPropertyString());
- assertEquals(date, props.getModifiedProperty().get());
- props.setModifiedProperty(strDate);
- assertEquals(strDate, props.getModifiedPropertyString());
- assertEquals(date, props.getModifiedProperty().get());
-
- // Tidy
- pkg.close();
- }
-
- @Test
- void testGetPropertiesLO() throws Exception {
- // Open the package
- OPCPackage pkg1 = OPCPackage.open(OpenXML4JTestDataSamples.openSampleStream("51444.xlsx"));
- PackageProperties props1 = pkg1.getPackageProperties();
- assertFalse(props1.getTitleProperty().isPresent());
- props1.setTitleProperty("Bug 51444 fixed");
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- pkg1.save(out);
- out.close();
- pkg1.close();
-
- OPCPackage pkg2 = OPCPackage.open(new ByteArrayInputStream(out.toByteArray()));
- PackageProperties props2 = pkg2.getPackageProperties();
- props2.setTitleProperty("Bug 51444 fixed");
- pkg2.close();
- }
-
- @Test
- void testEntitiesInCoreProps_56164() throws Exception {
- try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("CorePropertiesHasEntities.ooxml");
- OPCPackage p = OPCPackage.open(is)) {
-
- // Should have 3 root relationships
- boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false;
- for (PackageRelationship pr : p.getRelationships()) {
- if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT))
- foundDocRel = true;
- if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES))
- foundCorePropRel = true;
- if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES))
- foundExtPropRel = true;
- }
- assertTrue(foundDocRel, "Core Doc Relationship not found in " + p.getRelationships());
- assertTrue(foundCorePropRel, "Core Props Relationship not found in " + p.getRelationships());
- assertTrue(foundExtPropRel, "Ext Props Relationship not found in " + p.getRelationships());
-
- // Get the Core Properties
- PackagePropertiesPart props = (PackagePropertiesPart) p.getPackageProperties();
-
- // used to resolve a value but now we ignore DTD entities for security reasons
- assertEquals(isOldXercesActive(), props.getCreatorProperty().isPresent());
- }
- }
-
- @Test
- void testListOfCustomProperties() throws Exception {
- File inp = POIDataSamples.getSpreadSheetInstance().getFile("ExcelWithAttachments.xlsm");
- OPCPackage pkg = OPCPackage.open(inp, PackageAccess.READ);
- XSSFWorkbook wb = new XSSFWorkbook(pkg);
-
- assertNotNull(wb.getProperties());
- assertNotNull(wb.getProperties().getCustomProperties());
-
- for (CTProperty prop : wb.getProperties().getCustomProperties().getUnderlyingProperties().getPropertyList()) {
- assertNotNull(prop);
- }
-
- wb.close();
- pkg.close();
- }
-
- @Test
- void testAlternateCorePropertyTimezones() throws Exception {
- InputStream is = OpenXML4JTestDataSamples.openSampleStream("OPCCompliance_CoreProperties_AlternateTimezones.docx");
- OPCPackage pkg = OPCPackage.open(is);
- PackagePropertiesPart props = (PackagePropertiesPart)pkg.getPackageProperties();
- is.close();
-
- // 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);
-
- // Check text properties first
- assertEquals("Lorem Ipsum", props.getTitleProperty().get());
- assertEquals("Apache POI", props.getCreatorProperty().get());
-
- // Created at has a +3 timezone and milliseconds
- // 2006-10-13T18:06:00.123+03:00
- // = 2006-10-13T15:06:00.123+00:00
- assertEquals("2006-10-13T15:06:00Z", props.getCreatedPropertyString());
- assertEquals("2006-10-13T15:06:00.123Z", df.format(props.getCreatedProperty().get()));
-
- // Modified at has a -13 timezone but no milliseconds
- // 2007-06-20T07:59:00-13:00
- // = 2007-06-20T20:59:00-13:00
- assertEquals("2007-06-20T20:59:00Z", props.getModifiedPropertyString());
- assertEquals("2007-06-20T20:59:00.000Z", df.format(props.getModifiedProperty().get()));
-
-
- // Ensure we can change them with other timezones and still read back OK
- props.setCreatedProperty("2007-06-20T20:57:00+13:00");
- props.setModifiedProperty("2007-06-20T20:59:00.123-13:00");
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- pkg.save(baos);
- pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()));
-
- // Check text properties first - should be unchanged
- assertEquals("Lorem Ipsum", props.getTitleProperty().get());
- assertEquals("Apache POI", props.getCreatorProperty().get());
-
- // Check the updated times
- // 2007-06-20T20:57:00+13:00
- // = 2007-06-20T07:57:00Z
- assertEquals("2007-06-20T07:57:00.000Z", df.format(props.getCreatedProperty().get()));
-
- // 2007-06-20T20:59:00.123-13:00
- // = 2007-06-21T09:59:00.123Z
- assertEquals("2007-06-21T09:59:00.123Z", df.format(props.getModifiedProperty().get()));
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java
deleted file mode 100644
index 2572aadfad..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-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());
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java
deleted file mode 100644
index e68a92d200..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc;
-
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import java.io.File;
-
-import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test the addition of thumbnail in a package.
- */
-public final class TestPackageThumbnail {
-
- /**
- * Test package addThumbnail() method.
- */
- @Test
- void testSetProperties() throws Exception {
- String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageThumbnail.docx");
-
- String imagePath = OpenXML4JTestDataSamples.getSampleFileName("thumbnail.jpg");
-
- 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 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/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java
deleted file mode 100644
index 714d81180b..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-package org.apache.poi.openxml4j.opc;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import java.net.URI;
-
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.junit.jupiter.api.Test;
-
-class TestPackagingURIHelper {
-
- /**
- * Test relativizePartName() method.
- */
- @Test
- void testRelativizeURI() throws Exception {
- URI uri1 = new URI("/word/document.xml");
- URI uri2 = new URI("/word/media/image1.gif");
- URI uri3 = new URI("/word/media/image1.gif#Sheet1!A1");
- URI uri4 = new URI("#'My%20Sheet1'!A1");
-
- // Document to image is down a directory
- URI retURI1to2 = PackagingURIHelper.relativizeURI(uri1, uri2);
- assertEquals("media/image1.gif", retURI1to2.getPath());
- // Image to document is up a directory
- URI retURI2to1 = PackagingURIHelper.relativizeURI(uri2, uri1);
- assertEquals("../document.xml", retURI2to1.getPath());
-
- // Document and CustomXML parts totally different [Julien C.]
- URI uriCustomXml = new URI("/customXml/item1.xml");
- URI uriRes = PackagingURIHelper.relativizeURI(uri1, uriCustomXml);
- assertEquals("../customXml/item1.xml", uriRes.toString());
-
- // Document to itself is the same place (empty URI)
- URI retURI2 = PackagingURIHelper.relativizeURI(uri1, uri1);
- // YK: the line below used to assert empty string which is wrong
- // if source and target are the same they should be relaitivized as the last segment,
- // see Bugzilla 51187
- assertEquals("document.xml", retURI2.getPath());
-
- // relativization against root
- URI root = new URI("/");
- uriRes = PackagingURIHelper.relativizeURI(root, uri1);
- assertEquals("/word/document.xml", uriRes.toString());
-
- //URI compatible with MS Office and OpenOffice: leading slash is removed
- uriRes = PackagingURIHelper.relativizeURI(root, uri1, true);
- assertNotNull(uriRes);
- assertEquals("word/document.xml", uriRes.toString());
-
- //preserve URI fragments
- uriRes = PackagingURIHelper.relativizeURI(uri1, uri3, true);
- assertNotNull(uriRes);
- assertEquals("media/image1.gif#Sheet1!A1", uriRes.toString());
- assertNotNull(uriRes);
- uriRes = PackagingURIHelper.relativizeURI(root, uri4, true);
- assertNotNull(uriRes);
- assertEquals("#'My%20Sheet1'!A1", uriRes.toString());
- }
-
- /**
- * Test createPartName(String, y)
- */
- @Test
- void testCreatePartNameRelativeString()
- throws InvalidFormatException {
- PackagePartName partNameToValid = PackagingURIHelper
- .createPartName("/word/media/image1.gif");
-
- OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx");
- // Base part
- PackagePartName nameBase = PackagingURIHelper
- .createPartName("/word/document.xml");
- PackagePart partBase = pkg.createPart(nameBase, ContentTypes.XML);
- // Relative part name
- PackagePartName relativeName = PackagingURIHelper.createPartName(
- "media/image1.gif", partBase);
- assertEquals(partNameToValid, relativeName, "The part name must be equal to " + partNameToValid.getName());
- pkg.revert();
- }
-
- /**
- * Test createPartName(URI, y)
- */
- @Test
- void testCreatePartNameRelativeURI() throws Exception {
- PackagePartName partNameToValid = PackagingURIHelper
- .createPartName("/word/media/image1.gif");
-
- OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx");
- // Base part
- PackagePartName nameBase = PackagingURIHelper
- .createPartName("/word/document.xml");
- PackagePart partBase = pkg.createPart(nameBase, ContentTypes.XML);
- // Relative part name
- PackagePartName relativeName = PackagingURIHelper.createPartName(
- new URI("media/image1.gif"), partBase);
- assertEquals(partNameToValid, relativeName, "The part name must be equal to " + partNameToValid.getName());
- pkg.revert();
- }
-
- @Test
- void testCreateURIFromString() throws Exception {
- String[] href = {
- "..\\\\\\cygwin\\home\\yegor\\.vim\\filetype.vim",
- "..\\Program%20Files\\AGEIA%20Technologies\\v2.3.3\\NxCooking.dll",
- "file:///D:\\seva\\1981\\r810102ns.mp3",
- "..\\cygwin\\home\\yegor\\dinom\\%5baccess%5d.2010-10-26.log",
- "#'Instructions (Text)'!B21",
- "#'性'!B21",
- "javascript://",
- "#ctl||rId16||cmdAddAction||_x0000_i1029"
- };
-
- for(String s : href){
- URI uri = PackagingURIHelper.toURI(s);
- assertNotNull(uri);
- }
- }
-
- @Test
- void test53734() throws Exception {
- URI uri = PackagingURIHelper.toURI("javascript://");
- // POI appends a trailing slash tpo avoid "Expected authority at index 13: javascript://"
- // https://issues.apache.org/bugzilla/show_bug.cgi?id=53734
- assertEquals("javascript:///", uri.toASCIIString());
- }
-
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java
deleted file mode 100644
index d80c88ae12..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java
+++ /dev/null
@@ -1,442 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc;
-
-import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream;
-import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.net.URI;
-import java.util.regex.Pattern;
-
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
-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 Logger LOG = LogManager.getLogger(TestPackageCoreProperties.class);
-
- /**
- * Test relationships are correctly loaded. This at the moment fails (as of r499)
- * whenever a document is loaded before its correspondig .rels file has been found.
- * The code in this case assumes there are no relationships defined, but it should
- * really look also for not yet loaded parts.
- */
- @Test
- void testLoadRelationships() throws Exception {
- InputStream is = openSampleStream("sample.xlsx");
- try (OPCPackage pkg = OPCPackage.open(is)) {
- LOG.atDebug().log("1: {}", pkg);
- PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
- PackageRelationship coreDocRelationship = rels.getRelationship(0);
- PackagePart corePart = pkg.getPart(coreDocRelationship);
- String[] relIds = {"rId1", "rId2", "rId3"};
- for (String relId : relIds) {
- PackageRelationship rel = corePart.getRelationship(relId);
- assertNotNull(rel);
- PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI());
- PackagePart sheetPart = pkg.getPart(relName);
- assertEquals(1, sheetPart.getRelationships().size(), "Number of relationships1 for " + sheetPart.getPartName());
- }
- }
- }
-
- /**
- * Checks that we can fetch a collection of relations by
- * type, then grab from within there by id
- */
- @Test
- void testFetchFromCollection() throws Exception {
- InputStream is = openSampleStream("ExcelWithHyperlinks.xlsx");
- try (OPCPackage pkg = OPCPackage.open(is)) {
- PackagePart sheet = pkg.getPart(
- PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));
- assertNotNull(sheet);
-
- assertTrue(sheet.hasRelationships());
- assertEquals(6, sheet.getRelationships().size());
-
- // Should have three hyperlinks, and one comment
- PackageRelationshipCollection hyperlinks =
- sheet.getRelationshipsByType(HYPERLINK_REL_TYPE);
- PackageRelationshipCollection comments =
- sheet.getRelationshipsByType(COMMENTS_REL_TYPE);
- assertEquals(3, hyperlinks.size());
- assertEquals(1, comments.size());
-
- // Check we can get bits out by id
- // Hyperlinks are rId1, rId2 and rId3
- // Comment is rId6
- assertNotNull(hyperlinks.getRelationshipByID("rId1"));
- assertNotNull(hyperlinks.getRelationshipByID("rId2"));
- assertNotNull(hyperlinks.getRelationshipByID("rId3"));
- assertNull(hyperlinks.getRelationshipByID("rId6"));
-
- assertNull(comments.getRelationshipByID("rId1"));
- assertNull(comments.getRelationshipByID("rId2"));
- assertNull(comments.getRelationshipByID("rId3"));
- assertNotNull(comments.getRelationshipByID("rId6"));
-
- assertNotNull(sheet.getRelationship("rId1"));
- assertNotNull(sheet.getRelationship("rId2"));
- assertNotNull(sheet.getRelationship("rId3"));
- assertNotNull(sheet.getRelationship("rId6"));
- }
- }
-
- /**
- * Excel uses relations on sheets to store the details of
- * external hyperlinks. Check we can load these ok.
- */
- @Test
- void testLoadExcelHyperlinkRelations() throws Exception {
- InputStream is = openSampleStream("ExcelWithHyperlinks.xlsx");
- try (OPCPackage pkg = OPCPackage.open(is)) {
- PackagePart sheet = pkg.getPart(
- PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));
- assertNotNull(sheet);
-
- // rId1 is url
- PackageRelationship url = sheet.getRelationship("rId1");
- assertNotNull(url);
- assertEquals("rId1", url.getId());
- assertEquals("/xl/worksheets/sheet1.xml", url.getSourceURI().toString());
- assertEquals("http://poi.apache.org/", url.getTargetURI().toString());
-
- // rId2 is file
- PackageRelationship file = sheet.getRelationship("rId2");
- assertNotNull(file);
- assertEquals("rId2", file.getId());
- assertEquals("/xl/worksheets/sheet1.xml", file.getSourceURI().toString());
- assertEquals("WithVariousData.xlsx", file.getTargetURI().toString());
-
- // rId3 is mailto
- PackageRelationship mailto = sheet.getRelationship("rId3");
- assertNotNull(mailto);
- assertEquals("rId3", mailto.getId());
- assertEquals("/xl/worksheets/sheet1.xml", mailto.getSourceURI().toString());
- assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", mailto.getTargetURI().toString());
- }
- }
-
- /*
- * Excel uses relations on sheets to store the details of
- * external hyperlinks. Check we can create these OK,
- * then still read them later
- */
- @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);
-
- 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);
-
- // Check they were added properly
- assertNotNull(openxml4j);
- assertNotNull(sf);
- assertNotNull(file);
-
- 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://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());
-
- // 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
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- pkg.save(baos);
-
- // use revert to not re-write the input file
- pkg.revert();
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- pkg = OPCPackage.open(bais);
-
- // Check again
- sheet = pkg.getPart(
- PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));
-
- 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://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
- void testCreateRelationsFromScratch() throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- OPCPackage pkg = OPCPackage.create(baos);
-
- PackagePart partA =
- pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain");
- PackagePart partB =
- pkg.createPart(PackagingURIHelper.createPartName("/partB"), "image/png");
- assertNotNull(partA);
- assertNotNull(partB);
-
- // Internal
- partA.addRelationship(partB.getPartName(), TargetMode.INTERNAL, "http://example/Rel");
-
- // External
- partA.addExternalRelationship("http://poi.apache.org/", "http://example/poi");
- partB.addExternalRelationship("http://poi.apache.org/ss/", "http://example/poi/ss");
-
- // Check as expected currently
- assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString());
- assertEquals("http://poi.apache.org/",
- partA.getRelationship("rId2").getTargetURI().toString());
- assertEquals("http://poi.apache.org/ss/",
- partB.getRelationship("rId1").getTargetURI().toString());
-
-
- // Save, and re-load
- pkg.close();
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- pkg = OPCPackage.open(bais);
-
- partA = pkg.getPart(PackagingURIHelper.createPartName("/partA"));
- partB = pkg.getPart(PackagingURIHelper.createPartName("/partB"));
-
-
- // Check the relations
- assertEquals(2, partA.getRelationships().size());
- assertEquals(1, partB.getRelationships().size());
-
- assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString());
- assertEquals("http://poi.apache.org/",
- partA.getRelationship("rId2").getTargetURI().toString());
- assertEquals("http://poi.apache.org/ss/",
- partB.getRelationship("rId1").getTargetURI().toString());
- // Check core too
- PackageRelationship relationship = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_PROPERTIES).getRelationship(0);
- assertNotNull(relationship);
- assertEquals("/docProps/core.xml", relationship.getTargetURI().toString());
-
- // Add some more
- partB.addExternalRelationship("http://poi.apache.org/new", "http://example/poi/new");
- partB.addExternalRelationship("http://poi.apache.org/alt", "http://example/poi/alt");
-
- // Check the relations
- assertEquals(2, partA.getRelationships().size());
- assertEquals(3, partB.getRelationships().size());
-
- assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString());
- assertEquals("http://poi.apache.org/",
- partA.getRelationship("rId2").getTargetURI().toString());
- assertEquals("http://poi.apache.org/ss/",
- partB.getRelationship("rId1").getTargetURI().toString());
- assertEquals("http://poi.apache.org/new",
- partB.getRelationship("rId2").getTargetURI().toString());
- assertEquals("http://poi.apache.org/alt",
- partB.getRelationship("rId3").getTargetURI().toString());
- }
-
- @Test
- void testTargetWithSpecialChars() throws Exception{
- OPCPackage pkg;
-
- String filepath = OpenXML4JTestDataSamples.getSampleFileName("50154.xlsx");
- pkg = OPCPackage.open(filepath);
- assert_50154(pkg);
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- pkg.save(baos);
-
- // use revert to not re-write the input file
- pkg.revert();
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- pkg = OPCPackage.open(bais);
-
- assert_50154(pkg);
- }
-
- private void assert_50154(OPCPackage pkg) throws Exception {
- URI drawingURI = new URI("/xl/drawings/drawing1.xml");
- PackagePart drawingPart = pkg.getPart(PackagingURIHelper.createPartName(drawingURI));
- PackageRelationshipCollection drawingRels = drawingPart.getRelationships();
-
- assertEquals(6, drawingRels.size());
-
- // expected one image
- assertEquals(1, drawingPart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image").size());
- // and three hyperlinks
- assertEquals(5, drawingPart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink").size());
-
- PackageRelationship rId1 = drawingPart.getRelationship("rId1");
- URI parent = drawingPart.getPartName().getURI();
- URI rel1 = parent.relativize(rId1.getTargetURI());
- URI rel11 = PackagingURIHelper.relativizeURI(drawingPart.getPartName().getURI(), rId1.getTargetURI());
- assertEquals("'Another Sheet'!A1", rel1.getFragment());
- assertEquals("'Another Sheet'!A1", rel11.getFragment());
-
- PackageRelationship rId2 = drawingPart.getRelationship("rId2");
- URI rel2 = PackagingURIHelper.relativizeURI(drawingPart.getPartName().getURI(), rId2.getTargetURI());
- assertEquals("../media/image1.png", rel2.getPath());
-
- PackageRelationship rId3 = drawingPart.getRelationship("rId3");
- URI rel3 = parent.relativize(rId3.getTargetURI());
- assertEquals("ThirdSheet!A1", rel3.getFragment());
-
- PackageRelationship rId4 = drawingPart.getRelationship("rId4");
- URI rel4 = parent.relativize(rId4.getTargetURI());
- assertEquals("'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A1", rel4.getFragment());
-
- PackageRelationship rId5 = drawingPart.getRelationship("rId5");
- URI rel5 = parent.relativize(rId5.getTargetURI());
- // back slashed have been replaced with forward
- assertEquals("file:///D:/chan-chan.mp3", rel5.toString());
-
- PackageRelationship rId6 = drawingPart.getRelationship("rId6");
- URI rel6 = parent.relativize(rId6.getTargetURI());
- assertEquals("../../../../../../../cygwin/home/yegor/dinom/&&&[access].2010-10-26.log", rel6.getPath());
- assertEquals("'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A5", rel6.getFragment());
- }
-
- @Test
- void testSelfRelations_bug51187() throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PackageRelationship rel1;
- try (OPCPackage pkg = OPCPackage.create(baos)) {
-
- PackagePart partA =
- pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain");
- assertNotNull(partA);
-
- // reference itself
- rel1 = partA.addRelationship(partA.getPartName(), TargetMode.INTERNAL, "partA");
-
-
- // Save, and re-load
- }
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- try (OPCPackage pkg = OPCPackage.open(bais)) {
- PackagePart partA = pkg.getPart(PackagingURIHelper.createPartName("/partA"));
-
-
- // Check the relations
- assertEquals(1, partA.getRelationships().size());
-
- PackageRelationship rel2 = partA.getRelationships().getRelationship(0);
-
- assertNotNull(rel2);
- assertEquals(rel1.getRelationshipType(), rel2.getRelationshipType());
- assertEquals(rel1.getId(), rel2.getId());
- assertEquals(rel1.getSourceURI(), rel2.getSourceURI());
- assertEquals(rel1.getTargetURI(), rel2.getTargetURI());
- assertEquals(rel1.getTargetMode(), rel2.getTargetMode());
- }
- }
-
- @Test
- void testTrailingSpacesInURI_53282() throws Exception {
- try (InputStream is = openSampleStream("53282.xlsx");
- OPCPackage pkg1 = OPCPackage.open(is)) {
-
- PackageRelationshipCollection sheetRels = pkg1.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships();
- assertEquals(3, sheetRels.size());
- PackageRelationship rId1 = sheetRels.getRelationshipByID("rId1");
- assertEquals(TargetMode.EXTERNAL, rId1.getTargetMode());
- URI targetUri = rId1.getTargetURI();
- assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString());
- assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart());
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- pkg1.save(out);
- out.close();
-
- try (OPCPackage pkg2 = OPCPackage.open(new ByteArrayInputStream(out.toByteArray()))) {
- sheetRels = pkg2.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships();
- assertEquals(3, sheetRels.size());
- rId1 = sheetRels.getRelationshipByID("rId1");
- assertEquals(TargetMode.EXTERNAL, rId1.getTargetMode());
- targetUri = rId1.getTargetURI();
- assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString());
- assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart());
- }
- }
- }
-
- @Test
- void testEntitiesInRels_56164() throws Exception {
- try (InputStream is = openSampleStream("PackageRelsHasEntities.ooxml");
- OPCPackage p = OPCPackage.open(is)) {
-
- // Should have 3 root relationships
- boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false;
- for (PackageRelationship pr : p.getRelationships()) {
- foundDocRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT);
- foundCorePropRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES);
- foundExtPropRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES);
- }
- assertEquals(isOldXercesActive(), foundDocRel, "Core Doc Relationship not found in " + p.getRelationships());
- assertEquals(isOldXercesActive(), foundCorePropRel, "Core Props Relationship not found in " + p.getRelationships());
- assertEquals(isOldXercesActive(), foundExtPropRel, "Ext Props Relationship not found in " + p.getRelationships());
- }
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java
deleted file mode 100644
index fcc6e3cff8..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc;
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.util.Set;
-import java.util.TreeMap;
-
-import org.apache.commons.compress.archivers.ArchiveEntry;
-import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
-import org.apache.poi.util.IOUtils;
-import org.junit.jupiter.api.Assertions;
-import org.xmlunit.builder.DiffBuilder;
-import org.xmlunit.builder.Input;
-import org.xmlunit.diff.Comparison;
-import org.xmlunit.diff.ComparisonResult;
-import org.xmlunit.diff.DefaultNodeMatcher;
-import org.xmlunit.diff.Diff;
-import org.xmlunit.diff.DifferenceEvaluator;
-import org.xmlunit.diff.ElementSelectors;
-
-/**
- * Compare the contents of 2 zip files.
- */
-public final class ZipFileAssert {
- private ZipFileAssert() {
- }
-
- private static void equals(
- TreeMap<String, ByteArrayOutputStream> file1,
- TreeMap<String, ByteArrayOutputStream> file2) {
- Set<String> listFile1 = file1.keySet();
- Assertions.assertEquals(listFile1.size(), file2.keySet().size(), "not the same number of files in zip:");
-
- for (String fileName : listFile1) {
- // extract the contents for both
- ByteArrayOutputStream contain1 = file1.get(fileName);
- ByteArrayOutputStream contain2 = file2.get(fileName);
-
- assertNotNull(contain2, fileName + " not found in 2nd zip");
- // no need to check for contain1. The key come from it
-
- if (fileName.matches(".*\\.(xml|rels)$")) {
- // we have a xml file
- final Diff diff = DiffBuilder.
- compare(Input.fromByteArray(contain1.toByteArray())).
- withTest(Input.fromByteArray(contain2.toByteArray())).
- ignoreWhitespace().
- checkForSimilar().
- withDifferenceEvaluator(new IgnoreXMLDeclEvaluator()).
- withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes, ElementSelectors.byNameAndText)).
- build();
- assertFalse(diff.hasDifferences(), fileName+": "+diff.toString());
- } else {
- // not xml, may be an image or other binary format
- Assertions.assertEquals(contain1.size(), contain2.size(), fileName + " does not have the same size in both zip:");
- assertArrayEquals(contain1.toByteArray(), contain2.toByteArray(), "contents differ");
- }
- }
- }
-
- private static TreeMap<String, ByteArrayOutputStream> decompress(
- File filename) throws IOException {
- // store the zip content in memory
- // let s assume it is not Go ;-)
- TreeMap<String, ByteArrayOutputStream> zipContent = new TreeMap<>();
-
- try (
- /* Open file to decompress */
- FileInputStream file_decompress = new FileInputStream(filename);
-
- /* Create a buffer for the decompressed files */
- BufferedInputStream buffi = new BufferedInputStream(file_decompress);
-
- /* Open the file with the buffer */
- ZipArchiveInputStream zis = new ZipArchiveInputStream(buffi)
- ) {
-
- /* Processing entries of the zip file */
- ArchiveEntry entree;
- while ((entree = zis.getNextEntry()) != null) {
-
- /* Create a array for the current entry */
- ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
- IOUtils.copy(zis, byteArray);
- zipContent.put(entree.getName(), byteArray);
- }
-
- }
-
- return zipContent;
- }
-
- /**
- * Asserts that two files are equal. Throws an <tt>AssertionFailedError</tt>
- * if they are not.
- * <p>
- *
- */
- public static void assertEquals(File expected, File actual) {
- assertNotNull(expected);
- assertNotNull(actual);
-
- assertTrue(expected.exists(), "File does not exist [" + expected.getAbsolutePath() + "]");
- assertTrue(actual.exists(), "File does not exist [" + actual.getAbsolutePath() + "]");
- assertTrue(expected.canRead(), "Expected file not readable");
- assertTrue(actual.canRead(), "Actual file not readable");
-
- assertDoesNotThrow(() -> equals(decompress(expected), decompress(actual)));
- }
-
- private static class IgnoreXMLDeclEvaluator implements DifferenceEvaluator {
- @Override
- public ComparisonResult evaluate(final Comparison comparison, final ComparisonResult outcome) {
- if (outcome != ComparisonResult.EQUAL) {
- // only evaluate differences
- switch (comparison.getType()) {
- case CHILD_NODELIST_SEQUENCE:
- case XML_STANDALONE:
- case NAMESPACE_PREFIX:
- return ComparisonResult.SIMILAR;
- case TEXT_VALUE:
- switch (comparison.getControlDetails().getTarget().getParentNode().getNodeName()) {
- case "dcterms:created":
- case "dc:creator":
- return ComparisonResult.SIMILAR;
- }
- break;
- default:
- break;
- }
- }
-
- return outcome;
- }
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java
deleted file mode 100644
index 3ebd4041a3..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java
+++ /dev/null
@@ -1,300 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc.compliance;
-
-import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openComplianceSampleStream;
-import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream;
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.net.URISyntaxException;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
-import org.apache.poi.openxml4j.opc.ContentTypes;
-import org.apache.poi.openxml4j.opc.OPCPackage;
-import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
-import org.apache.poi.openxml4j.opc.PackagingURIHelper;
-import org.apache.poi.openxml4j.opc.TargetMode;
-import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.TempFile;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test core properties Open Packaging Convention compliance.
- *
- * 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.
- * (POI relaxes this on reading, as Office sometimes breaks this)
- *
- * M4.2: The format designer shall not specify and the format producer shall not
- * create Core Properties that use the Markup Compatibility namespace as defined
- * in Annex F, "Standard Namespaces and Content Types". A format consumer shall
- * consider the use of the Markup Compatibility namespace to be an 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:
- * <dcterms:created> and <dcterms:modified> Consumers shall consider a document
- * element that violates this constraint to be an 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.
- *
- * 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 final class TestOPCComplianceCoreProperties {
-
- @Test
- void testCorePropertiesPart() throws IOException {
- try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) {
- assertDoesNotThrow(() -> OPCPackage.open(is).close());
- }
- }
-
- private static String extractInvalidFormatMessage(String sampleNameSuffix) throws IOException {
- try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix)) {
- InvalidFormatException e = assertThrows(InvalidFormatException.class,
- () -> OPCPackage.open(is).revert(), "expected OPC compliance exception was not thrown");
- return e.getMessage();
- }
- }
-
- /**
- * Test M4.1 rule.
- */
- @Test
- void testOnlyOneCorePropertiesPart() throws Exception {
- // We have relaxed this check, so we can read the file anyway
- assertDoesNotThrow(() -> {
- try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx");
- OPCPackage pkg = OPCPackage.open(is)) {
- assertNotNull(pkg);
- }
- }, "M4.1 should be being relaxed");
-
- // We will use the first core properties, and ignore the others
-
- try (InputStream is = openSampleStream("MultipleCoreProperties.docx");
- OPCPackage pkg = OPCPackage.open(is)) {
-
- // We can see 2 by type
- assertEquals(2, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
- // But only the first one by relationship
- assertEquals(1, pkg.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size());
- // It should be core.xml not the older core1.xml
- assertEquals(
- "/docProps/core.xml",
- pkg.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).get(0).getPartName().toString()
- );
- }
- }
-
- private static URI createURI(String text) {
- try {
- return new URI(text);
- } catch (URISyntaxException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Test M4.1 rule.
- */
- @Test
- void testOnlyOneCorePropertiesPart_AddRelationship() throws IOException, InvalidFormatException {
- try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) {
- OPCPackage pkg = OPCPackage.open(is);
- URI partUri = createURI("/docProps/core2.xml");
- InvalidOperationException e = assertThrows(InvalidOperationException.class, () ->
- pkg.addRelationship(PackagingURIHelper.createPartName(partUri), TargetMode.INTERNAL, PackageRelationshipTypes.CORE_PROPERTIES),
- "expected OPC compliance exception was not thrown"
- );
- assertEquals("OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead.", e.getMessage());
- pkg.revert();
- }
- }
-
- /**
- * Test M4.1 rule.
- */
- @Test
- void testOnlyOneCorePropertiesPart_AddPart() throws InvalidFormatException, IOException {
- String sampleFileName = "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx";
- try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) {
-
- URI partUri = createURI("/docProps/core2.xml");
- InvalidOperationException e = assertThrows(InvalidOperationException.class, () ->
- pkg.createPart(PackagingURIHelper.createPartName(partUri), ContentTypes.CORE_PROPERTIES_PART),
- "expected OPC compliance exception was not thrown");
- assertEquals("OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !", e.getMessage());
- pkg.revert();
- }
- }
-
- /**
- * Test M4.2 rule.
- */
- @Test
- void testDoNotUseCompatibilityMarkup() throws IOException {
- String msg = extractInvalidFormatMessage("DoNotUseCompatibilityMarkupFAIL.docx");
- assertEquals("OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.", msg);
- }
-
- /**
- * Test M4.3 rule.
- */
- @Test
- void testDCTermsNamespaceLimitedUse() throws IOException {
- String msg = extractInvalidFormatMessage("DCTermsNamespaceLimitedUseFAIL.docx");
- assertEquals("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: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.", msg);
- }
-
- /**
- * Test M4.4 rule.
- */
- @Test
- void testUnauthorizedXMLLangAttribute() throws IOException {
- String msg = extractInvalidFormatMessage("UnauthorizedXMLLangAttributeFAIL.docx");
- assertEquals("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.", msg);
- }
-
- /**
- * Test M4.5 rule.
- */
- @Test
- void testLimitedXSITypeAttribute_NotPresent() throws IOException {
- String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_NotPresentFAIL.docx");
- assertEquals("The element 'created' must have the 'xsi:type' attribute present !", msg);
- }
-
- /**
- * Test M4.5 rule.
- */
- @Test
- void testLimitedXSITypeAttribute_PresentWithUnauthorizedValue() throws IOException {
- String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx");
- assertEquals("The element 'modified' must have the 'xsi:type' attribute with the value 'dcterms:W3CDTF', but had 'W3CDTF' !", msg);
- }
-
- /**
- * Document with no core properties - testing at the OPC level,
- * saving into a new stream
- */
- @Test
- void testNoCoreProperties_saveNew() throws Exception {
- String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx";
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) {
- // Verify it has empty properties
- assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
- assertNotNull(pkg.getPackageProperties());
- assertNotNull(pkg.getPackageProperties().getLanguageProperty());
- assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
-
- // Save and re-load
- pkg.save(baos);
- pkg.revert();
- }
-
- try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) {
- // An Empty Properties part has been added in the save/load
- assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
- assertNotNull(pkg.getPackageProperties());
- assertNotNull(pkg.getPackageProperties().getLanguageProperty());
- assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
- }
-
- // Open a new copy of it
- try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) {
- // Save and re-load, without having touched the properties yet
- baos.reset();
- pkg.save(baos);
- pkg.revert();
- }
-
- try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) {
- // Check that this too added empty properties without error
- assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
- assertNotNull(pkg.getPackageProperties());
- assertNotNull(pkg.getPackageProperties().getLanguageProperty());
- assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
- }
- }
-
- /**
- * Document with no core properties - testing at the OPC level,
- * from a temp-file, saving in-place
- */
- @Test
- void testNoCoreProperties_saveInPlace() throws Exception {
- String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx";
-
- // Copy this into a temp file, so we can play with it
- File tmp = TempFile.createTempFile("poi-test", ".opc");
- try (FileOutputStream out = new FileOutputStream(tmp);
- InputStream in = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(sampleFileName)) {
- IOUtils.copy(in, out);
- }
-
- // Open it from that temp file
- try (OPCPackage pkg = OPCPackage.open(tmp)) {
-
- // Empty properties
- assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
- assertNotNull(pkg.getPackageProperties());
- assertNotNull(pkg.getPackageProperties().getLanguageProperty());
- assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
-
- // Save and close
- }
-
- // Re-open and check
- try (OPCPackage pkg = OPCPackage.open(tmp)) {
- // An Empty Properties part has been added in the save/load
- assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
- assertNotNull(pkg.getPackageProperties());
- assertNotNull(pkg.getPackageProperties().getLanguageProperty());
- assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent());
-
- // Finish and tidy
- pkg.revert();
- }
- assertTrue(tmp.delete());
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java
deleted file mode 100644
index e81605fc26..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc.compliance;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
-import org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException;
-import org.apache.poi.openxml4j.opc.ContentTypes;
-import org.apache.poi.openxml4j.opc.OPCPackage;
-import org.apache.poi.openxml4j.opc.PackagePartName;
-import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
-import org.apache.poi.openxml4j.opc.PackagingURIHelper;
-import org.apache.poi.openxml4j.opc.TargetMode;
-import org.apache.poi.util.TempFile;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test Open Packaging Convention package model compliance.
- *
- * 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.
- */
-class TestOPCCompliancePackageModel {
-
- private static File TESTFILE;
-
- @BeforeAll
- public static void setup() throws IOException {
- TESTFILE = TempFile.createTempFile("TODELETEIFEXIST", ".docx");
- }
-
- @BeforeEach
- void tearDown() {
- if (TESTFILE.exists()) {
- assertTrue(TESTFILE.delete());
- }
- }
-
- /**
- * A package implementer shall neither create nor recognize a part with a
- * part name derived from another part name by appending segments to it.
- * [M1.11]
- */
- @Test
- void testPartNameDerivationAdditionFailure() throws InvalidFormatException, IOException {
- try (OPCPackage pkg = OPCPackage.create(TESTFILE)) {
- PackagePartName name = PackagingURIHelper.createPartName("/word/document.xml");
- PackagePartName nameDerived = PackagingURIHelper.createPartName("/word/document.xml/image1.gif");
- pkg.createPart(name, ContentTypes.XML);
-
- assertThrows(InvalidOperationException.class, () -> pkg.createPart(nameDerived, ContentTypes.EXTENSION_GIF),
- "A package implementer shall neither create nor recognize a part with a part name derived from another " +
- "part name by appending segments to it. [M1.11]");
- pkg.revert();
- }
- }
-
- /**
- * A package implementer shall neither create nor recognize a part with a
- * part name derived from another part name by appending segments to it.
- * [M1.11]
- */
- @Test
- void testPartNameDerivationReadingFailure() {
- String filename = "OPCCompliance_DerivedPartNameFAIL.docx";
- assertThrows(InvalidFormatException.class, () ->
- OPCPackage.open(POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename)),
- "A package implementer shall neither create nor recognize a part with a part name derived from another" +
- " part name by appending segments to it. [M1.11]"
- );
- }
-
- /**
- * Rule M1.12 : Packages shall not contain equivalent part names and package
- * implementers shall neither create nor recognize packages with equivalent
- * part names.
- */
- @Test
- void testAddPackageAlreadyAddFailure() throws Exception {
- try (OPCPackage pkg = OPCPackage.create(TESTFILE)) {
- PackagePartName name1 = PackagingURIHelper.createPartName("/word/document.xml");
- PackagePartName name2 = PackagingURIHelper.createPartName("/word/document.xml");
-
- pkg.createPart(name1, ContentTypes.XML);
- assertThrows(PartAlreadyExistsException.class, () -> pkg.createPart(name2, ContentTypes.XML),
- "Packages shall not contain equivalent part names and package implementers shall neither create nor " +
- "recognize packages with equivalent part names. [M1.12]"
- );
- pkg.revert();
- }
- }
-
- /**
- * Rule M1.12 : Packages shall not contain equivalent part names and package
- * implementers shall neither create nor recognize packages with equivalent
- * part names.
- */
- @Test
- void testAddPackageAlreadyAddFailure2() throws Exception {
- try (OPCPackage pkg = OPCPackage.create(TESTFILE)) {
- PackagePartName partName = PackagingURIHelper.createPartName("/word/document.xml");
- pkg.createPart(partName, ContentTypes.XML);
- assertThrows(InvalidOperationException.class, () -> pkg.createPart(partName, ContentTypes.XML),
- "Packages shall not contain equivalent part names and package implementers shall neither create nor " +
- "recognize packages with equivalent part names. [M1.12]"
- );
- pkg.revert();
- }
- }
-
- /**
- * Try to add a relationship to a relationship part.
- * <p>
- * 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.
- */
- @Test
- void testAddRelationshipRelationshipsPartFailure() throws IOException, InvalidFormatException {
- try (OPCPackage pkg = OPCPackage.create(TESTFILE)) {
- PackagePartName name1 = PackagingURIHelper.createPartName("/test/_rels/document.xml.rels");
-
- assertThrows(InvalidOperationException.class,
- () -> pkg.addRelationship(name1, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT),
- "The Relationships part shall not have relationships to any other part [M1.25]"
- );
- pkg.revert();
- }
- }
-
- @Test
- void testToString() throws IOException {
- try (OPCPackage pkg = OPCPackage.create(TESTFILE)) {
- assertEquals("OPCPackage{" +
- "packageAccess=READ_WRITE, " +
- "relationships=null, " +
- "packageProperties=Name: /docProps/core.xml - Content Type: application/vnd.openxmlformats-package.core-properties+xml, " +
- "isDirty=false}", pkg.toString());
- }
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java
deleted file mode 100644
index edfe0fea3e..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc.compliance;
-
-import static org.apache.poi.openxml4j.opc.PackagingURIHelper.createPartName;
-import static org.apache.poi.openxml4j.opc.PackagingURIHelper.isValidPartName;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.openxml4j.opc.PackagePartName;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test part name Open Packaging Convention compliance.
- *
- * (Open Packaging Convention 8.1.1 Part names) :
- *
- * The part name grammar is defined as follows:
- *
- * part_name = 1*( "/" segment )
- *
- * segment = 1*( pchar )
- *
- * pchar is defined in RFC 3986.
- *
- * The part name grammar implies the following constraints. The package
- * implementer shall neither create any part that violates these constraints nor
- * retrieve any data from a package as a part if the purported part name
- * violates these constraints.
- *
- * A part name shall not be empty. [M1.1]
- *
- * A part name shall not have empty segments. [M1.3]
- *
- * A part name shall start with a forward slash ("/") character. [M1.4]
- *
- * A part name shall not have a forward slash as the last character. [M1.5]
- *
- * A segment shall not hold any characters other than pchar characters. [M1.6]
- *
- * Part segments have the following additional constraints. The package
- * implementer shall neither create any part with a part name comprised of a
- * segment that violates these constraints nor retrieve any data from a package
- * as a part if the purported part name contains a segment that violates these
- * constraints.
- *
- * A segment shall not contain percent-encoded forward slash ("/"), or backward
- * slash ("\") characters. [M1.7]
- *
- * A segment shall not contain percent-encoded unreserved characters. [M1.8]
- *
- * A segment shall not end with a dot (".") character. [M1.9]
- *
- * A segment shall include at least one non-dot character. [M1.10]
- *
- * A package implementer shall neither create nor recognize a part with a part
- * name derived from another part name by appending segments to it. [M1.11]
- *
- * Part name equivalence is determined by comparing part names as
- * case-insensitive ASCII strings. [M1.12]
- *
- * @author Julien Chable
- */
-public final class TestOPCCompliancePartName {
-
- /**
- * Test some common invalid names.
- *
- * A segment shall not contain percent-encoded unreserved characters. [M1.8]
- */
- @Test
- void testInvalidPartNames() {
- String[] invalidNames = { "/", "/xml./doc.xml", "[Content_Types].xml", "//xml/." };
- for (String s : invalidNames) {
- URI uri = null;
- try {
- uri = new URI(s);
- } catch (URISyntaxException e) {
- assertEquals("[Content_Types].xml", s);
- continue;
- }
- assertFalse(isValidPartName(uri), "This part name SHOULD NOT be valid: " + s);
- }
- }
-
- /**
- * Test some common valid names.
- */
- @Test
- void testValidPartNames() throws URISyntaxException {
- String[] validNames = { "/xml/item1.xml", "/document.xml", "/a/%D1%86.xml" };
- for (String s : validNames) {
- assertTrue(isValidPartName(new URI(s)), "This part name SHOULD be valid: " + s);
- }
- }
-
- /**
- * A part name shall not be empty. [M1.1]
- */
- @Test
- void testEmptyPartNameFailure() {
- assertThrows(InvalidFormatException.class, () -> createPartName(new URI("")),
- "A part name shall not be empty. [M1.1]");
- }
-
- /**
- * A part name shall not have empty segments. [M1.3]
- *
- * A segment shall not end with a dot ('.') character. [M1.9]
- *
- * A segment shall include at least one non-dot character. [M1.10]
- */
- @Test
- void testPartNameWithInvalidSegmentsFailure() throws URISyntaxException {
- String[] invalidNames = { "//document.xml", "//word/document.xml",
- "/word//document.rels", "/word//rels//document.rels",
- "/xml./doc.xml", "/document.", "/./document.xml",
- "/word/./doc.rels", "/%2F/document.xml" };
- for (String s : invalidNames) {
- assertFalse(isValidPartName(new URI(s)), "A part name shall not have empty segments. [M1.3]");
- }
- }
-
- /**
- * A segment shall not hold any characters other than ipchar (RFC 3987) characters.
- * [M1.6].
- */
- @Test
- void testPartNameWithNonPCharCharacters() throws URISyntaxException {
- String[] validNames = { "/doc&.xml" };
- for (String s : validNames) {
- assertTrue(isValidPartName(new URI(s)),
- "A segment shall not contain non pchar characters [M1.6] : " + s);
- }
- }
-
- /**
- * A segment shall not contain percent-encoded unreserved characters [M1.8].
- */
- @Test
- void testPartNameWithUnreservedEncodedCharactersFailure() throws URISyntaxException {
- String[] invalidNames = { "/a/docum%65nt.xml" };
- for (String s : invalidNames) {
- assertFalse(isValidPartName(new URI(s)), "A segment shall not contain percent-encoded unreserved characters [M1.8] : " + s);
- }
- }
-
- /**
- * A part name shall start with a forward slash ('/') character. [M1.4]
- */
- @Test
- void testPartNameStartsWithAForwardSlashFailure() {
- assertThrows(InvalidFormatException.class, () -> createPartName(new URI("document.xml")),
- "A part name shall start with a forward slash ('/') character. [M1.4]");
- }
-
- /**
- * A part name shall not have a forward slash as the last character. [M1.5]
- */
- @Test
- void testPartNameEndsWithAForwardSlashFailure() {
- assertThrows(InvalidFormatException.class, () -> createPartName(new URI("/document.xml/")),
- "A part name shall not have a forward slash as the last character. [M1.5]");
- }
-
- /**
- * Part name equivalence is determined by comparing part names as
- * case-insensitive ASCII strings. [M1.12]
- */
- @Test
- void testPartNameComparaison() throws Exception {
- String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" };
- String[] partName2 = { "/WORD/DocUment.XML", "/docProps/core.xml", "/rels/.rels" };
- for (int i = 0; i < partName1.length || i < partName2.length; ++i) {
- PackagePartName p1 = createPartName(partName1[i]);
- PackagePartName p2 = createPartName(partName2[i]);
- assertEquals(p1, p2);
- assertEquals(0, p1.compareTo(p2));
- assertEquals(p1.hashCode(), p2.hashCode());
- }
- }
-
- /**
- * Part name equivalence is determined by comparing part names as
- * case-insensitive ASCII strings. [M1.12].
- *
- * All the comparisons MUST FAIL !
- */
- @Test
- void testPartNameComparaisonFailure() throws Exception {
- String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" };
- String[] partName2 = { "/WORD/DocUment.XML2", "/docProp/core.xml", "/rels/rels" };
- for (int i = 0; i < partName1.length || i < partName2.length; ++i) {
- PackagePartName p1 = createPartName(partName1[i]);
- PackagePartName p2 = createPartName(partName2[i]);
- assertNotEquals(p1, p2);
- assertNotEquals(0, p1.compareTo(p2));
- assertNotEquals(p1.hashCode(), p2.hashCode());
- }
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java
deleted file mode 100644
index aab917ec63..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc.internal;
-
-import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.poi.ooxml.util.POIXMLUnits;
-import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
-import org.apache.poi.openxml4j.opc.OPCPackage;
-import org.apache.poi.openxml4j.opc.PackageAccess;
-import org.apache.poi.openxml4j.opc.PackagePart;
-import org.apache.poi.openxml4j.opc.PackagePartName;
-import org.apache.poi.openxml4j.opc.PackageRelationship;
-import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
-import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
-import org.apache.poi.openxml4j.opc.PackagingURIHelper;
-import org.apache.poi.ss.usermodel.ClientAnchor;
-import org.apache.poi.ss.usermodel.CreationHelper;
-import org.apache.poi.ss.usermodel.Drawing;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.xssf.XSSFTestDataSamples;
-import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
-import org.apache.poi.xssf.usermodel.XSSFDrawing;
-import org.apache.poi.xssf.usermodel.XSSFPicture;
-import org.apache.poi.xssf.usermodel.XSSFPictureData;
-import org.apache.poi.xssf.usermodel.XSSFShape;
-import org.apache.poi.xssf.usermodel.XSSFSheet;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor;
-
-public final class TestContentTypeManager {
-
- /**
- * Test the properties part content parsing.
- */
- @Test
- void testContentType() throws Exception {
- String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
-
- // Retrieves core properties part
- try (OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ)) {
- PackageRelationshipCollection rels = p.getRelationshipsByType(PackageRelationshipTypes.CORE_PROPERTIES);
- PackageRelationship corePropertiesRelationship = rels.getRelationship(0);
- PackagePart coreDocument = p.getPart(corePropertiesRelationship);
-
- assertEquals("application/vnd.openxmlformats-package.core-properties+xml", coreDocument.getContentType());
- }
- }
-
- /**
- * Test the addition of several default and override content types.
- */
- @Test
- void testContentTypeAddition() throws Exception {
- ContentTypeManager ctm = new ZipContentTypeManager(null, null);
-
- PackagePartName name1 = PackagingURIHelper.createPartName("/foo/foo.XML");
- PackagePartName name2 = PackagingURIHelper.createPartName("/foo/foo2.xml");
- PackagePartName name3 = PackagingURIHelper.createPartName("/foo/doc.rels");
- PackagePartName name4 = PackagingURIHelper.createPartName("/foo/doc.RELS");
-
- // Add content types
- ctm.addContentType(name1, "foo-type1");
- ctm.addContentType(name2, "foo-type2");
- ctm.addContentType(name3, "text/xml+rel");
- ctm.addContentType(name4, "text/xml+rel");
-
- assertEquals(ctm.getContentType(name1), "foo-type1");
- assertEquals(ctm.getContentType(name2), "foo-type2");
- assertEquals(ctm.getContentType(name3), "text/xml+rel");
- assertEquals(ctm.getContentType(name3), "text/xml+rel");
- }
-
- /**
- * Test the addition then removal of content types.
- */
- @Test
- void testContentTypeRemoval() throws Exception {
- ContentTypeManager ctm = new ZipContentTypeManager(null, null);
-
- PackagePartName name1 = PackagingURIHelper.createPartName("/foo/foo.xml");
- PackagePartName name2 = PackagingURIHelper.createPartName("/foo/foo2.xml");
- PackagePartName name3 = PackagingURIHelper.createPartName("/foo/doc.rels");
- PackagePartName name4 = PackagingURIHelper.createPartName("/foo/doc.RELS");
-
- // Add content types
- ctm.addContentType(name1, "foo-type1");
- ctm.addContentType(name2, "foo-type2");
- ctm.addContentType(name3, "text/xml+rel");
- ctm.addContentType(name4, "text/xml+rel");
- ctm.removeContentType(name2);
- ctm.removeContentType(name3);
-
- assertEquals(ctm.getContentType(name1), "foo-type1");
- assertEquals(ctm.getContentType(name2), "foo-type1");
- assertNull(ctm.getContentType(name3));
-
- ctm.removeContentType(name1);
- assertNull(ctm.getContentType(name1));
- assertNull(ctm.getContentType(name2));
- }
-
- /**
- * Test the addition then removal of content types in a package.
- */
- @Disabled
- void testContentTypeRemovalPackage() {
- // TODO
- }
-
- protected byte[] toByteArray(Workbook wb) {
- try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
- wb.write(os);
- return os.toByteArray();
- } catch (IOException e) {
- throw new RuntimeException("failed to write excel file.");
- }
- }
-
- @Test
- void bug62629CombinePictures() throws Exception {
- // this file has incorrect default content-types which caused problems in Apache POI
- // we now handle this broken file more gracefully
- try (XSSFWorkbook targetWB = openSampleWorkbook("62629_target.xlsm");
- XSSFWorkbook mergeWB = openSampleWorkbook("62629_toMerge.xlsx")) {
- for (Sheet b_sheet : mergeWB) {
- XSSFSheet sheet = targetWB.createSheet(b_sheet.getSheetName());
-
- XSSFDrawing drawingOld = (XSSFDrawing)b_sheet.createDrawingPatriarch();
- XSSFDrawing drawingNew = sheet.createDrawingPatriarch();
- CreationHelper helper = sheet.getWorkbook().getCreationHelper();
- List<XSSFShape> shapes = drawingOld.getShapes();
-
- for (XSSFShape shape : shapes) {
- assertTrue(shape instanceof XSSFPicture);
- XSSFPicture pic = (XSSFPicture)shape;
- XSSFPictureData picData = pic.getPictureData();
- int pictureIndex = targetWB.addPicture(picData.getData(), picData.getPictureType());
- ClientAnchor oldAnchor = pic.getClientAnchor();
- assertNotNull(oldAnchor);
- ClientAnchor anchor = helper.createClientAnchor();
- anchor.setAnchorType(oldAnchor.getAnchorType());
- anchor.setDx1(oldAnchor.getDx1());
- anchor.setDx2(oldAnchor.getDx2());
- anchor.setDy1(oldAnchor.getDy1());
- anchor.setDy2(oldAnchor.getDy2());
- anchor.setCol1(oldAnchor.getCol1());
- anchor.setCol2(oldAnchor.getCol2());
- anchor.setRow1(oldAnchor.getRow1());
- anchor.setRow2(oldAnchor.getRow2());
- drawingNew.createPicture(anchor, pictureIndex);
- }
- }
-
- try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(targetWB)) {
- for (XSSFWorkbook wb : Arrays.asList(targetWB, mergeWB)) {
- for (Sheet sheet : wb) {
- XSSFSheet backSheet = wbBack.getSheet(sheet.getSheetName());
- assertNotNull(backSheet);
- XSSFDrawing origPat = (XSSFDrawing)sheet.createDrawingPatriarch();
- XSSFDrawing backPat = backSheet.createDrawingPatriarch();
- assertEquals(origPat.getShapes().size(), backPat.getShapes().size());
- }
- }
- }
- }
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java
deleted file mode 100644
index 3b9b03aed4..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.openxml4j.opc.internal.marshallers;
-
-import static org.apache.poi.openxml4j.opc.PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-
-import org.apache.commons.compress.archivers.ArchiveEntry;
-import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
-import org.apache.poi.openxml4j.opc.PackagePartName;
-import org.apache.poi.openxml4j.opc.PackagingURIHelper;
-import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
-import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
-import org.junit.jupiter.api.Test;
-
-class TestZipPackagePropertiesMarshaller {
- private final PartMarshaller marshaller = new ZipPackagePropertiesMarshaller();
-
- private boolean marshall() throws OpenXML4JException {
- return marshall(new ZipArchiveOutputStream(new ByteArrayOutputStream()));
- }
-
- private boolean marshall(OutputStream zos) throws OpenXML4JException {
- PackagePartName rootUri = PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI);
- PackagePropertiesPart part = new PackagePropertiesPart(null, rootUri);
- return marshaller.marshall(part, zos);
- }
-
-
- @Test
- void nonZipOutputStream() {
- OutputStream notAZipOutputStream = new ByteArrayOutputStream(0);
- assertThrows(IllegalArgumentException.class, () -> marshall(notAZipOutputStream));
- }
-
- @Test
- void withZipOutputStream() throws Exception {
- assertTrue(marshall());
- }
-
- @Test
- void ioException() {
- ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new ByteArrayOutputStream()) {
- @Override
- public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException {
- throw new IOException("TestException");
- }
- };
- assertThrows(OpenXML4JException.class, () -> marshall(zos));
- }
-}
diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/util/TestZipSecureFile.java b/src/ooxml/testcases/org/apache/poi/openxml4j/util/TestZipSecureFile.java
deleted file mode 100644
index d80a44a1d8..0000000000
--- a/src/ooxml/testcases/org/apache/poi/openxml4j/util/TestZipSecureFile.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- 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
-
- 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,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-package org.apache.poi.openxml4j.util;
-
-import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
-import org.apache.commons.compress.archivers.zip.ZipFile;
-import org.apache.poi.util.IOUtils;
-import org.apache.poi.xssf.XSSFTestDataSamples;
-import org.junit.jupiter.api.Test;
-
-import java.io.InputStream;
-import java.util.Enumeration;
-
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-class TestZipSecureFile {
- @Test
- void testThresholdInputStream() throws Exception {
- // This fails in Java 10 because our reflection injection of the ThresholdInputStream causes a
- // ClassCastException in ZipFile now
- // The relevant change in the JDK is http://hg.openjdk.java.net/jdk/jdk10/rev/85ea7e83af30#l5.66
-
- try (ZipFile thresholdInputStream = new ZipFile(XSSFTestDataSamples.getSampleFile("template.xlsx"))) {
- try (ZipSecureFile secureFile = new ZipSecureFile(XSSFTestDataSamples.getSampleFile("template.xlsx"))) {
- Enumeration<? extends ZipArchiveEntry> entries = thresholdInputStream.getEntries();
- while (entries.hasMoreElements()) {
- ZipArchiveEntry entry = entries.nextElement();
-
- try (InputStream inputStream = secureFile.getInputStream(entry)) {
- assertTrue(IOUtils.toByteArray(inputStream).length > 0);
- }
- }
- }
- }
- }
-}