diff options
Diffstat (limited to 'src/ooxml/testcases/org')
21 files changed, 1395 insertions, 1387 deletions
diff --git a/src/ooxml/testcases/org/apache/poi/TestEmbeded.java b/src/ooxml/testcases/org/apache/poi/TestEmbeded.java index 6a427bbdc0..ff97d0329d 100644 --- a/src/ooxml/testcases/org/apache/poi/TestEmbeded.java +++ b/src/ooxml/testcases/org/apache/poi/TestEmbeded.java @@ -25,7 +25,7 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.xslf.XSLFSlideShow; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.openxml4j.opc.Package; +import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; import junit.framework.TestCase; @@ -47,7 +47,7 @@ public class TestEmbeded extends TestCase File f = new File(dirname, "ExcelWithAttachments.xlsx"); assertTrue(f.exists()); - POIXMLDocument doc = new XSSFWorkbook(Package.open(f.toString())); + POIXMLDocument doc = new XSSFWorkbook(OPCPackage.open(f.toString())); test(doc, 4); } @@ -55,7 +55,7 @@ public class TestEmbeded extends TestCase File f = new File(dirname, "WordWithAttachments.docx"); assertTrue(f.exists()); - POIXMLDocument doc = new XWPFDocument(Package.open(f.toString())); + POIXMLDocument doc = new XWPFDocument(OPCPackage.open(f.toString())); test(doc, 5); } @@ -63,7 +63,7 @@ public class TestEmbeded extends TestCase File f = new File(dirname, "PPTWithAttachments.pptx"); assertTrue(f.exists()); - POIXMLDocument doc = new XSLFSlideShow(Package.open(f.toString())); + POIXMLDocument doc = new XSLFSlideShow(OPCPackage.open(f.toString())); test(doc, 4); } diff --git a/src/ooxml/testcases/org/apache/poi/TestXMLPropertiesTextExtractor.java b/src/ooxml/testcases/org/apache/poi/TestXMLPropertiesTextExtractor.java index 33c11436e5..90a7329271 100644 --- a/src/ooxml/testcases/org/apache/poi/TestXMLPropertiesTextExtractor.java +++ b/src/ooxml/testcases/org/apache/poi/TestXMLPropertiesTextExtractor.java @@ -20,7 +20,7 @@ import java.io.File; import org.apache.poi.xssf.extractor.XSSFExcelExtractor; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.openxml4j.opc.Package; +import org.apache.poi.openxml4j.opc.OPCPackage; import junit.framework.TestCase; @@ -33,7 +33,7 @@ public class TestXMLPropertiesTextExtractor extends TestCase { } public void testGetFromMainExtractor() throws Exception { - org.apache.poi.openxml4j.opc.Package pkg = Package.open( + OPCPackage pkg = OPCPackage.open( (new File(dirname, "ExcelWithAttachments.xlsx")).toString() ); XSSFWorkbook wb = new XSSFWorkbook(pkg); @@ -54,7 +54,7 @@ public class TestXMLPropertiesTextExtractor extends TestCase { } public void testCore() throws Exception { - org.apache.poi.openxml4j.opc.Package pkg = Package.open( + OPCPackage pkg = OPCPackage.open( (new File(dirname, "ExcelWithAttachments.xlsx")).toString() ); XSSFWorkbook wb = new XSSFWorkbook(pkg); @@ -71,7 +71,7 @@ public class TestXMLPropertiesTextExtractor extends TestCase { } public void testExtended() throws Exception { - org.apache.poi.openxml4j.opc.Package pkg = Package.open( + OPCPackage pkg = OPCPackage.open( (new File(dirname, "ExcelWithAttachments.xlsx")).toString() ); XSSFWorkbook wb = new XSSFWorkbook(pkg); diff --git a/src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java b/src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java index e75ba3c9e6..bbbbaa9733 100644 --- a/src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java +++ b/src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java @@ -34,7 +34,7 @@ import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import junit.framework.TestCase; import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.opc.Package; +import org.apache.poi.openxml4j.opc.OPCPackage; /** * Test that the extractor factory plays nicely @@ -276,34 +276,34 @@ public class TestExtractorFactory extends TestCase { public void testPackage() throws Exception { // Excel assertTrue( - ExtractorFactory.createExtractor(Package.open(xlsx.toString())) + ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())) instanceof XSSFExcelExtractor ); assertTrue( - ExtractorFactory.createExtractor(Package.open(xlsx.toString())).getText().length() > 200 + ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())).getText().length() > 200 ); // Word assertTrue( - ExtractorFactory.createExtractor(Package.open(docx.toString())) + ExtractorFactory.createExtractor(OPCPackage.open(docx.toString())) instanceof XWPFWordExtractor ); assertTrue( - ExtractorFactory.createExtractor(Package.open(docx.toString())).getText().length() > 120 + ExtractorFactory.createExtractor(OPCPackage.open(docx.toString())).getText().length() > 120 ); // PowerPoint assertTrue( - ExtractorFactory.createExtractor(Package.open(pptx.toString())) + ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString())) instanceof XSLFPowerPointExtractor ); assertTrue( - ExtractorFactory.createExtractor(Package.open(pptx.toString())).getText().length() > 120 + ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString())).getText().length() > 120 ); // Text try { - ExtractorFactory.createExtractor(Package.open(txt.toString())); + ExtractorFactory.createExtractor(OPCPackage.open(txt.toString())); fail(); } catch(InvalidOperationException e) { // Good diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java index c35f57833e..01e628eba4 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java @@ -1,103 +1,103 @@ -/* ====================================================================
- 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.IOException;
-import java.io.InputStream;
-import java.util.TreeMap;
-
-import junit.framework.TestCase;
-
-import org.apache.log4j.Logger;
-import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-
-public final class TestListParts extends TestCase {
- private static Logger logger = Logger.getLogger("org.apache.poi.openxml4j.test");
-
- private TreeMap<PackagePartName, String> expectedValues;
-
- private TreeMap<PackagePartName, String> values;
-
- @Override
- protected void setUp() throws Exception {
- values = new TreeMap<PackagePartName, String>();
-
- // Expected values
- expectedValues = new TreeMap<PackagePartName, String>();
- 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.
- */
- public void testListParts() throws InvalidFormatException {
- InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.docx");
-
- Package p;
- try {
- p = Package.open(is);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- for (PackagePart part : p.getParts()) {
- values.put(part.getPartName(), part.getContentType());
- logger.debug(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));
- }
- }
-}
+/* ==================================================================== + 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.IOException; +import java.io.InputStream; +import java.util.TreeMap; + +import junit.framework.TestCase; + +import org.apache.log4j.Logger; +import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; + +public final class TestListParts extends TestCase { + private static Logger logger = Logger.getLogger("org.apache.poi.openxml4j.test"); + + private TreeMap<PackagePartName, String> expectedValues; + + private TreeMap<PackagePartName, String> values; + + @Override + protected void setUp() throws Exception { + values = new TreeMap<PackagePartName, String>(); + + // Expected values + expectedValues = new TreeMap<PackagePartName, String>(); + 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. + */ + public void testListParts() throws InvalidFormatException { + InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.docx"); + + OPCPackage p; + try { + p = OPCPackage.open(is); + } catch (IOException e) { + throw new RuntimeException(e); + } + for (PackagePart part : p.getParts()) { + values.put(part.getPartName(), part.getContentType()); + logger.debug(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 index 0b95bbe119..5f667deba9 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java @@ -1,417 +1,417 @@ -/* ====================================================================
- 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.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.lang.reflect.Field;
-import java.net.URI;
-import java.util.TreeMap;
-
-import junit.framework.TestCase;
-
-import org.apache.log4j.Logger;
-import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
-import org.apache.poi.openxml4j.opc.internal.FileHelper;
-import org.dom4j.Document;
-import org.dom4j.DocumentHelper;
-import org.dom4j.Element;
-import org.dom4j.Namespace;
-import org.dom4j.QName;
-
-public final class TestPackage extends TestCase {
- private static Logger logger = Logger.getLogger("org.apache.poi.openxml4j.test");
-
- /**
- * Test that just opening and closing the file doesn't alter the document.
- */
- public void testOpenSave() throws Exception {
- String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
- File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
-
- Package p = Package.open(originalFile, PackageAccess.READ_WRITE);
- p.save(targetFile.getAbsoluteFile());
-
- // Compare the original and newly saved document
- assertTrue(targetFile.exists());
- //ZipFileAssert.assertEquals(originalFile, targetFile);
- assertTrue(targetFile.delete());
- }
-
- /**
- * Test that when we create a new Package, we give it
- * the correct default content types
- */
- public void testCreateGetsContentTypes() throws Exception {
- File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
-
- // Zap the target file, in case of an earlier run
- if(targetFile.exists()) targetFile.delete();
-
- Package pkg = Package.create(targetFile);
-
- // Check it has content types for rels and xml
- ContentTypeManager ctm = getContentTypeManager(pkg);
- assertEquals(
- "application/xml",
- ctm.getContentType(
- PackagingURIHelper.createPartName("/foo.xml")
- )
- );
- assertEquals(
- ContentTypes.RELATIONSHIPS_PART,
- ctm.getContentType(
- PackagingURIHelper.createPartName("/foo.rels")
- )
- );
- assertNull(
- ctm.getContentType(
- PackagingURIHelper.createPartName("/foo.txt")
- )
- );
- }
-
- /**
- * Test package creation.
- */
- public void testCreatePackageAddPart() throws Exception {
- File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
-
- File expectedFileFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageOUTPUT.docx");
-
- // Zap the target file, in case of an earlier run
- if(targetFile.exists()) targetFile.delete();
-
- // Create a package
- Package pkg = Package.create(targetFile);
- PackagePartName corePartName = PackagingURIHelper
- .createPartName("/word/document.xml");
-
- pkg.addRelationship(corePartName, TargetMode.INTERNAL,
- PackageRelationshipTypes.CORE_DOCUMENT, "rId1");
-
- PackagePart corePart = pkg
- .createPart(
- corePartName,
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
-
- Document doc = DocumentHelper.createDocument();
- Namespace nsWordprocessinML = new Namespace("w",
- "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
- Element elDocument = doc.addElement(new QName("document",
- nsWordprocessinML));
- Element elBody = elDocument.addElement(new QName("body",
- nsWordprocessinML));
- Element elParagraph = elBody.addElement(new QName("p",
- nsWordprocessinML));
- Element elRun = elParagraph
- .addElement(new QName("r", nsWordprocessinML));
- Element elText = elRun.addElement(new QName("t", nsWordprocessinML));
- elText.setText("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
- */
- public void testCreatePackageWithCoreDocument() throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- Package pkg = Package.create(baos);
-
- // Add a core document
- PackagePartName corePartName = PackagingURIHelper.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, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml");
- // Put in some dummy content
- OutputStream coreOut = corePart.getOutputStream();
- coreOut.write("<dummy-xml />".getBytes());
- coreOut.close();
-
- // And another bit
- PackagePartName sheetPartName = PackagingURIHelper.createPartName("/xl/worksheets/sheet1.xml");
- PackageRelationship rel =
- corePart.addRelationship(sheetPartName, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", "rSheet1");
- PackagePart part = pkg.createPart(sheetPartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml");
- // Dummy content again
- coreOut = corePart.getOutputStream();
- coreOut.write("<dummy-xml2 />".getBytes());
- coreOut.close();
-
-
- // Check things are as expected
- PackageRelationshipCollection coreRels =
- pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
- assertEquals(1, coreRels.size());
- PackageRelationship coreRel = coreRels.getRelationship(0);
- assertEquals("/", coreRel.getSourceURI().toString());
- assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString());
- assertNotNull(pkg.getPart(coreRel));
-
-
- // Save and re-load
- pkg.close();
- FileOutputStream fout = new FileOutputStream(File.createTempFile("testCreatePackageWithCoreDocument", ".zip"));
- fout.write(baos.toByteArray());
- fout.close();
- pkg = Package.open(new ByteArrayInputStream(baos.toByteArray()));
-
-
- // Check still right
- coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
- assertEquals(1, coreRels.size());
- coreRel = coreRels.getRelationship(0);
- assertEquals("/", coreRel.getSourceURI().toString());
- assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString());
- assertNotNull(pkg.getPart(coreRel));
- }
-
- /**
- * Test package opening.
- */
- public void testOpenPackage() throws Exception {
- File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageTMP.docx");
-
- File inputFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageINPUT.docx");
-
- File expectedFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageOUTPUT.docx");
-
- // Copy the input file in the output directory
- FileHelper.copyFile(inputFile, targetFile);
-
- // Create a package
- Package pkg = Package.open(targetFile.getAbsolutePath());
-
- // Modify core part
- PackagePartName corePartName = PackagingURIHelper
- .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(PackagingURIHelper.createPartName(PackagingURIHelper
- .resolvePartUri(corePart.getPartName().getURI(), rel
- .getTargetURI())));
- }
-
- // Create a content
- Document doc = DocumentHelper.createDocument();
- Namespace nsWordprocessinML = new Namespace("w",
- "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
- Element elDocument = doc.addElement(new QName("document",
- nsWordprocessinML));
- Element elBody = elDocument.addElement(new QName("body",
- nsWordprocessinML));
- Element elParagraph = elBody.addElement(new QName("p",
- nsWordprocessinML));
- Element elRun = elParagraph
- .addElement(new QName("r", nsWordprocessinML));
- Element elText = elRun.addElement(new QName("t", nsWordprocessinML));
- elText.setText("Hello Open XML !");
-
- StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
-
- // Save and close
- try {
- pkg.close();
- } catch (IOException e) {
- fail();
- }
-
- //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
- */
- public void testSaveToOutputStream() throws Exception {
- String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
- File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
-
- Package p = Package.open(originalFile, PackageAccess.READ_WRITE);
- FileOutputStream fout = new FileOutputStream(targetFile);
- p.save(fout);
- fout.close();
-
- // Compare the original and newly saved document
- assertTrue(targetFile.exists());
- //ZipFileAssert.assertEquals(originalFile, targetFile);
- assertTrue(targetFile.delete());
- }
-
- /**
- * Checks that we can open+read a package from a
- * simple InputStream, in addition to the normal
- * reading from a file
- */
- public void testOpenFromInputStream() throws Exception {
- String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
-
- FileInputStream finp = new FileInputStream(originalFile);
-
- Package p = Package.open(finp);
-
- assertNotNull(p);
- assertNotNull(p.getRelationships());
- assertEquals(12, p.getParts().size());
-
- // Check it has the usual bits
- assertTrue(p.hasRelationships());
- assertTrue(p.containPart(PackagingURIHelper.createPartName("/_rels/.rels")));
- }
-
- /**
- * TODO: fix and enable
- */
- public void disabled_testRemovePartRecursive() throws Exception {
- String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
- File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx");
- File tempFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveTMP.docx");
-
- Package p = Package.open(originalFile, PackageAccess.READ_WRITE);
- p.removePartRecursive(PackagingURIHelper.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());
- }
-
- public void testDeletePart() throws InvalidFormatException {
- TreeMap<PackagePartName, String> expectedValues;
- TreeMap<PackagePartName, String> values;
-
- values = new TreeMap<PackagePartName, String>();
-
- // Expected values
- expectedValues = new TreeMap<PackagePartName, String>();
- 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/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");
-
- String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
-
- Package p = Package.open(filepath, PackageAccess.READ_WRITE);
- // Remove the core part
- p.deletePart(PackagingURIHelper.createPartName("/word/document.xml"));
-
- for (PackagePart part : p.getParts()) {
- values.put(part.getPartName(), part.getContentType());
- logger.debug(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));
- }
- // Don't save modifications
- p.revert();
- }
-
- public void testDeletePartRecursive() throws InvalidFormatException {
- TreeMap<PackagePartName, String> expectedValues;
- TreeMap<PackagePartName, String> values;
-
- values = new TreeMap<PackagePartName, String>();
-
- // Expected values
- expectedValues = new TreeMap<PackagePartName, String>();
- 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");
-
- String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
-
- Package p = Package.open(filepath, PackageAccess.READ_WRITE);
- // Remove the core part
- p.deletePartRecursive(PackagingURIHelper.createPartName("/word/document.xml"));
-
- for (PackagePart part : p.getParts()) {
- values.put(part.getPartName(), part.getContentType());
- logger.debug(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));
- }
- // Don't save modifications
- p.revert();
- }
-
- private static ContentTypeManager getContentTypeManager(Package pkg) throws Exception {
- Field f = Package.class.getDeclaredField("contentTypeManager");
- f.setAccessible(true);
- return (ContentTypeManager)f.get(pkg);
- }
-}
+/* ==================================================================== + 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.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.net.URI; +import java.util.TreeMap; + +import junit.framework.TestCase; + +import org.apache.log4j.Logger; +import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.internal.ContentTypeManager; +import org.apache.poi.openxml4j.opc.internal.FileHelper; +import org.dom4j.Document; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.dom4j.Namespace; +import org.dom4j.QName; + +public final class TestPackage extends TestCase { + private static Logger logger = Logger.getLogger("org.apache.poi.openxml4j.test"); + + /** + * Test that just opening and closing the file doesn't alter the document. + */ + public void testOpenSave() throws Exception { + String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx"); + + OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE); + p.save(targetFile.getAbsoluteFile()); + + // Compare the original and newly saved document + assertTrue(targetFile.exists()); + //ZipFileAssert.assertEquals(originalFile, targetFile); + assertTrue(targetFile.delete()); + } + + /** + * Test that when we create a new Package, we give it + * the correct default content types + */ + public void testCreateGetsContentTypes() throws Exception { + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx"); + + // Zap the target file, in case of an earlier run + if(targetFile.exists()) targetFile.delete(); + + OPCPackage pkg = OPCPackage.create(targetFile); + + // Check it has content types for rels and xml + ContentTypeManager ctm = getContentTypeManager(pkg); + assertEquals( + "application/xml", + ctm.getContentType( + PackagingURIHelper.createPartName("/foo.xml") + ) + ); + assertEquals( + ContentTypes.RELATIONSHIPS_PART, + ctm.getContentType( + PackagingURIHelper.createPartName("/foo.rels") + ) + ); + assertNull( + ctm.getContentType( + PackagingURIHelper.createPartName("/foo.txt") + ) + ); + } + + /** + * Test package creation. + */ + public void testCreatePackageAddPart() throws Exception { + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx"); + + File expectedFileFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageOUTPUT.docx"); + + // Zap the target file, in case of an earlier run + if(targetFile.exists()) targetFile.delete(); + + // Create a package + OPCPackage pkg = OPCPackage.create(targetFile); + PackagePartName corePartName = PackagingURIHelper + .createPartName("/word/document.xml"); + + pkg.addRelationship(corePartName, TargetMode.INTERNAL, + PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); + + PackagePart corePart = pkg + .createPart( + corePartName, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"); + + Document doc = DocumentHelper.createDocument(); + Namespace nsWordprocessinML = new Namespace("w", + "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); + Element elDocument = doc.addElement(new QName("document", + nsWordprocessinML)); + Element elBody = elDocument.addElement(new QName("body", + nsWordprocessinML)); + Element elParagraph = elBody.addElement(new QName("p", + nsWordprocessinML)); + Element elRun = elParagraph + .addElement(new QName("r", nsWordprocessinML)); + Element elText = elRun.addElement(new QName("t", nsWordprocessinML)); + elText.setText("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 + */ + public void testCreatePackageWithCoreDocument() throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + OPCPackage pkg = OPCPackage.create(baos); + + // Add a core document + PackagePartName corePartName = PackagingURIHelper.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, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"); + // Put in some dummy content + OutputStream coreOut = corePart.getOutputStream(); + coreOut.write("<dummy-xml />".getBytes()); + coreOut.close(); + + // And another bit + PackagePartName sheetPartName = PackagingURIHelper.createPartName("/xl/worksheets/sheet1.xml"); + PackageRelationship rel = + corePart.addRelationship(sheetPartName, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", "rSheet1"); + PackagePart part = pkg.createPart(sheetPartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"); + // Dummy content again + coreOut = corePart.getOutputStream(); + coreOut.write("<dummy-xml2 />".getBytes()); + coreOut.close(); + + + // Check things are as expected + PackageRelationshipCollection coreRels = + pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); + assertEquals(1, coreRels.size()); + PackageRelationship coreRel = coreRels.getRelationship(0); + assertEquals("/", coreRel.getSourceURI().toString()); + assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString()); + assertNotNull(pkg.getPart(coreRel)); + + + // Save and re-load + pkg.close(); + FileOutputStream fout = new FileOutputStream(File.createTempFile("testCreatePackageWithCoreDocument", ".zip")); + fout.write(baos.toByteArray()); + fout.close(); + pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray())); + + + // Check still right + coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); + assertEquals(1, coreRels.size()); + coreRel = coreRels.getRelationship(0); + assertEquals("/", coreRel.getSourceURI().toString()); + assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString()); + assertNotNull(pkg.getPart(coreRel)); + } + + /** + * Test package opening. + */ + public void testOpenPackage() throws Exception { + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageTMP.docx"); + + File inputFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageINPUT.docx"); + + File expectedFile = OpenXML4JTestDataSamples.getOutputFile("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 = PackagingURIHelper + .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(PackagingURIHelper.createPartName(PackagingURIHelper + .resolvePartUri(corePart.getPartName().getURI(), rel + .getTargetURI()))); + } + + // Create a content + Document doc = DocumentHelper.createDocument(); + Namespace nsWordprocessinML = new Namespace("w", + "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); + Element elDocument = doc.addElement(new QName("document", + nsWordprocessinML)); + Element elBody = elDocument.addElement(new QName("body", + nsWordprocessinML)); + Element elParagraph = elBody.addElement(new QName("p", + nsWordprocessinML)); + Element elRun = elParagraph + .addElement(new QName("r", nsWordprocessinML)); + Element elText = elRun.addElement(new QName("t", nsWordprocessinML)); + elText.setText("Hello Open XML !"); + + StreamHelper.saveXmlInStream(doc, corePart.getOutputStream()); + + // Save and close + try { + pkg.close(); + } catch (IOException e) { + fail(); + } + + //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 + */ + public void testSaveToOutputStream() throws Exception { + String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx"); + + OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE); + FileOutputStream fout = new FileOutputStream(targetFile); + p.save(fout); + fout.close(); + + // Compare the original and newly saved document + assertTrue(targetFile.exists()); + //ZipFileAssert.assertEquals(originalFile, targetFile); + assertTrue(targetFile.delete()); + } + + /** + * Checks that we can open+read a package from a + * simple InputStream, in addition to the normal + * reading from a file + */ + public void testOpenFromInputStream() throws Exception { + String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); + + FileInputStream finp = new FileInputStream(originalFile); + + OPCPackage p = OPCPackage.open(finp); + + assertNotNull(p); + assertNotNull(p.getRelationships()); + assertEquals(12, p.getParts().size()); + + // Check it has the usual bits + assertTrue(p.hasRelationships()); + assertTrue(p.containPart(PackagingURIHelper.createPartName("/_rels/.rels"))); + } + + /** + * TODO: fix and enable + */ + public void disabled_testRemovePartRecursive() throws Exception { + String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); + File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx"); + File tempFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveTMP.docx"); + + OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE); + p.removePartRecursive(PackagingURIHelper.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()); + } + + public void testDeletePart() throws InvalidFormatException { + TreeMap<PackagePartName, String> expectedValues; + TreeMap<PackagePartName, String> values; + + values = new TreeMap<PackagePartName, String>(); + + // Expected values + expectedValues = new TreeMap<PackagePartName, String>(); + 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/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"); + + String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); + + OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE); + // Remove the core part + p.deletePart(PackagingURIHelper.createPartName("/word/document.xml")); + + for (PackagePart part : p.getParts()) { + values.put(part.getPartName(), part.getContentType()); + logger.debug(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)); + } + // Don't save modifications + p.revert(); + } + + public void testDeletePartRecursive() throws InvalidFormatException { + TreeMap<PackagePartName, String> expectedValues; + TreeMap<PackagePartName, String> values; + + values = new TreeMap<PackagePartName, String>(); + + // Expected values + expectedValues = new TreeMap<PackagePartName, String>(); + 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"); + + String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); + + OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE); + // Remove the core part + p.deletePartRecursive(PackagingURIHelper.createPartName("/word/document.xml")); + + for (PackagePart part : p.getParts()) { + values.put(part.getPartName(), part.getContentType()); + logger.debug(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)); + } + // Don't save modifications + p.revert(); + } + + private static ContentTypeManager getContentTypeManager(OPCPackage pkg) throws Exception { + Field f = OPCPackage.class.getDeclaredField("contentTypeManager"); + f.setAccessible(true); + return (ContentTypeManager)f.get(pkg); + } +} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java index 54e21b89d3..1014279981 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java @@ -1,121 +1,121 @@ -/* ====================================================================
- 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.File;
-import java.io.IOException;
-import java.text.ParsePosition;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import junit.framework.TestCase;
-
-import org.apache.log4j.Logger;
-import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
-import org.apache.poi.openxml4j.util.Nullable;
-
-public final class TestPackageCoreProperties extends TestCase {
-
- /**
- * Test package core properties getters.
- */
- public void testGetProperties() {
- try {
- // Open the package
- Package p = Package.open(OpenXML4JTestDataSamples.openSampleStream("TestPackageCoreProperiesGetters.docx"));
- compareProperties(p);
- p.revert();
- } catch (OpenXML4JException e) {
- Logger.getLogger("org.apache.poi.openxml4j.demo").debug(e.getMessage());
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Test package core properties setters.
- */
- public void testSetProperties() throws Exception {
- String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCoreProperiesSetters.docx");
-
- File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx");
-
- // Open package
- Package p = Package.open(inputPath, PackageAccess.READ_WRITE);
-
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
- Date dateToInsert = df.parse("2007-05-12T08:00:00Z", new ParsePosition(
- 0));
-
- PackageProperties props = p.getPackageProperties();
- props.setCategoryProperty("MyCategory");
- props.setContentStatusProperty("MyContentStatus");
- props.setContentTypeProperty("MyContentType");
- props.setCreatedProperty(new Nullable<Date>(dateToInsert));
- props.setCreatorProperty("MyCreator");
- props.setDescriptionProperty("MyDescription");
- props.setIdentifierProperty("MyIdentifier");
- props.setKeywordsProperty("MyKeywords");
- props.setLanguageProperty("MyLanguage");
- props.setLastModifiedByProperty("Julien Chable");
- props.setLastPrintedProperty(new Nullable<Date>(dateToInsert));
- props.setModifiedProperty(new Nullable<Date>(dateToInsert));
- props.setRevisionProperty("2");
- props.setTitleProperty("MyTitle");
- props.setSubjectProperty("MySubject");
- props.setVersionProperty("2");
- // Save the package in the output directory
- p.save(outputFile);
-
- // Open the newly created file to check core properties saved values.
- Package p2 = Package.open(outputFile.getAbsolutePath(), PackageAccess.READ);
- compareProperties(p2);
- p2.revert();
- outputFile.delete();
- }
-
- private void compareProperties(Package p) throws InvalidFormatException {
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
- Date expectedDate = df.parse("2007-05-12T08:00:00Z", new ParsePosition(
- 0));
-
- // Gets the core properties
- PackageProperties props = p.getPackageProperties();
- assertEquals("MyCategory", props.getCategoryProperty().getValue());
- assertEquals("MyContentStatus", props.getContentStatusProperty()
- .getValue());
- assertEquals("MyContentType", props.getContentTypeProperty().getValue());
- assertEquals(expectedDate, props.getCreatedProperty().getValue());
- assertEquals("MyCreator", props.getCreatorProperty().getValue());
- assertEquals("MyDescription", props.getDescriptionProperty().getValue());
- assertEquals("MyIdentifier", props.getIdentifierProperty().getValue());
- assertEquals("MyKeywords", props.getKeywordsProperty().getValue());
- assertEquals("MyLanguage", props.getLanguageProperty().getValue());
- assertEquals("Julien Chable", props.getLastModifiedByProperty()
- .getValue());
- assertEquals(expectedDate, props.getLastPrintedProperty().getValue());
- assertEquals(expectedDate, props.getModifiedProperty().getValue());
- assertEquals("2", props.getRevisionProperty().getValue());
- assertEquals("MySubject", props.getSubjectProperty().getValue());
- assertEquals("MyTitle", props.getTitleProperty().getValue());
- assertEquals("2", props.getVersionProperty().getValue());
- }
-}
+/* ==================================================================== + 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.File; +import java.io.IOException; +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.util.Date; + +import junit.framework.TestCase; + +import org.apache.log4j.Logger; +import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.exceptions.OpenXML4JException; +import org.apache.poi.openxml4j.util.Nullable; + +public final class TestPackageCoreProperties extends TestCase { + + /** + * Test package core properties getters. + */ + public void testGetProperties() { + try { + // Open the package + OPCPackage p = OPCPackage.open(OpenXML4JTestDataSamples.openSampleStream("TestPackageCoreProperiesGetters.docx")); + compareProperties(p); + p.revert(); + } catch (OpenXML4JException e) { + Logger.getLogger("org.apache.poi.openxml4j.demo").debug(e.getMessage()); + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Test package core properties setters. + */ + public void testSetProperties() throws Exception { + String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCoreProperiesSetters.docx"); + + File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx"); + + // Open package + OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE); + + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + Date dateToInsert = df.parse("2007-05-12T08:00:00Z", new ParsePosition( + 0)); + + PackageProperties props = p.getPackageProperties(); + props.setCategoryProperty("MyCategory"); + props.setContentStatusProperty("MyContentStatus"); + props.setContentTypeProperty("MyContentType"); + props.setCreatedProperty(new Nullable<Date>(dateToInsert)); + props.setCreatorProperty("MyCreator"); + props.setDescriptionProperty("MyDescription"); + props.setIdentifierProperty("MyIdentifier"); + props.setKeywordsProperty("MyKeywords"); + props.setLanguageProperty("MyLanguage"); + props.setLastModifiedByProperty("Julien Chable"); + props.setLastPrintedProperty(new Nullable<Date>(dateToInsert)); + props.setModifiedProperty(new Nullable<Date>(dateToInsert)); + props.setRevisionProperty("2"); + props.setTitleProperty("MyTitle"); + props.setSubjectProperty("MySubject"); + props.setVersionProperty("2"); + // Save the package in the output directory + p.save(outputFile); + + // Open the newly created file to check core properties saved values. + 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'"); + Date expectedDate = df.parse("2007-05-12T08:00:00Z", new ParsePosition( + 0)); + + // Gets the core properties + PackageProperties props = p.getPackageProperties(); + assertEquals("MyCategory", props.getCategoryProperty().getValue()); + assertEquals("MyContentStatus", props.getContentStatusProperty() + .getValue()); + assertEquals("MyContentType", props.getContentTypeProperty().getValue()); + assertEquals(expectedDate, props.getCreatedProperty().getValue()); + assertEquals("MyCreator", props.getCreatorProperty().getValue()); + assertEquals("MyDescription", props.getDescriptionProperty().getValue()); + assertEquals("MyIdentifier", props.getIdentifierProperty().getValue()); + assertEquals("MyKeywords", props.getKeywordsProperty().getValue()); + assertEquals("MyLanguage", props.getLanguageProperty().getValue()); + assertEquals("Julien Chable", props.getLastModifiedByProperty() + .getValue()); + assertEquals(expectedDate, props.getLastPrintedProperty().getValue()); + assertEquals(expectedDate, props.getModifiedProperty().getValue()); + assertEquals("2", props.getRevisionProperty().getValue()); + assertEquals("MySubject", props.getSubjectProperty().getValue()); + assertEquals("MyTitle", props.getTitleProperty().getValue()); + assertEquals("2", props.getVersionProperty().getValue()); + } +} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java index a7b9e7b6f6..01a44327c7 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java @@ -1,57 +1,57 @@ -/* ====================================================================
- 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.File;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
-
-/**
- * Test the addition of thumbnail in a package.
- *
- * @author Julien Chable
- */
-public final class TestPackageThumbnail extends TestCase {
-
- /**
- * Test package addThumbnail() method.
- */
- public void testSetProperties() throws Exception {
- String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageThumbnail.docx");
-
- String imagePath = OpenXML4JTestDataSamples.getSampleFileName("thumbnail.jpg");
-
- File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageThumbnailOUTPUT.docx");
-
- // Open package
- Package p = Package.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.
- Package p2 = Package.open(outputFile.getAbsolutePath(), PackageAccess.READ);
- if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL)
- .size() == 0)
- fail("Thumbnail not added to the package !");
- p2.revert();
- outputFile.delete();
- }
-}
+/* ==================================================================== + 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.File; + +import junit.framework.TestCase; + +import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; + +/** + * Test the addition of thumbnail in a package. + * + * @author Julien Chable + */ +public final class TestPackageThumbnail extends TestCase { + + /** + * Test package addThumbnail() method. + */ + public void testSetProperties() throws Exception { + String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageThumbnail.docx"); + + String imagePath = OpenXML4JTestDataSamples.getSampleFileName("thumbnail.jpg"); + + File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageThumbnailOUTPUT.docx"); + + // Open package + 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. + OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ); + if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL) + .size() == 0) + fail("Thumbnail not added to the package !"); + p2.revert(); + 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 index 478552f70f..48a4b4ecc1 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java @@ -1,117 +1,117 @@ -/* ====================================================================
- 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.net.URI;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.openxml4j.opc.ContentTypes;
-import org.apache.poi.openxml4j.opc.Package;
-import org.apache.poi.openxml4j.opc.PackagePart;
-import org.apache.poi.openxml4j.opc.PackagePartName;
-import org.apache.poi.openxml4j.opc.PackagingURIHelper;
-
-public class TestPackagingURIHelper extends TestCase {
-
- /**
- * Test relativizePartName() method.
- *
- * TODO: fix and unable
- */
- public void testRelativizeURI() throws Exception {
- URI uri1 = new URI("/word/document.xml");
- URI uri2 = new URI("/word/media/image1.gif");
-
- // 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);
- assertEquals("", retURI2.getPath());
-
- // Document and root totally different
- URI uri4 = new URI("/");
- try {
- PackagingURIHelper.relativizeURI(uri1, uri4);
- //TODO: figure oout why the assertion fails
- //fail("Must throw an exception ! Can't relativize with an empty URI");
- } catch (Exception e) {
- // Do nothing
- }
- try {
- PackagingURIHelper.relativizeURI(uri4, uri1);
- //TODO: figure oout why the assertion fails
- //fail("Must throw an exception ! Can't relativize with an empty URI");
- } catch (Exception e) {
- // Do nothing
- }
- }
-
- /**
- * Test createPartName(String, y)
- */
- public void testCreatePartNameRelativeString()
- throws InvalidFormatException {
- PackagePartName partNameToValid = PackagingURIHelper
- .createPartName("/word/media/image1.gif");
-
- Package pkg = Package.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);
- assertTrue("The part name must be equal to "
- + partNameToValid.getName(), partNameToValid
- .equals(relativeName));
- pkg.revert();
- }
-
- /**
- * Test createPartName(URI, y)
- */
- public void testCreatePartNameRelativeURI() throws Exception {
- PackagePartName partNameToValid = PackagingURIHelper
- .createPartName("/word/media/image1.gif");
-
- Package pkg = Package.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);
- assertTrue("The part name must be equal to "
- + partNameToValid.getName(), partNameToValid
- .equals(relativeName));
- pkg.revert();
- }
-}
+/* ==================================================================== + 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.net.URI; + +import junit.framework.TestCase; + +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.ContentTypes; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.openxml4j.opc.PackagePart; +import org.apache.poi.openxml4j.opc.PackagePartName; +import org.apache.poi.openxml4j.opc.PackagingURIHelper; + +public class TestPackagingURIHelper extends TestCase { + + /** + * Test relativizePartName() method. + * + * TODO: fix and unable + */ + public void testRelativizeURI() throws Exception { + URI uri1 = new URI("/word/document.xml"); + URI uri2 = new URI("/word/media/image1.gif"); + + // 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); + assertEquals("", retURI2.getPath()); + + // Document and root totally different + URI uri4 = new URI("/"); + try { + PackagingURIHelper.relativizeURI(uri1, uri4); + //TODO: figure oout why the assertion fails + //fail("Must throw an exception ! Can't relativize with an empty URI"); + } catch (Exception e) { + // Do nothing + } + try { + PackagingURIHelper.relativizeURI(uri4, uri1); + //TODO: figure oout why the assertion fails + //fail("Must throw an exception ! Can't relativize with an empty URI"); + } catch (Exception e) { + // Do nothing + } + } + + /** + * Test createPartName(String, y) + */ + public 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); + assertTrue("The part name must be equal to " + + partNameToValid.getName(), partNameToValid + .equals(relativeName)); + pkg.revert(); + } + + /** + * Test createPartName(URI, y) + */ + public 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); + assertTrue("The part name must be equal to " + + partNameToValid.getName(), partNameToValid + .equals(relativeName)); + pkg.revert(); + } +} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java index 972bd268a3..a4ef876b47 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java @@ -45,7 +45,7 @@ public class TestRelationships extends TestCase { */ public void testLoadRelationships() throws Exception { InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.xlsx"); - Package pkg = Package.open(is); + OPCPackage pkg = OPCPackage.open(is); logger.debug("1: " + pkg); PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); PackageRelationship coreDocRelationship = rels.getRelationship(0); @@ -66,7 +66,7 @@ public class TestRelationships extends TestCase { */ public void testFetchFromCollection() throws Exception { InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx"); - Package pkg = Package.open(is); + OPCPackage pkg = OPCPackage.open(is); PackagePart sheet = pkg.getPart( PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); assertNotNull(sheet); @@ -107,7 +107,7 @@ public class TestRelationships extends TestCase { */ public void testLoadExcelHyperlinkRelations() throws Exception { InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx"); - Package pkg = Package.open(is); + OPCPackage pkg = OPCPackage.open(is); PackagePart sheet = pkg.getPart( PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); assertNotNull(sheet); @@ -141,7 +141,7 @@ public class TestRelationships extends TestCase { */ public void testCreateExcelHyperlinkRelations() throws Exception { String filepath = OpenXML4JTestDataSamples.getSampleFileName("ExcelWithHyperlinks.xlsx"); - Package pkg = Package.open(filepath, PackageAccess.READ_WRITE); + OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE); PackagePart sheet = pkg.getPart( PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); assertNotNull(sheet); @@ -185,7 +185,7 @@ public class TestRelationships extends TestCase { ByteArrayOutputStream baos = new ByteArrayOutputStream(); pkg.save(baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = Package.open(bais); + pkg = OPCPackage.open(bais); // Check again sheet = pkg.getPart( @@ -208,7 +208,7 @@ public class TestRelationships extends TestCase { public void testCreateRelationsFromScratch() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Package pkg = Package.create(baos); + OPCPackage pkg = OPCPackage.create(baos); PackagePart partA = pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain"); @@ -235,7 +235,7 @@ public class TestRelationships extends TestCase { // Save, and re-load pkg.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = Package.open(bais); + pkg = OPCPackage.open(bais); partA = pkg.getPart(PackagingURIHelper.createPartName("/partA")); partB = pkg.getPart(PackagingURIHelper.createPartName("/partB")); 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 index d2cb8f616e..7d26fddd7a 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java @@ -1,208 +1,208 @@ -/* ====================================================================
- 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 java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.net.URISyntaxException;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.TestCase;
-
-import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
-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.Package;
-import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
-import org.apache.poi.openxml4j.opc.PackagingURIHelper;
-import org.apache.poi.openxml4j.opc.TargetMode;
-
-/**
- * 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.
- *
- * 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.
- *
- * @author Julien Chable
- */
-public final class TestOPCComplianceCoreProperties extends TestCase {
-
- public void testCorePropertiesPart() {
- Package pkg;
- try {
- InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
- pkg = Package.open(is);
- } catch (InvalidFormatException e) {
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- pkg.revert();
- }
-
- private static String extractInvalidFormatMessage(String sampleNameSuffix) {
-
- InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix);
- Package pkg;
- try {
- pkg = Package.open(is);
- } catch (InvalidFormatException e) {
- // expected during successful test
- return e.getMessage();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- pkg.revert();
- // Normally must thrown an InvalidFormatException exception.
- throw new AssertionFailedError("expected OPC compliance exception was not thrown");
- }
-
- /**
- * Test M4.1 rule.
- */
- public void testOnlyOneCorePropertiesPart() {
- String msg = extractInvalidFormatMessage("OnlyOneCorePropertiesPartFAIL.docx");
- assertEquals("OPC Compliance error [M4.1]: there is more than one core properties relationship in the package !", msg);
- }
-
- private static URI createURI(String text) {
- try {
- return new URI(text);
- } catch (URISyntaxException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Test M4.1 rule.
- */
- public void testOnlyOneCorePropertiesPart_AddRelationship() {
- InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
- Package pkg;
- try {
- pkg = Package.open(is);
- } catch (InvalidFormatException e) {
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- URI partUri = createURI("/docProps/core2.xml");
- try {
- pkg.addRelationship(PackagingURIHelper.createPartName(partUri), TargetMode.INTERNAL,
- PackageRelationshipTypes.CORE_PROPERTIES);
- fail("expected OPC compliance exception was not thrown");
- } catch (InvalidFormatException e) {
- throw new RuntimeException(e);
- } catch (InvalidOperationException e) {
- // expected during successful test
- 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.
- */
- public void testOnlyOneCorePropertiesPart_AddPart() {
- String sampleFileName = OpenXML4JTestDataSamples.getComplianceSampleFileName("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
- Package pkg = null;
- try {
- pkg = Package.open(sampleFileName);
- } catch (InvalidFormatException e) {
- throw new RuntimeException(e);
- }
-
- URI partUri = createURI("/docProps/core2.xml");
- try {
- pkg.createPart(PackagingURIHelper.createPartName(partUri),
- ContentTypes.CORE_PROPERTIES_PART);
- fail("expected OPC compliance exception was not thrown");
- } catch (InvalidFormatException e) {
- throw new RuntimeException(e);
- } catch (InvalidOperationException e) {
- // expected during successful test
- 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.
- */
- public void testDoNotUseCompatibilityMarkup() {
- 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.
- */
- public void testDCTermsNamespaceLimitedUse() {
- 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.
- */
- public void testUnauthorizedXMLLangAttribute() {
- 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.
- */
- public void testLimitedXSITypeAttribute_NotPresent() {
- String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_NotPresentFAIL.docx");
- assertEquals("The element 'created' must have the 'xsi:type' attribute present !", msg);
- }
-
- /**
- * Test M4.5 rule.
- */
- public void testLimitedXSITypeAttribute_PresentWithUnauthorizedValue() {
- String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx");
- assertEquals("The element 'modified' must have the 'xsi:type' attribute with the value 'dcterms:W3CDTF' !", msg);
- }
-}
+/* ==================================================================== + 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 java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; + +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; + +import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; +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; + +/** + * 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. + * + * 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. + * + * @author Julien Chable + */ +public final class TestOPCComplianceCoreProperties extends TestCase { + + public void testCorePropertiesPart() { + OPCPackage pkg; + try { + InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx"); + pkg = OPCPackage.open(is); + } catch (InvalidFormatException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + pkg.revert(); + } + + private static String extractInvalidFormatMessage(String sampleNameSuffix) { + + InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix); + OPCPackage pkg; + try { + pkg = OPCPackage.open(is); + } catch (InvalidFormatException e) { + // expected during successful test + return e.getMessage(); + } catch (IOException e) { + throw new RuntimeException(e); + } + pkg.revert(); + // Normally must thrown an InvalidFormatException exception. + throw new AssertionFailedError("expected OPC compliance exception was not thrown"); + } + + /** + * Test M4.1 rule. + */ + public void testOnlyOneCorePropertiesPart() { + String msg = extractInvalidFormatMessage("OnlyOneCorePropertiesPartFAIL.docx"); + assertEquals("OPC Compliance error [M4.1]: there is more than one core properties relationship in the package !", msg); + } + + private static URI createURI(String text) { + try { + return new URI(text); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + /** + * Test M4.1 rule. + */ + public void testOnlyOneCorePropertiesPart_AddRelationship() { + InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx"); + OPCPackage pkg; + try { + pkg = OPCPackage.open(is); + } catch (InvalidFormatException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + URI partUri = createURI("/docProps/core2.xml"); + try { + pkg.addRelationship(PackagingURIHelper.createPartName(partUri), TargetMode.INTERNAL, + PackageRelationshipTypes.CORE_PROPERTIES); + fail("expected OPC compliance exception was not thrown"); + } catch (InvalidFormatException e) { + throw new RuntimeException(e); + } catch (InvalidOperationException e) { + // expected during successful test + 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. + */ + public void testOnlyOneCorePropertiesPart_AddPart() { + String sampleFileName = OpenXML4JTestDataSamples.getComplianceSampleFileName("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx"); + OPCPackage pkg = null; + try { + pkg = OPCPackage.open(sampleFileName); + } catch (InvalidFormatException e) { + throw new RuntimeException(e); + } + + URI partUri = createURI("/docProps/core2.xml"); + try { + pkg.createPart(PackagingURIHelper.createPartName(partUri), + ContentTypes.CORE_PROPERTIES_PART); + fail("expected OPC compliance exception was not thrown"); + } catch (InvalidFormatException e) { + throw new RuntimeException(e); + } catch (InvalidOperationException e) { + // expected during successful test + 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. + */ + public void testDoNotUseCompatibilityMarkup() { + 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. + */ + public void testDCTermsNamespaceLimitedUse() { + 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. + */ + public void testUnauthorizedXMLLangAttribute() { + 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. + */ + public void testLimitedXSITypeAttribute_NotPresent() { + String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_NotPresentFAIL.docx"); + assertEquals("The element 'created' must have the 'xsi:type' attribute present !", msg); + } + + /** + * Test M4.5 rule. + */ + public void testLimitedXSITypeAttribute_PresentWithUnauthorizedValue() { + String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx"); + assertEquals("The element 'modified' must have the 'xsi:type' attribute with the value 'dcterms:W3CDTF' !", msg); + } +} 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 index f135b41388..332642f69a 100755 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java @@ -1,162 +1,162 @@ -/* ====================================================================
- 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 java.io.File;
-
-import junit.framework.TestCase;
-
-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.Package;
-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;
-
-/**
- * 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.
- *
- * @author Julien Chable
- */
-public class TestOPCCompliancePackageModel extends TestCase {
-
- public TestOPCCompliancePackageModel(String name) {
- super(name);
- }
-
- /**
- * 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]
- */
- public void testPartNameDerivationAdditionFailure() {
- Package pkg = Package.create("TODELETEIFEXIST.docx");
- try {
- PackagePartName name = PackagingURIHelper
- .createPartName("/word/document.xml");
- PackagePartName nameDerived = PackagingURIHelper
- .createPartName("/word/document.xml/image1.gif");
- pkg.createPart(name, ContentTypes.XML);
- pkg.createPart(nameDerived, ContentTypes.EXTENSION_GIF);
- } catch (InvalidOperationException e) {
- pkg.revert();
- return;
- } catch (InvalidFormatException e) {
- fail(e.getMessage());
- }
- fail("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]");
- }
-
- /**
- * 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]
- */
- public void testPartNameDerivationReadingFailure() {
- String filepath = System.getProperty("openxml4j.compliance.input")
- + File.separator + "OPCCompliance_DerivedPartNameFAIL.docx";
- try {
- Package.open(filepath);
- } catch (InvalidFormatException e) {
- return;
- }
- fail("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.
- */
- public void testAddPackageAlreadyAddFailure() throws Exception {
- Package pkg = Package.create("DELETEIFEXISTS.docx");
- PackagePartName name1 = null;
- PackagePartName name2 = null;
- try {
- name1 = PackagingURIHelper.createPartName("/word/document.xml");
- name2 = PackagingURIHelper.createPartName("/word/document.xml");
- } catch (InvalidFormatException e) {
- throw new Exception(e.getMessage());
- }
- pkg.createPart(name1, ContentTypes.XML);
- try {
- pkg.createPart(name2, ContentTypes.XML);
- } catch (InvalidOperationException e) {
- return;
- }
- fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]");
- }
-
- /**
- * Rule M1.12 : Packages shall not contain equivalent part names and package
- * implementers shall neither create nor recognize packages with equivalent
- * part names.
- */
- public void testAddPackageAlreadyAddFailure2() throws Exception {
- Package pkg = Package.create("DELETEIFEXISTS.docx");
- PackagePartName partName = null;
- try {
- partName = PackagingURIHelper.createPartName("/word/document.xml");
- } catch (InvalidFormatException e) {
- throw new Exception(e.getMessage());
- }
- pkg.createPart(partName, ContentTypes.XML);
- try {
- pkg.createPart(partName, ContentTypes.XML);
- } catch (InvalidOperationException e) {
- return;
- }
- fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]");
- }
-
- /**
- * Try to add a relationship to a relationship part.
- *
- * Check rule M1.25: The Relationships part shall not have relationships to
- * any other part. Package implementers shall enforce this requirement upon
- * the attempt to create such a relationship and shall treat any such
- * relationship as invalid.
- */
- public void testAddRelationshipRelationshipsPartFailure() {
- Package pkg = Package.create("DELETEIFEXISTS.docx");
- PackagePartName name1 = null;
- try {
- name1 = PackagingURIHelper
- .createPartName("/test/_rels/document.xml.rels");
- } catch (InvalidFormatException e) {
- fail("This exception should never happen !");
- }
-
- try {
- pkg.addRelationship(name1, TargetMode.INTERNAL,
- PackageRelationshipTypes.CORE_DOCUMENT);
- } catch (InvalidOperationException e) {
- return;
- }
- fail("Fail test -> M1.25: The Relationships part shall not have relationships to any other part");
- }
-}
+/* ==================================================================== + 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 java.io.File; + +import junit.framework.TestCase; + +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.PackagePartName; +import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; +import org.apache.poi.openxml4j.opc.PackagingURIHelper; +import org.apache.poi.openxml4j.opc.TargetMode; + +/** + * 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. + * + * @author Julien Chable + */ +public class TestOPCCompliancePackageModel extends TestCase { + + public TestOPCCompliancePackageModel(String name) { + super(name); + } + + /** + * 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] + */ + public void testPartNameDerivationAdditionFailure() { + OPCPackage pkg = OPCPackage.create("TODELETEIFEXIST.docx"); + try { + PackagePartName name = PackagingURIHelper + .createPartName("/word/document.xml"); + PackagePartName nameDerived = PackagingURIHelper + .createPartName("/word/document.xml/image1.gif"); + pkg.createPart(name, ContentTypes.XML); + pkg.createPart(nameDerived, ContentTypes.EXTENSION_GIF); + } catch (InvalidOperationException e) { + pkg.revert(); + return; + } catch (InvalidFormatException e) { + fail(e.getMessage()); + } + fail("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]"); + } + + /** + * 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] + */ + public void testPartNameDerivationReadingFailure() { + String filepath = System.getProperty("openxml4j.compliance.input") + + File.separator + "OPCCompliance_DerivedPartNameFAIL.docx"; + try { + OPCPackage.open(filepath); + } catch (InvalidFormatException e) { + return; + } + fail("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. + */ + public void testAddPackageAlreadyAddFailure() throws Exception { + OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); + PackagePartName name1 = null; + PackagePartName name2 = null; + try { + name1 = PackagingURIHelper.createPartName("/word/document.xml"); + name2 = PackagingURIHelper.createPartName("/word/document.xml"); + } catch (InvalidFormatException e) { + throw new Exception(e.getMessage()); + } + pkg.createPart(name1, ContentTypes.XML); + try { + pkg.createPart(name2, ContentTypes.XML); + } catch (InvalidOperationException e) { + return; + } + fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); + } + + /** + * Rule M1.12 : Packages shall not contain equivalent part names and package + * implementers shall neither create nor recognize packages with equivalent + * part names. + */ + public void testAddPackageAlreadyAddFailure2() throws Exception { + OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); + PackagePartName partName = null; + try { + partName = PackagingURIHelper.createPartName("/word/document.xml"); + } catch (InvalidFormatException e) { + throw new Exception(e.getMessage()); + } + pkg.createPart(partName, ContentTypes.XML); + try { + pkg.createPart(partName, ContentTypes.XML); + } catch (InvalidOperationException e) { + return; + } + fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); + } + + /** + * Try to add a relationship to a relationship part. + * + * Check rule M1.25: The Relationships part shall not have relationships to + * any other part. Package implementers shall enforce this requirement upon + * the attempt to create such a relationship and shall treat any such + * relationship as invalid. + */ + public void testAddRelationshipRelationshipsPartFailure() { + OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); + PackagePartName name1 = null; + try { + name1 = PackagingURIHelper + .createPartName("/test/_rels/document.xml.rels"); + } catch (InvalidFormatException e) { + fail("This exception should never happen !"); + } + + try { + pkg.addRelationship(name1, TargetMode.INTERNAL, + PackageRelationshipTypes.CORE_DOCUMENT); + } catch (InvalidOperationException e) { + return; + } + fail("Fail test -> M1.25: The Relationships part shall not have relationships to any other part"); + } +} diff --git a/src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java b/src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java index f1553e0e16..af93ba9aa5 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java +++ b/src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java @@ -24,7 +24,7 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.openxml4j.opc.Package; +import org.apache.poi.openxml4j.opc.OPCPackage; import junit.framework.TestCase; @@ -63,7 +63,7 @@ public class TestWorkbookFactory extends TestCase { // Package -> xssf wb = WorkbookFactory.create( - Package.open(xlsx.toString()) + OPCPackage.open(xlsx.toString()) ); assertNotNull(wb); assertTrue(wb instanceof XSSFWorkbook); diff --git a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java index 13971f7efe..e1e821323c 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java @@ -18,14 +18,14 @@ package org.apache.poi.xslf; import java.io.File; +import junit.framework.TestCase; + import org.apache.poi.POIXMLDocument; -import org.apache.poi.openxml4j.opc.Package; +import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdListEntry; import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMasterIdListEntry; -import junit.framework.TestCase; - public class TestXSLFSlideShow extends TestCase { private String sampleFile; @@ -39,7 +39,7 @@ public class TestXSLFSlideShow extends TestCase { } public void testContainsMainContentType() throws Exception { - Package pack = POIXMLDocument.openPackage(sampleFile); + OPCPackage pack = POIXMLDocument.openPackage(sampleFile); boolean found = false; for(PackagePart part : pack.getParts()) { diff --git a/src/ooxml/testcases/org/apache/poi/xssf/XSSFTestDataSamples.java b/src/ooxml/testcases/org/apache/poi/xssf/XSSFTestDataSamples.java index 5214a22a2e..6c37c7086f 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/XSSFTestDataSamples.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/XSSFTestDataSamples.java @@ -1,75 +1,80 @@ -/* ====================================================================
- 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.xssf;
-
-import java.io.*;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.openxml4j.opc.Package;
-
-/**
- * Centralises logic for finding/opening sample files in the src/testcases/org/apache/poi/hssf/hssf/data folder.
- *
- * @author Josh Micich
- */
-public class XSSFTestDataSamples {
- public static final XSSFWorkbook openSampleWorkbook(String sampleName) {
- InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleName);
- try {
- Package pkg = Package.open(is);
- return new XSSFWorkbook(pkg);
- } catch (InvalidFormatException e) {
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- public static <R extends Workbook> R writeOutAndReadBack(R wb) {
- Workbook result;
- try {
- if (wb instanceof HSSFWorkbook) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
- wb.write(baos);
- InputStream is = new ByteArrayInputStream(baos.toByteArray());
- result = new HSSFWorkbook(is);
- } else if (wb instanceof XSSFWorkbook) {
- File tmp = File.createTempFile("poi-ooxml-", ".xlsx");
- tmp.deleteOnExit();
- FileOutputStream out = new FileOutputStream(tmp);
- wb.write(out);
- out.close();
- Package pkg = Package.open(tmp.getAbsolutePath());
- result = new XSSFWorkbook(pkg);
- } else {
- throw new RuntimeException("Unexpected workbook type ("
- + wb.getClass().getName() + ")");
- }
- } catch (InvalidFormatException e) {
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- @SuppressWarnings("unchecked")
- R r = (R) result;
- return r;
- }
-}
+/* ==================================================================== + 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.xssf; + +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 org.apache.poi.hssf.HSSFTestDataSamples; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +/** + * Centralises logic for finding/opening sample files in the src/testcases/org/apache/poi/hssf/hssf/data folder. + * + * @author Josh Micich + */ +public class XSSFTestDataSamples { + public static final XSSFWorkbook openSampleWorkbook(String sampleName) { + InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleName); + try { + OPCPackage pkg = OPCPackage.open(is); + return new XSSFWorkbook(pkg); + } catch (InvalidFormatException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + public static <R extends Workbook> R writeOutAndReadBack(R wb) { + Workbook result; + try { + if (wb instanceof HSSFWorkbook) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); + wb.write(baos); + InputStream is = new ByteArrayInputStream(baos.toByteArray()); + result = new HSSFWorkbook(is); + } else if (wb instanceof XSSFWorkbook) { + File tmp = File.createTempFile("poi-ooxml-", ".xlsx"); + tmp.deleteOnExit(); + FileOutputStream out = new FileOutputStream(tmp); + wb.write(out); + out.close(); + OPCPackage pkg = OPCPackage.open(tmp.getAbsolutePath()); + result = new XSSFWorkbook(pkg); + } else { + throw new RuntimeException("Unexpected workbook type (" + + wb.getClass().getName() + ")"); + } + } catch (InvalidFormatException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + @SuppressWarnings("unchecked") + R r = (R) result; + return r; + } +} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java index 9ad4af7baa..567cd014ea 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java @@ -25,7 +25,7 @@ import junit.framework.TestCase; import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.openxml4j.opc.Package; +import org.apache.poi.openxml4j.opc.OPCPackage; /** * Tests for XSSFReader @@ -49,7 +49,7 @@ public class TestXSSFReader extends TestCase { public void testGetBits() throws Exception { File f = new File(dirName, "SampleSS.xlsx"); - Package pkg = Package.open(f.toString()); + OPCPackage pkg = OPCPackage.open(f.toString()); XSSFReader r = new XSSFReader(pkg); @@ -63,7 +63,7 @@ public class TestXSSFReader extends TestCase { public void testStyles() throws Exception { File f = new File(dirName, "SampleSS.xlsx"); - Package pkg = Package.open(f.toString()); + OPCPackage pkg = OPCPackage.open(f.toString()); XSSFReader r = new XSSFReader(pkg); @@ -73,7 +73,7 @@ public class TestXSSFReader extends TestCase { public void testStrings() throws Exception { File f = new File(dirName, "SampleSS.xlsx"); - Package pkg = Package.open(f.toString()); + OPCPackage pkg = OPCPackage.open(f.toString()); XSSFReader r = new XSSFReader(pkg); @@ -83,7 +83,7 @@ public class TestXSSFReader extends TestCase { public void testSheets() throws Exception { File f = new File(dirName, "SampleSS.xlsx"); - Package pkg = Package.open(f.toString()); + OPCPackage pkg = OPCPackage.open(f.toString()); XSSFReader r = new XSSFReader(pkg); byte[] data = new byte[4096]; @@ -116,7 +116,7 @@ public class TestXSSFReader extends TestCase { */ public void testOrderOfSheets() throws Exception { File f = new File(dirName, "reordered_sheets.xlsx"); - Package pkg = Package.open(f.toString()); + OPCPackage pkg = OPCPackage.open(f.toString()); XSSFReader r = new XSSFReader(pkg); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java index 062a93e7c0..05a85fc548 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java @@ -32,7 +32,7 @@ import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.Package; +import org.apache.poi.openxml4j.opc.OPCPackage; import org.openxmlformats.schemas.spreadsheetml.x2006.main.*; import junit.framework.TestCase; @@ -125,7 +125,7 @@ public class TestCommentsTable extends TestCase { ); assertTrue(xml.exists()); - Package pkg = Package.open(xml.toString()); + OPCPackage pkg = OPCPackage.open(xml.toString()); XSSFWorkbook wb = new XSSFWorkbook(pkg); List<POIXMLDocumentPart> rels = wb.getSheetAt(0).getRelations(); CommentsTable ct = null; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java index 01160f23f5..b6182cb418 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java @@ -32,7 +32,7 @@ import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.openxml4j.opc.Package; +import org.apache.poi.openxml4j.opc.OPCPackage; /** * Performs much the same role as {@link TestFormulasFromSpreadsheet}, @@ -149,7 +149,7 @@ public final class TestFormulaEvaluatorOnXSSF extends TestCase { protected void setUp() throws Exception { if (workbook == null) { InputStream is = HSSFTestDataSamples.openSampleFileStream(SS.FILENAME); - Package pkg = Package.open(is); + OPCPackage pkg = OPCPackage.open(is); workbook = new XSSFWorkbook( pkg ); sheet = workbook.getSheetAt( 0 ); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java index b35d59c5b4..3715410ef9 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java @@ -21,7 +21,8 @@ import java.io.File; import junit.framework.TestCase; -import org.apache.poi.openxml4j.opc.Package; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.xssf.XSSFTestDataSamples; @@ -71,7 +72,7 @@ public class TestXSSFBugs extends TestCase { * We should carry vba macros over after save */ public void test45431() throws Exception { - Package pkg = Package.open(getFilePath("45431.xlsm")); + OPCPackage pkg = OPCPackage.open(getFilePath("45431.xlsm")); XSSFWorkbook wb = new XSSFWorkbook(pkg); assertTrue(wb.isMacroEnabled()); @@ -89,7 +90,7 @@ public class TestXSSFBugs extends TestCase { // Save and re-open, both still there XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); - Package nPkg = nwb.getPackage(); + OPCPackage nPkg = nwb.getPackage(); assertTrue(nwb.isMacroEnabled()); vba = nPkg.getPart( diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java index e4d6bc091f..8b721b6199 100755 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java @@ -1,77 +1,79 @@ -/* ====================================================================
- 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.xssf.usermodel;
-
-import junit.framework.TestCase;
-import org.apache.poi.xssf.XSSFTestDataSamples;
-import org.apache.poi.POIXMLDocumentPart;
-
-import java.util.List;
-
-/**
- * @author Yegor Kozlov
- */
-public class TestXSSFDrawing extends TestCase {
- public void testRead(){
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx");
- XSSFSheet sheet = wb.getSheetAt(0);
- //the sheet has one relationship and it is XSSFDrawing
- List<POIXMLDocumentPart> rels = sheet.getRelations();
- assertEquals(1, rels.size());
- assertTrue(rels.get(0) instanceof XSSFDrawing);
-
- XSSFDrawing drawing = (XSSFDrawing)rels.get(0);
- //sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing
- assertSame(drawing, sheet.createDrawingPatriarch());
- String drawingId = drawing.getPackageRelationship().getId();
-
- //there should be a relation to this drawing in the worksheet
- assertTrue(sheet.getCTWorksheet().isSetDrawing());
- assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId());
-
- }
-
- public void testNew(){
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFSheet sheet = wb.createSheet();
- //multiple calls of createDrawingPatriarch should return the same instance of XSSFDrawing
- XSSFDrawing dr1 = sheet.createDrawingPatriarch();
- XSSFDrawing dr2 = sheet.createDrawingPatriarch();
- assertSame(dr1, dr2);
-
- List<POIXMLDocumentPart> rels = sheet.getRelations();
- assertEquals(1, rels.size());
- assertTrue(rels.get(0) instanceof XSSFDrawing);
-
- XSSFDrawing drawing = (XSSFDrawing)rels.get(0);
- String drawingId = drawing.getPackageRelationship().getId();
-
- //there should be a relation to this drawing in the worksheet
- assertTrue(sheet.getCTWorksheet().isSetDrawing());
- assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId());
-
- }
- public void testMultipleDrawings(){
- XSSFWorkbook wb = new XSSFWorkbook();
- for (int i = 0; i < 3; i++) {
- XSSFSheet sheet = wb.createSheet();
- XSSFDrawing drawing = sheet.createDrawingPatriarch();
- }
- org.apache.poi.openxml4j.opc.Package pkg = wb.getPackage();
- assertEquals(3, pkg.getPartsByContentType(XSSFRelation.DRAWINGS.getContentType()).size());
- }
-}
+/* ==================================================================== + 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.xssf.usermodel; + +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.poi.POIXMLDocumentPart; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.xssf.XSSFTestDataSamples; + +/** + * @author Yegor Kozlov + */ +public class TestXSSFDrawing extends TestCase { + public void testRead(){ + XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx"); + XSSFSheet sheet = wb.getSheetAt(0); + //the sheet has one relationship and it is XSSFDrawing + List<POIXMLDocumentPart> rels = sheet.getRelations(); + assertEquals(1, rels.size()); + assertTrue(rels.get(0) instanceof XSSFDrawing); + + XSSFDrawing drawing = (XSSFDrawing)rels.get(0); + //sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing + assertSame(drawing, sheet.createDrawingPatriarch()); + String drawingId = drawing.getPackageRelationship().getId(); + + //there should be a relation to this drawing in the worksheet + assertTrue(sheet.getCTWorksheet().isSetDrawing()); + assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId()); + + } + + public void testNew(){ + XSSFWorkbook wb = new XSSFWorkbook(); + XSSFSheet sheet = wb.createSheet(); + //multiple calls of createDrawingPatriarch should return the same instance of XSSFDrawing + XSSFDrawing dr1 = sheet.createDrawingPatriarch(); + XSSFDrawing dr2 = sheet.createDrawingPatriarch(); + assertSame(dr1, dr2); + + List<POIXMLDocumentPart> rels = sheet.getRelations(); + assertEquals(1, rels.size()); + assertTrue(rels.get(0) instanceof XSSFDrawing); + + XSSFDrawing drawing = (XSSFDrawing)rels.get(0); + String drawingId = drawing.getPackageRelationship().getId(); + + //there should be a relation to this drawing in the worksheet + assertTrue(sheet.getCTWorksheet().isSetDrawing()); + assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId()); + + } + public void testMultipleDrawings(){ + XSSFWorkbook wb = new XSSFWorkbook(); + for (int i = 0; i < 3; i++) { + XSSFSheet sheet = wb.createSheet(); + XSSFDrawing drawing = sheet.createDrawingPatriarch(); + } + OPCPackage pkg = wb.getPackage(); + assertEquals(3, pkg.getPartsByContentType(XSSFRelation.DRAWINGS.getContentType()).size()); + } +} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java index 09acaac09e..73c181bd2b 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java @@ -29,7 +29,7 @@ import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.Package; +import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheet; @@ -251,7 +251,7 @@ public final class TestXSSFWorkbook extends TestCase { out.close(); // Check the package contains what we'd expect it to - Package pkg = Package.open(file.toString()); + OPCPackage pkg = OPCPackage.open(file.toString()); PackagePart wbRelPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/_rels/workbook.xml.rels")); assertNotNull(wbRelPart); @@ -293,7 +293,7 @@ public final class TestXSSFWorkbook extends TestCase { assertNotNull(workbook.getStylesSource()); // And check a few low level bits too - Package pkg = Package.open(HSSFTestDataSamples.openSampleFileStream("Formatting.xlsx")); + OPCPackage pkg = OPCPackage.open(HSSFTestDataSamples.openSampleFileStream("Formatting.xlsx")); PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFDocument.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFDocument.java index 24fbfcc895..68df95786c 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFDocument.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFDocument.java @@ -18,13 +18,13 @@ package org.apache.poi.xwpf; import java.io.File; +import junit.framework.TestCase; + import org.apache.poi.POIXMLDocument; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.apache.poi.openxml4j.opc.Package; -import org.apache.poi.openxml4j.opc.PackagePart; - -import junit.framework.TestCase; public class TestXWPFDocument extends TestCase { private File sampleFile; @@ -47,7 +47,7 @@ public class TestXWPFDocument extends TestCase { } public void testContainsMainContentType() throws Exception { - Package pack = POIXMLDocument.openPackage(sampleFile.toString()); + OPCPackage pack = POIXMLDocument.openPackage(sampleFile.toString()); boolean found = false; for(PackagePart part : pack.getParts()) { |