]> source.dussan.org Git - poi.git/commitdiff
Changed CRLF to LF in ooxml/java. Minor fixes for compiler warnings and formatting
authorJosh Micich <josh@apache.org>
Wed, 20 May 2009 08:02:35 +0000 (08:02 +0000)
committerJosh Micich <josh@apache.org>
Wed, 20 May 2009 08:02:35 +0000 (08:02 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@776607 13f79535-47bb-0310-9956-ffa450edef68

56 files changed:
src/ooxml/java/org/apache/poi/POIXMLException.java
src/ooxml/java/org/apache/poi/POIXMLFactory.java
src/ooxml/java/org/apache/poi/POIXMLRelation.java
src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java
src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidOperationException.java
src/ooxml/java/org/apache/poi/openxml4j/exceptions/OpenXML4JException.java
src/ooxml/java/org/apache/poi/openxml4j/exceptions/OpenXML4JRuntimeException.java
src/ooxml/java/org/apache/poi/openxml4j/opc/CertificateEmbeddingOption.java
src/ooxml/java/org/apache/poi/openxml4j/opc/CompressionOption.java
src/ooxml/java/org/apache/poi/openxml4j/opc/Configuration.java
src/ooxml/java/org/apache/poi/openxml4j/opc/ContentTypes.java
src/ooxml/java/org/apache/poi/openxml4j/opc/EncryptionOption.java
src/ooxml/java/org/apache/poi/openxml4j/opc/PackageAccess.java
src/ooxml/java/org/apache/poi/openxml4j/opc/PackageNamespaces.java
src/ooxml/java/org/apache/poi/openxml4j/opc/PackagePartCollection.java
src/ooxml/java/org/apache/poi/openxml4j/opc/PackagePartName.java
src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationshipTypes.java
src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java
src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java
src/ooxml/java/org/apache/poi/openxml4j/opc/TargetMode.java
src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/FileHelper.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PartMarshaller.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PartUnmarshaller.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ZipHelper.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/DefaultMarshaller.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/PackagePropertiesMarshaller.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPackagePropertiesMarshaller.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/signature/DigitalCertificatePart.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/signature/DigitalSignatureOriginPart.java
src/ooxml/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/PackagePropertiesUnmarshaller.java
src/ooxml/java/org/apache/poi/openxml4j/opc/signature/PackageDigitalSignature.java
src/ooxml/java/org/apache/poi/openxml4j/opc/signature/PackageDigitalSignatureManager.java
src/ooxml/java/org/apache/poi/openxml4j/util/Nullable.java
src/ooxml/java/org/apache/poi/xssf/dev/XSSFDump.java
src/ooxml/java/org/apache/poi/xssf/dev/XSSFSave.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFAnchor.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChildAnchor.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFClientAnchor.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConnector.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDrawing.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationWorkbook.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFactory.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPicture.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFShape.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFShapeGroup.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSimpleShape.java
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTextBox.java
src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFRowShifter.java
src/ooxml/java/org/apache/poi/xwpf/usermodel/Borders.java
src/ooxml/java/org/apache/poi/xwpf/usermodel/ParagraphAlignment.java
src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFactory.java
src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRelation.java

index 1a4bf7ff1dcaaa9cc4d64e16e551dd15a4a9452b..0c5ad44a51c33aa97e40404e453ec49d69da79a2 100755 (executable)
@@ -1,69 +1,69 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi;\r
-\r
-/**\r
- * Indicates a generic OOXML error.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class POIXMLException extends RuntimeException{\r
-    /**\r
-     * Create a new <code>POIXMLException</code> with no\r
-     * detail mesage.\r
-     */\r
-    public POIXMLException() {\r
-           super();\r
-    }\r
-\r
-    /**\r
-     * Create a new <code>POIXMLException</code> with\r
-     * the <code>String</code> specified as an error message.\r
-     *\r
-     * @param msg The error message for the exception.\r
-     */\r
-   public POIXMLException(String msg) {\r
-           super(msg);\r
-    }\r
-\r
-    /**\r
-     * Create a new <code>POIXMLException</code> with\r
-     * the <code>String</code> specified as an error message and the cause.\r
-     *\r
-     * @param msg The error message for the exception.\r
-     * @param  cause the cause (which is saved for later retrieval by the\r
-     *         {@link #getCause()} method).  (A <tt>null</tt> value is\r
-     *         permitted, and indicates that the cause is nonexistent or\r
-     *         unknown.)\r
-     */\r
-    public POIXMLException(String msg, Throwable cause) {\r
-        super(msg, cause);\r
-    }\r
-\r
-    /**\r
-     * Create a new <code>POIXMLException</code> with\r
-     * the specified cause.\r
-     *\r
-     * @param  cause the cause (which is saved for later retrieval by the\r
-     *         {@link #getCause()} method).  (A <tt>null</tt> value is\r
-     *         permitted, and indicates that the cause is nonexistent or\r
-     *         unknown.)\r
-     */\r
-     public POIXMLException(Throwable cause) {\r
-        super(cause);\r
-    }\r
-}\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;
+
+/**
+ * Indicates a generic OOXML error.
+ *
+ * @author Yegor Kozlov
+ */
+public final class POIXMLException extends RuntimeException{
+    /**
+     * Create a new <code>POIXMLException</code> with no
+     * detail mesage.
+     */
+    public POIXMLException() {
+        super();
+    }
+
+    /**
+     * Create a new <code>POIXMLException</code> with
+     * the <code>String</code> specified as an error message.
+     *
+     * @param msg The error message for the exception.
+     */
+   public POIXMLException(String msg) {
+        super(msg);
+    }
+
+    /**
+     * Create a new <code>POIXMLException</code> with
+     * the <code>String</code> specified as an error message and the cause.
+     *
+     * @param msg The error message for the exception.
+     * @param  cause the cause (which is saved for later retrieval by the
+     *         {@link #getCause()} method).  (A <tt>null</tt> value is
+     *         permitted, and indicates that the cause is nonexistent or
+     *         unknown.)
+     */
+    public POIXMLException(String msg, Throwable cause) {
+        super(msg, cause);
+    }
+
+    /**
+     * Create a new <code>POIXMLException</code> with
+     * the specified cause.
+     *
+     * @param  cause the cause (which is saved for later retrieval by the
+     *         {@link #getCause()} method).  (A <tt>null</tt> value is
+     *         permitted, and indicates that the cause is nonexistent or
+     *         unknown.)
+     */
+     public POIXMLException(Throwable cause) {
+        super(cause);
+    }
+}
index f10cf0ca01f1da83422a81cec7039bf070c738e6..d8b311190893c1d2f3b0adc36b3b829ca299b257 100755 (executable)
@@ -1,48 +1,47 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi;\r
-\r
-import org.apache.poi.openxml4j.opc.PackageRelationship;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-\r
-\r
-/**\r
- * Defines a factory API that enables sub-classes to create instances of <code>POIXMLDocumentPart</code>\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public abstract class POIXMLFactory {\r
-\r
-    /**\r
-     * Create a POIXMLDocumentPart from existing package part and relation. This method is called\r
-     * from {@link POIXMLDocumentPart#read(POIXMLFactory)} when parsing a document\r
-     *\r
-     * @param rel   the package part relationship\r
-     * @param part  the PackagePart representing the created instance\r
-     * @return A new instance of a POIXMLDocumentPart.\r
-     */\r
-     public abstract POIXMLDocumentPart createDocumentPart(PackageRelationship rel, PackagePart part);\r
-\r
-    /**\r
-     * Create a new POIXMLDocumentPart using the supplied descriptor. This method is used when adding new parts\r
-     * to a document, for example, when adding a sheet to a workbook, slide to a presentation, etc.\r
-     *\r
-     * @param descriptor  describes the object to create\r
-     * @return A new instance of a POIXMLDocumentPart.\r
-     */\r
-     public abstract POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor);\r
-}\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;
+
+import org.apache.poi.openxml4j.opc.PackageRelationship;
+import org.apache.poi.openxml4j.opc.PackagePart;
+
+/**
+ * Defines a factory API that enables sub-classes to create instances of <code>POIXMLDocumentPart</code>
+ *
+ * @author Yegor Kozlov
+ */
+public abstract class POIXMLFactory {
+
+    /**
+     * Create a POIXMLDocumentPart from existing package part and relation. This method is called
+     * from {@link POIXMLDocumentPart#read(POIXMLFactory)} when parsing a document
+     *
+     * @param rel   the package part relationship
+     * @param part  the PackagePart representing the created instance
+     * @return A new instance of a POIXMLDocumentPart.
+     */
+     public abstract POIXMLDocumentPart createDocumentPart(PackageRelationship rel, PackagePart part);
+
+    /**
+     * Create a new POIXMLDocumentPart using the supplied descriptor. This method is used when adding new parts
+     * to a document, for example, when adding a sheet to a workbook, slide to a presentation, etc.
+     *
+     * @param descriptor  describes the object to create
+     * @return A new instance of a POIXMLDocumentPart.
+     */
+     public abstract POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor);
+}
index a11c49ca18c92b7dfa54f049e9afc0b457b32396..e89090960ca69d4865a6459203f8046d0013d76c 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi;\r
-\r
-/**\r
- * Represents a descriptor of a OOXML relation.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public abstract class POIXMLRelation {\r
-\r
-    /**\r
-     * Describes the content stored in a part.\r
-     */\r
-    protected String _type;\r
-\r
-    /**\r
-     * The kind of connection between a source part and a target part in a package.\r
-     */\r
-    protected String _relation;\r
-\r
-    /**\r
-     * The path component of a pack URI.\r
-     */\r
-    protected String _defaultName;\r
-\r
-    /**\r
-     * Defines what object is used to construct instances of this relationship\r
-     */\r
-    private Class<? extends POIXMLDocumentPart> _cls;\r
-\r
-    /**\r
-     * Instantiates a POIXMLRelation.\r
-     *\r
-     * @param type content type\r
-     * @param rel  relationship\r
-     * @param defaultName default item name\r
-     * @param cls defines what object is used to construct instances of this relationship\r
-     */\r
-    public POIXMLRelation(String type, String rel, String defaultName, Class<? extends POIXMLDocumentPart> cls) {\r
-        _type = type;\r
-        _relation = rel;\r
-        _defaultName = defaultName;\r
-        _cls = cls;\r
-    }\r
-\r
-    /**\r
-     * Instantiates a POIXMLRelation.\r
-     *\r
-     * @param type content type\r
-     * @param rel  relationship\r
-     * @param defaultName default item name\r
-     */\r
-    public POIXMLRelation(String type, String rel, String defaultName) {\r
-        this(type, rel, defaultName, null);\r
-    }\r
-    /**\r
-     * Return the content type. Content types define a media type, a subtype, and an\r
-     * optional set of parameters, as defined in RFC 2616.\r
-     *\r
-     * @return the content type\r
-     */\r
-    public String getContentType() {\r
-        return _type;\r
-    }\r
-\r
-    /**\r
-     * Return the relationship, the kind of connection between a source part and a target part in a package.\r
-     * Relationships make the connections between parts directly discoverable without looking at the content\r
-     * in the parts, and without altering the parts themselves.\r
-     *\r
-     * @return the relationship\r
-     */\r
-    public String getRelation() {\r
-        return _relation;\r
-    }\r
-\r
-    /**\r
-     * Return the default part name. Part names are used to refer to a part in the context of a\r
-     * package, typically as part of a URI.\r
-     *\r
-     * @return the default part name\r
-     */\r
-    public String getDefaultFileName() {\r
-        return _defaultName;\r
-    }\r
-\r
-    /**\r
-     * Returns the filename for the nth one of these,\r
-     *  eg /xl/comments4.xml\r
-     */\r
-    public String getFileName(int index) {\r
-        if(_defaultName.indexOf("#") == -1) {\r
-            // Generic filename in all cases\r
-            return getDefaultFileName();\r
-        }\r
-        return _defaultName.replace("#", Integer.toString(index));\r
-    }\r
-\r
-    /**\r
-     * Return type of the obejct used to construct instances of this relationship\r
-     *\r
-     * @return the class of the object used to construct instances of this relation\r
-     */\r
-    public Class<? extends POIXMLDocumentPart> getRelationClass(){\r
-        return _cls;\r
-    }\r
-}\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;
+
+/**
+ * Represents a descriptor of a OOXML relation.
+ *
+ * @author Yegor Kozlov
+ */
+public abstract class POIXMLRelation {
+
+    /**
+     * Describes the content stored in a part.
+     */
+    protected String _type;
+
+    /**
+     * The kind of connection between a source part and a target part in a package.
+     */
+    protected String _relation;
+
+    /**
+     * The path component of a pack URI.
+     */
+    protected String _defaultName;
+
+    /**
+     * Defines what object is used to construct instances of this relationship
+     */
+    private Class<? extends POIXMLDocumentPart> _cls;
+
+    /**
+     * Instantiates a POIXMLRelation.
+     *
+     * @param type content type
+     * @param rel  relationship
+     * @param defaultName default item name
+     * @param cls defines what object is used to construct instances of this relationship
+     */
+    public POIXMLRelation(String type, String rel, String defaultName, Class<? extends POIXMLDocumentPart> cls) {
+        _type = type;
+        _relation = rel;
+        _defaultName = defaultName;
+        _cls = cls;
+    }
+
+    /**
+     * Instantiates a POIXMLRelation.
+     *
+     * @param type content type
+     * @param rel  relationship
+     * @param defaultName default item name
+     */
+    public POIXMLRelation(String type, String rel, String defaultName) {
+        this(type, rel, defaultName, null);
+    }
+    /**
+     * Return the content type. Content types define a media type, a subtype, and an
+     * optional set of parameters, as defined in RFC 2616.
+     *
+     * @return the content type
+     */
+    public String getContentType() {
+        return _type;
+    }
+
+    /**
+     * Return the relationship, the kind of connection between a source part and a target part in a package.
+     * Relationships make the connections between parts directly discoverable without looking at the content
+     * in the parts, and without altering the parts themselves.
+     *
+     * @return the relationship
+     */
+    public String getRelation() {
+        return _relation;
+    }
+
+    /**
+     * Return the default part name. Part names are used to refer to a part in the context of a
+     * package, typically as part of a URI.
+     *
+     * @return the default part name
+     */
+    public String getDefaultFileName() {
+        return _defaultName;
+    }
+
+    /**
+     * Returns the filename for the nth one of these,
+     *  e.g. /xl/comments4.xml
+     */
+    public String getFileName(int index) {
+        if(_defaultName.indexOf("#") == -1) {
+            // Generic filename in all cases
+            return getDefaultFileName();
+        }
+        return _defaultName.replace("#", Integer.toString(index));
+    }
+
+    /**
+     * Return type of the obejct used to construct instances of this relationship
+     *
+     * @return the class of the object used to construct instances of this relation
+     */
+    public Class<? extends POIXMLDocumentPart> getRelationClass(){
+        return _cls;
+    }
+}
index 689f8f33db6908cf87e7aebedbcd5878e2a6565b..13ed195c223c4ecf8b0d004217662a74782f1014 100755 (executable)
@@ -1,27 +1,26 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== \r
- */\r
-\r
-package org.apache.poi.openxml4j.exceptions;\r
-\r
-@SuppressWarnings("serial")\r
-public class InvalidFormatException extends OpenXML4JException{\r
-\r
-       public InvalidFormatException(String message){\r
-               super(message);\r
-       }\r
-}\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.openxml4j.exceptions;
+
+@SuppressWarnings("serial")
+public final class InvalidFormatException extends OpenXML4JException{
+
+       public InvalidFormatException(String message){
+               super(message);
+       }
+}
index 9e45ccf4b3e6193cdf8efdda6f701a0dca26152d..814edd1179979121b1cefdf079b929067c93557a 100755 (executable)
@@ -1,32 +1,32 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.exceptions;\r
-\r
-/**\r
- * Throw when an invalid operation is done.\r
- * \r
- * @author Julien Chable\r
- * @version 1.0\r
- */\r
-@SuppressWarnings("serial")\r
-public class InvalidOperationException extends OpenXML4JRuntimeException{\r
-\r
-       public InvalidOperationException(String message){\r
-               super(message);\r
-       }\r
-}\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.openxml4j.exceptions;
+
+/**
+ * Throw when an invalid operation is done.
+ *
+ * @author Julien Chable
+ * @version 1.0
+ */
+@SuppressWarnings("serial")
+public final class InvalidOperationException extends OpenXML4JRuntimeException{
+
+       public InvalidOperationException(String message){
+               super(message);
+       }
+}
index d2fa0e1446ad6e612ababa2b82f29cd66b6a3228..09979d96de171a874e8a8466fb6904b01bb6ca51 100755 (executable)
@@ -1,34 +1,34 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.exceptions;\r
-\r
-/**\r
- * Global exception throws when a critical error occurs. (this exception is not\r
- * set as Runtime in order to force user to manage the exception in a\r
- * try/catch).\r
- * \r
- * @author CDubettier, Julien Chable\r
- * @version 1.0\r
- */\r
-@SuppressWarnings("serial")\r
-public class OpenXML4JException extends Exception {\r
-\r
-       public OpenXML4JException(String msg) {\r
-               super(msg);\r
-       }\r
-}\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.openxml4j.exceptions;
+
+/**
+ * Global exception throws when a critical error occurs. (this exception is not
+ * set as Runtime in order to force user to manage the exception in a
+ * try/catch).
+ *
+ * @author CDubettier, Julien Chable
+ * @version 1.0
+ */
+@SuppressWarnings("serial")
+public class OpenXML4JException extends Exception {
+
+       public OpenXML4JException(String msg) {
+               super(msg);
+       }
+}
index c68d85ecbb43dfcafeb5a1e29c5f1660929b9628..7e95153fa67083aacc6ded3883039ca3e97a72a0 100755 (executable)
@@ -1,34 +1,34 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.exceptions;\r
-\r
-/**\r
- * Global exception throws when a critical error occurs (this exception is\r
- * set as Runtime in order not to force the user to manage the exception in a\r
- * try/catch).\r
- * \r
- * @author Julien Chable\r
- * @version 1.0\r
- */\r
-@SuppressWarnings("serial")\r
-public class OpenXML4JRuntimeException extends RuntimeException {\r
-\r
-       public OpenXML4JRuntimeException(String msg) {\r
-               super(msg);\r
-       }\r
-}\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.openxml4j.exceptions;
+
+/**
+ * Global exception throws when a critical error occurs (this exception is
+ * set as Runtime in order not to force the user to manage the exception in a
+ * try/catch).
+ *
+ * @author Julien Chable
+ * @version 1.0
+ */
+@SuppressWarnings("serial")
+public class OpenXML4JRuntimeException extends RuntimeException {
+
+       public OpenXML4JRuntimeException(String msg) {
+               super(msg);
+       }
+}
index 8b946e6d080a8046e55f56e9067072c17115209a..cd7b456941963841a3ab365065c01dd5ef75c2db 100755 (executable)
@@ -1,33 +1,32 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-/**\r
- * Specifies the location where the X.509 certificate that is used in signing is stored.\r
- * \r
- * @author Julien Chable\r
- * @version 1.0\r
- */\r
-public enum CertificateEmbeddingOption {\r
-       /** The certificate is embedded in its own PackagePart. */\r
-       IN_CERTIFICATE_PART,\r
-       /** The certificate is embedded in the SignaturePart that is created for the signature being added. */\r
-       IN_SIGNATURE_PART,\r
-       /** The certificate in not embedded in the package. */\r
-       NOT_EMBEDDED\r
-}\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.openxml4j.opc;
+
+/**
+ * Specifies the location where the X.509 certificate that is used in signing is stored.
+ *
+ * @author Julien Chable
+ */
+public enum CertificateEmbeddingOption {
+       /** The certificate is embedded in its own PackagePart. */
+       IN_CERTIFICATE_PART,
+       /** The certificate is embedded in the SignaturePart that is created for the signature being added. */
+       IN_SIGNATURE_PART,
+       /** The certificate in not embedded in the package. */
+       NOT_EMBEDDED
+}
index b6c5b30f7dfd2f1fc27006c661c678c93cf44815..583b5c51de442ed368ae64b45a4597c433b01d17 100755 (executable)
@@ -1,47 +1,47 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-import java.util.zip.Deflater;\r
-\r
-/**\r
- * Specifies the compression level for content that is stored in a PackagePart.\r
- * \r
- * @author Julien Chable\r
- * @version 1.0\r
- */\r
-public enum CompressionOption {\r
-       /** Compression is optimized for performance. */\r
-       FAST(Deflater.BEST_SPEED),\r
-       /** Compression is optimized for size. */\r
-       MAXIMUM(Deflater.BEST_COMPRESSION),\r
-       /** Compression is optimized for a balance between size and performance. */\r
-       NORMAL(Deflater.DEFAULT_COMPRESSION),\r
-       /** Compression is turned off. */\r
-       NOT_COMPRESSED(Deflater.NO_COMPRESSION);\r
-\r
-       private final int value;\r
-\r
-       CompressionOption(int value) {\r
-               this.value = value;\r
-       }\r
-\r
-       public int value() {\r
-               return this.value;\r
-       }\r
-}\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.openxml4j.opc;
+
+import java.util.zip.Deflater;
+
+/**
+ * Specifies the compression level for content that is stored in a PackagePart.
+ *
+ * @author Julien Chable
+ * @version 1.0
+ */
+public enum CompressionOption {
+       /** Compression is optimized for performance. */
+       FAST(Deflater.BEST_SPEED),
+       /** Compression is optimized for size. */
+       MAXIMUM(Deflater.BEST_COMPRESSION),
+       /** Compression is optimized for a balance between size and performance. */
+       NORMAL(Deflater.DEFAULT_COMPRESSION),
+       /** Compression is turned off. */
+       NOT_COMPRESSED(Deflater.NO_COMPRESSION);
+
+       private final int value;
+
+       CompressionOption(int value) {
+               this.value = value;
+       }
+
+       public int value() {
+               return this.value;
+       }
+}
index 72241b38d9bfa290ae4931bf173c109c01d45a5a..40141befc889ad0f1f4e4d982c74e82e5b14efc1 100755 (executable)
@@ -1,43 +1,43 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-import java.io.File;\r
-\r
-/**\r
- * Storage class for configuration storage parameters.\r
- * TODO xml syntax checking is no longer done with DOM4j parser -> remove the schema or do it ?\r
- * \r
- * @author CDubettier, Julen Chable\r
- * @version 1.0\r
- */\r
-public class Configuration {\r
-       // TODO configuration by default. should be clearly stated that it should be\r
-       // changed to match installation path\r
-       // as schemas dir is needed in runtime\r
-       static private String pathForXmlSchema = System.getProperty("user.dir")\r
-                       + File.separator + "src" + File.separator + "schemas";\r
-\r
-       public static String getPathForXmlSchema() {\r
-               return pathForXmlSchema;\r
-       }\r
-\r
-       public static void setPathForXmlSchema(String pathForXmlSchema) {\r
-               Configuration.pathForXmlSchema = pathForXmlSchema;\r
-       }\r
-}\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.openxml4j.opc;
+
+import java.io.File;
+
+/**
+ * Storage class for configuration storage parameters.
+ * TODO xml syntax checking is no longer done with DOM4j parser -> remove the schema or do it ?
+ *
+ * @author CDubettier, Julen Chable
+ * @version 1.0
+ */
+public final class Configuration {
+       // TODO configuration by default. should be clearly stated that it should be
+       // changed to match installation path
+       // as schemas dir is needed in runtime
+       static private String pathForXmlSchema = System.getProperty("user.dir")
+                       + File.separator + "src" + File.separator + "schemas";
+
+       public static String getPathForXmlSchema() {
+               return pathForXmlSchema;
+       }
+
+       public static void setPathForXmlSchema(String pathForXmlSchema) {
+               Configuration.pathForXmlSchema = pathForXmlSchema;
+       }
+}
index 9671d3a67a8996afdddd46377088ad5e03282abd..3754ce8a9a4561979d8e7fa5ac13e26466c3affe 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-/**\r
- * Open Packaging Convention content types (see Annex F : Standard Namespaces\r
- * and Content Types).\r
- * \r
- * @author CDubettier define some constants, Julien Chable\r
- * @version 0.1\r
- */\r
-public class ContentTypes {\r
-\r
-       /*\r
-        * Open Packaging Convention (Annex F : Standard Namespaces and Content\r
-        * Types)\r
-        */\r
-\r
-       /**\r
-        * Core Properties part.\r
-        */\r
-       public static final String CORE_PROPERTIES_PART = "application/vnd.openxmlformats-package.core-properties+xml";\r
-\r
-       /**\r
-        * Digital Signature Certificate part.\r
-        */\r
-       public static final String DIGITAL_SIGNATURE_CERTIFICATE_PART = "application/vnd.openxmlformats-package.digital-signature-certificate";\r
-\r
-       /**\r
-        * Digital Signature Origin part.\r
-        */\r
-       public static final String DIGITAL_SIGNATURE_ORIGIN_PART = "application/vnd.openxmlformats-package.digital-signature-origin";\r
-\r
-       /**\r
-        * Digital Signature XML Signature part.\r
-        */\r
-       public static final String DIGITAL_SIGNATURE_XML_SIGNATURE_PART = "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml";\r
-\r
-       /**\r
-        * Relationships part.\r
-        */\r
-       public static final String RELATIONSHIPS_PART = "application/vnd.openxmlformats-package.relationships+xml";\r
-\r
-       /**\r
-        * Custom XML part.\r
-        */\r
-       public static final String CUSTOM_XML_PART = "application/vnd.openxmlformats-officedocument.customXmlProperties+xml";\r
-\r
-       /**\r
-        * Plain old xml. Note - OOXML uses application/xml, and not text/xml!\r
-        */\r
-       public static final String PLAIN_OLD_XML = "application/xml";\r
-\r
-       public static final String IMAGE_JPEG = "image/jpeg";\r
-\r
-       public static final String EXTENSION_JPG_1 = "jpg";\r
-\r
-       public static final String EXTENSION_JPG_2 = "jpeg";\r
-\r
-       // image/png ISO/IEC 15948:2003 http://www.libpng.org/pub/png/spec/\r
-       public static final String IMAGE_PNG = "image/png";\r
-\r
-       public static final String EXTENSION_PNG = "png";\r
-\r
-       // image/gif http://www.w3.org/Graphics/GIF/spec-gif89a.txt\r
-       public static final String IMAGE_GIF = "image/gif";\r
-\r
-       public static final String EXTENSION_GIF = "gif";\r
-\r
-       /**\r
-        * TIFF image format.\r
-        * \r
-        * @see <a href="http://partners.adobe.com/public/developer/tiff/index.html#spec">\r
-     * http://partners.adobe.com/public/developer/tiff/index.html#spec</a>\r
-        */\r
-       public static final String IMAGE_TIFF = "image/tiff";\r
-\r
-       public static final String EXTENSION_TIFF = "tiff";\r
-\r
-       /**\r
-        * Pict image format.\r
-        * \r
-        * @see <a href="http://developer.apple.com/documentation/mac/QuickDraw/QuickDraw-2.html">\r
-     * http://developer.apple.com/documentation/mac/QuickDraw/QuickDraw-2.html</a>\r
-        */\r
-       public static final String IMAGE_PICT = "image/pict";\r
-\r
-       public static final String EXTENSION_PICT = "tiff";\r
-\r
-       /**\r
-        * XML file.\r
-        */\r
-       public static final String XML = "text/xml";\r
-\r
-       public static final String EXTENSION_XML = "xml";\r
-\r
-       public static String getContentTypeFromFileExtension(String filename) {\r
-               String extension = filename.substring(filename.lastIndexOf(".") + 1)\r
-                               .toLowerCase();\r
-               if (extension.equals(EXTENSION_JPG_1)\r
-                               || extension.equals(EXTENSION_JPG_2))\r
-                       return IMAGE_JPEG;\r
-               else if (extension.equals(EXTENSION_GIF))\r
-                       return IMAGE_GIF;\r
-               else if (extension.equals(EXTENSION_PICT))\r
-                       return IMAGE_PICT;\r
-               else if (extension.equals(EXTENSION_PNG))\r
-                       return IMAGE_PNG;\r
-               else if (extension.equals(EXTENSION_TIFF))\r
-                       return IMAGE_TIFF;\r
-               else if (extension.equals(EXTENSION_XML))\r
-                       return XML;\r
-               else\r
-                       return null;\r
-       }\r
-}\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.openxml4j.opc;
+
+/**
+ * Open Packaging Convention content types (see Annex F : Standard Namespaces
+ * and Content Types).
+ *
+ * @author CDubettier define some constants, Julien Chable
+ */
+public final class ContentTypes {
+
+       /*
+        * Open Packaging Convention (Annex F : Standard Namespaces and Content
+        * Types)
+        */
+
+       /**
+        * Core Properties part.
+        */
+       public static final String CORE_PROPERTIES_PART = "application/vnd.openxmlformats-package.core-properties+xml";
+
+       /**
+        * Digital Signature Certificate part.
+        */
+       public static final String DIGITAL_SIGNATURE_CERTIFICATE_PART = "application/vnd.openxmlformats-package.digital-signature-certificate";
+
+       /**
+        * Digital Signature Origin part.
+        */
+       public static final String DIGITAL_SIGNATURE_ORIGIN_PART = "application/vnd.openxmlformats-package.digital-signature-origin";
+
+       /**
+        * Digital Signature XML Signature part.
+        */
+       public static final String DIGITAL_SIGNATURE_XML_SIGNATURE_PART = "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml";
+
+       /**
+        * Relationships part.
+        */
+       public static final String RELATIONSHIPS_PART = "application/vnd.openxmlformats-package.relationships+xml";
+
+       /**
+        * Custom XML part.
+        */
+       public static final String CUSTOM_XML_PART = "application/vnd.openxmlformats-officedocument.customXmlProperties+xml";
+
+       /**
+        * Plain old xml. Note - OOXML uses application/xml, and not text/xml!
+        */
+       public static final String PLAIN_OLD_XML = "application/xml";
+
+       public static final String IMAGE_JPEG = "image/jpeg";
+
+       public static final String EXTENSION_JPG_1 = "jpg";
+
+       public static final String EXTENSION_JPG_2 = "jpeg";
+
+       // image/png ISO/IEC 15948:2003 http://www.libpng.org/pub/png/spec/
+       public static final String IMAGE_PNG = "image/png";
+
+       public static final String EXTENSION_PNG = "png";
+
+       // image/gif http://www.w3.org/Graphics/GIF/spec-gif89a.txt
+       public static final String IMAGE_GIF = "image/gif";
+
+       public static final String EXTENSION_GIF = "gif";
+
+       /**
+        * TIFF image format.
+        *
+        * @see <a href="http://partners.adobe.com/public/developer/tiff/index.html#spec">
+        * http://partners.adobe.com/public/developer/tiff/index.html#spec</a>
+        */
+       public static final String IMAGE_TIFF = "image/tiff";
+
+       public static final String EXTENSION_TIFF = "tiff";
+
+       /**
+        * Pict image format.
+        *
+        * @see <a href="http://developer.apple.com/documentation/mac/QuickDraw/QuickDraw-2.html">
+        * http://developer.apple.com/documentation/mac/QuickDraw/QuickDraw-2.html</a>
+        */
+       public static final String IMAGE_PICT = "image/pict";
+
+       public static final String EXTENSION_PICT = "tiff";
+
+       /**
+        * XML file.
+        */
+       public static final String XML = "text/xml";
+
+       public static final String EXTENSION_XML = "xml";
+
+       public static String getContentTypeFromFileExtension(String filename) {
+               String extension = filename.substring(filename.lastIndexOf(".") + 1)
+                               .toLowerCase();
+               if (extension.equals(EXTENSION_JPG_1)
+                               || extension.equals(EXTENSION_JPG_2))
+                       return IMAGE_JPEG;
+               else if (extension.equals(EXTENSION_GIF))
+                       return IMAGE_GIF;
+               else if (extension.equals(EXTENSION_PICT))
+                       return IMAGE_PICT;
+               else if (extension.equals(EXTENSION_PNG))
+                       return IMAGE_PNG;
+               else if (extension.equals(EXTENSION_TIFF))
+                       return IMAGE_TIFF;
+               else if (extension.equals(EXTENSION_XML))
+                       return XML;
+               else
+                       return null;
+       }
+}
index 0e15332f32a7dbabe8fe1c6fb99f7baa3a366ebd..bc994e0f1ceedab12f11c28a044171d38c123717 100755 (executable)
@@ -1,29 +1,29 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-/**\r
- * Specifies the encryption option for parts in a Package.\r
- * \r
- * @author Julien Chable\r
- * @version 0.1\r
- */\r
-public enum EncryptionOption {\r
-    /** No encryption. */\r
-    NONE\r
-}\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.openxml4j.opc;
+
+/**
+ * Specifies the encryption option for parts in a Package.
+ *
+ * @author Julien Chable
+ * @version 0.1
+ */
+public enum EncryptionOption {
+    /** No encryption. */
+    NONE
+}
index a40f4ac43670dcb15fc73486f92aaaa9140ccf16..25688222857faa5ff8d4a4ad1962555807590fd6 100755 (executable)
@@ -1,33 +1,33 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-/**\r
- * Specifies package access.\r
- * \r
- * @author Julien Chable\r
- * @version 1.0\r
- */\r
-public enum PackageAccess {\r
-    /** Read only. Write not authorized. */\r
-    READ,\r
-    /** Write only. Read not authorized. */\r
-    WRITE,\r
-    /** Read and Write mode. */\r
-    READ_WRITE\r
-}\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.openxml4j.opc;
+
+/**
+ * Specifies package access.
+ *
+ * @author Julien Chable
+ * @version 1.0
+ */
+public enum PackageAccess {
+    /** Read only. Write not authorized. */
+    READ,
+    /** Write only. Read not authorized. */
+    WRITE,
+    /** Read and Write mode. */
+    READ_WRITE
+}
index 5f53781eb8359252b06d477ebeff1e69effe3d42..d1adc519fcc55da56b77853326b41befe9df8463 100755 (executable)
@@ -1,52 +1,52 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-/**\r
- * Open Packaging Convention namespaces URI.\r
- * \r
- * @author Julien Chable\r
- * @version 1.0\r
- */\r
-public interface PackageNamespaces {\r
-\r
-       /**\r
-        * Content Types.\r
-        */\r
-       public static final String CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types";\r
-       \r
-       /**\r
-        * Core Properties.\r
-        */\r
-       public static final String CORE_PROPERTIES = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";\r
-       \r
-       /**\r
-        * Digital Signatures.\r
-        */\r
-       public static final String DIGITAL_SIGNATURE = "http://schemas.openxmlformats.org/package/2006/digital-signature";\r
-       \r
-       /**\r
-        * Relationships.\r
-        */\r
-       public static final String RELATIONSHIPS = "http://schemas.openxmlformats.org/package/2006/relationships";\r
-       \r
-       /**\r
-        * Markup Compatibility.\r
-        */\r
-       public static final String MARKUP_COMPATIBILITY = "http://schemas.openxmlformats.org/markup-compatibility/2006";\r
-}\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.openxml4j.opc;
+
+/**
+ * Open Packaging Convention namespaces URI.
+ *
+ * @author Julien Chable
+ * @version 1.0
+ */
+public interface PackageNamespaces {
+
+       /**
+        * Content Types.
+        */
+       public static final String CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
+
+       /**
+        * Core Properties.
+        */
+       public static final String CORE_PROPERTIES = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
+
+       /**
+        * Digital Signatures.
+        */
+       public static final String DIGITAL_SIGNATURE = "http://schemas.openxmlformats.org/package/2006/digital-signature";
+
+       /**
+        * Relationships.
+        */
+       public static final String RELATIONSHIPS = "http://schemas.openxmlformats.org/package/2006/relationships";
+
+       /**
+        * Markup Compatibility.
+        */
+       public static final String MARKUP_COMPATIBILITY = "http://schemas.openxmlformats.org/markup-compatibility/2006";
+}
index 54021302bf89fe6555086f1b5e7f88dd9eb9b7b9..e4ecbd44b8908a6cf2ea6e21b1f9753719670f49 100755 (executable)
@@ -1,81 +1,81 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-import java.util.ArrayList;\r
-import java.util.TreeMap;\r
-\r
-import org.apache.poi.openxml4j.exceptions.InvalidOperationException;\r
-\r
-/**\r
- * A package part collection.\r
- * \r
- * @author Julien Chable\r
- * @version 0.1\r
- */\r
-public final class PackagePartCollection extends\r
-               TreeMap<PackagePartName, PackagePart> {\r
-\r
-       private static final long serialVersionUID = 2515031135957635515L;\r
-\r
-       /**\r
-        * Arraylist use to store this collection part names as string for rule\r
-        * M1.11 optimized checking.\r
-        */\r
-       private ArrayList<String> registerPartNameStr = new ArrayList<String>();\r
-\r
-       @Override\r
-       public Object clone() {\r
-               return super.clone();\r
-       }\r
-\r
-       /**\r
-        * Check rule [M1.11]: a package implementer shall neither create nor\r
-        * recognize a part with a part name derived from another part name by\r
-        * appending segments to it.\r
-        * \r
-        * @exception InvalidOperationException\r
-        *                Throws if you try to add a part with a name derived from\r
-        *                another part name.\r
-        */\r
-       @Override\r
-       public PackagePart put(PackagePartName partName, PackagePart part) {\r
-               String[] segments = partName.getURI().toASCIIString().split(\r
-                               PackagingURIHelper.FORWARD_SLASH_STRING);\r
-               StringBuffer concatSeg = new StringBuffer();\r
-               for (String seg : segments) {\r
-                       if (!seg.equals(""))\r
-                               concatSeg.append(PackagingURIHelper.FORWARD_SLASH_CHAR);\r
-                       concatSeg.append(seg);\r
-                       if (this.registerPartNameStr.contains(concatSeg.toString())) {\r
-                               throw new InvalidOperationException(\r
-                                               "You can't add a part with a part name derived from another part ! [M1.11]");\r
-                       }\r
-               }\r
-               this.registerPartNameStr.add(partName.getName());\r
-               return super.put(partName, part);\r
-       }\r
-\r
-       @Override\r
-       public PackagePart remove(Object key) {\r
-               if (key instanceof PackagePartName) {\r
-                       this.registerPartNameStr.remove(((PackagePartName) key).getName());\r
-               }\r
-               return super.remove(key);\r
-       }\r
-}\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.openxml4j.opc;
+
+import java.util.ArrayList;
+import java.util.TreeMap;
+
+import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
+
+/**
+ * A package part collection.
+ *
+ * @author Julien Chable
+ * @version 0.1
+ */
+public final class PackagePartCollection extends
+               TreeMap<PackagePartName, PackagePart> {
+
+       private static final long serialVersionUID = 2515031135957635515L;
+
+       /**
+        * Arraylist use to store this collection part names as string for rule
+        * M1.11 optimized checking.
+        */
+       private ArrayList<String> registerPartNameStr = new ArrayList<String>();
+
+       @Override
+       public Object clone() {
+               return super.clone();
+       }
+
+       /**
+        * Check rule [M1.11]: a package implementer shall neither create nor
+        * recognize a part with a part name derived from another part name by
+        * appending segments to it.
+        *
+        * @exception InvalidOperationException
+        *                Throws if you try to add a part with a name derived from
+        *                another part name.
+        */
+       @Override
+       public PackagePart put(PackagePartName partName, PackagePart part) {
+               String[] segments = partName.getURI().toASCIIString().split(
+                               PackagingURIHelper.FORWARD_SLASH_STRING);
+               StringBuffer concatSeg = new StringBuffer();
+               for (String seg : segments) {
+                       if (!seg.equals(""))
+                               concatSeg.append(PackagingURIHelper.FORWARD_SLASH_CHAR);
+                       concatSeg.append(seg);
+                       if (this.registerPartNameStr.contains(concatSeg.toString())) {
+                               throw new InvalidOperationException(
+                                               "You can't add a part with a part name derived from another part ! [M1.11]");
+                       }
+               }
+               this.registerPartNameStr.add(partName.getName());
+               return super.put(partName, part);
+       }
+
+       @Override
+       public PackagePart remove(Object key) {
+               if (key instanceof PackagePartName) {
+                       this.registerPartNameStr.remove(((PackagePartName) key).getName());
+               }
+               return super.remove(key);
+       }
+}
index f1cc7fdaad953dbf7ee6823a5f08178292cca406..4b1a8448d9cecbc6e311a1c64b67a3f8d2b6b7a7 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-import java.net.URI;\r
-import java.net.URISyntaxException;\r
-\r
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException;\r
-\r
-/**\r
- * An immutable Open Packaging Convention compliant part name.\r
- * \r
- * @author Julien Chable\r
- * @version 0.1\r
- * \r
- * @see <a href="http://www.ietf.org/rfc/rfc3986.txt">http://www.ietf.org/rfc/rfc3986.txt</a>\r
- */\r
-public final class PackagePartName implements Comparable<PackagePartName> {\r
-\r
-       /**\r
-        * Part name stored as an URI.\r
-        */\r
-       private URI partNameURI;\r
-\r
-       /*\r
-        * URI Characters definition (RFC 3986)\r
-        */\r
-\r
-       /**\r
-        * Reserved characters for sub delimitations.\r
-        */\r
-       private static String[] RFC3986_PCHAR_SUB_DELIMS = { "!", "$", "&", "'",\r
-                       "(", ")", "*", "+", ",", ";", "=" };\r
-\r
-       /**\r
-        * Unreserved character (+ ALPHA & DIGIT).\r
-        */\r
-       private static String[] RFC3986_PCHAR_UNRESERVED_SUP = { "-", ".", "_", "~" };\r
-\r
-       /**\r
-        * Authorized reserved characters for pChar.\r
-        */\r
-       private static String[] RFC3986_PCHAR_AUTHORIZED_SUP = { ":", "@" };\r
-\r
-       /**\r
-        * Flag to know if this part name is from a relationship part name.\r
-        */\r
-       private boolean isRelationship;\r
-\r
-       /**\r
-        * Constructor. Makes a ValidPartName object from a java.net.URI\r
-        * \r
-        * @param uri\r
-        *            The URI to validate and to transform into ValidPartName.\r
-        * @param checkConformance\r
-        *            Flag to specify if the contructor have to validate the OPC\r
-        *            conformance. Must be always <code>true</code> except for\r
-        *            special URI like '/' which is needed for internal use by\r
-        *            OpenXML4J but is not valid.\r
-        * @throws InvalidFormatException\r
-        *             Throw if the specified part name is not conform to Open\r
-        *             Packaging Convention specifications.\r
-        * @see java.net.URI\r
-        */\r
-       PackagePartName(URI uri, boolean checkConformance)\r
-                       throws InvalidFormatException {\r
-               if (checkConformance) {\r
-                       throwExceptionIfInvalidPartUri(uri);\r
-               } else {\r
-                       if (!PackagingURIHelper.PACKAGE_ROOT_URI.equals(uri)) {\r
-                               throw new OpenXML4JRuntimeException(\r
-                                               "OCP conformance must be check for ALL part name except special cases : ['/']");\r
-                       }\r
-               }\r
-               this.partNameURI = uri;\r
-               this.isRelationship = isRelationshipPartURI(this.partNameURI);\r
-       }\r
-\r
-       /**\r
-        * Constructor. Makes a ValidPartName object from a String part name.\r
-        * \r
-        * @param partName\r
-        *            Part name to valid and to create.\r
-        * @param checkConformance\r
-        *            Flag to specify if the contructor have to validate the OPC\r
-        *            conformance. Must be always <code>true</code> except for\r
-        *            special URI like '/' which is needed for internal use by\r
-        *            OpenXML4J but is not valid.\r
-        * @throws InvalidFormatException\r
-        *             Throw if the specified part name is not conform to Open\r
-        *             Packaging Convention specifications.\r
-        */\r
-       PackagePartName(String partName, boolean checkConformance)\r
-                       throws InvalidFormatException {\r
-               URI partURI;\r
-               try {\r
-                       partURI = new URI(partName);\r
-               } catch (URISyntaxException e) {\r
-                       throw new IllegalArgumentException(\r
-                                       "partName argmument is not a valid OPC part name !");\r
-               }\r
-\r
-               if (checkConformance) {\r
-                       throwExceptionIfInvalidPartUri(partURI);\r
-               } else {\r
-                       if (!PackagingURIHelper.PACKAGE_ROOT_URI.equals(partURI)) {\r
-                               throw new OpenXML4JRuntimeException(\r
-                                               "OCP conformance must be check for ALL part name except special cases : ['/']");\r
-                       }\r
-               }\r
-               this.partNameURI = partURI;\r
-               this.isRelationship = isRelationshipPartURI(this.partNameURI);\r
-       }\r
-\r
-       /**\r
-        * Check if the specified part name is a relationship part name.\r
-        * \r
-        * @param partUri\r
-        *            The URI to check.\r
-        * @return <code>true</code> if this part name respect the relationship\r
-        *         part naming convention else <code>false</code>.\r
-        */\r
-       private boolean isRelationshipPartURI(URI partUri) {\r
-               if (partUri == null)\r
-                       throw new IllegalArgumentException("partUri");\r
-\r
-               return partUri.getPath().matches(\r
-                               "^.*/" + PackagingURIHelper.RELATIONSHIP_PART_SEGMENT_NAME + "/.*\\"\r
-                                               + PackagingURIHelper.RELATIONSHIP_PART_EXTENSION_NAME\r
-                                               + "$");\r
-       }\r
-\r
-       /**\r
-        * Know if this part name is a relationship part name.\r
-        * \r
-        * @return <code>true</code> if this part name respect the relationship\r
-        *         part naming convention else <code>false</code>.\r
-        */\r
-       public boolean isRelationshipPartURI() {\r
-               return this.isRelationship;\r
-       }\r
-\r
-       /**\r
-        * Throws an exception (of any kind) if the specified part name does not\r
-        * follow the Open Packaging Convention specifications naming rules.\r
-        * \r
-        * @param partUri\r
-        *            The part name to check.\r
-        * @throws Exception\r
-        *             Throws if the part name is invalid.\r
-        */\r
-       private static void throwExceptionIfInvalidPartUri(URI partUri)\r
-                       throws InvalidFormatException {\r
-               if (partUri == null)\r
-                       throw new IllegalArgumentException("partUri");\r
-               // Check if the part name URI is empty [M1.1]\r
-               throwExceptionIfEmptyURI(partUri);\r
-\r
-               // Check if the part name URI is absolute\r
-               throwExceptionIfAbsoluteUri(partUri);\r
-\r
-               // Check if the part name URI starts with a forward slash [M1.4]\r
-               throwExceptionIfPartNameNotStartsWithForwardSlashChar(partUri);\r
-\r
-               // Check if the part name URI ends with a forward slash [M1.5]\r
-               throwExceptionIfPartNameEndsWithForwardSlashChar(partUri);\r
-\r
-               // Check if the part name does not have empty segments. [M1.3]\r
-               // Check if a segment ends with a dot ('.') character. [M1.9]\r
-               throwExceptionIfPartNameHaveInvalidSegments(partUri);\r
-       }\r
-\r
-       /**\r
-        * Throws an exception if the specified URI is empty. [M1.1]\r
-        * \r
-        * @param partURI\r
-        *            Part URI to check.\r
-        * @throws InvalidFormatException\r
-        *             If the specified URI is empty.\r
-        */\r
-       private static void throwExceptionIfEmptyURI(URI partURI)\r
-                       throws InvalidFormatException {\r
-               if (partURI == null)\r
-                       throw new IllegalArgumentException("partURI");\r
-\r
-               String uriPath = partURI.getPath();\r
-               if (uriPath.length() == 0\r
-                               || ((uriPath.length() == 1) && (uriPath.charAt(0) == PackagingURIHelper.FORWARD_SLASH_CHAR)))\r
-                       throw new InvalidFormatException(\r
-                                       "A part name shall not be empty [M1.1]: "\r
-                                                       + partURI.getPath());\r
-       }\r
-\r
-       /**\r
-        * Throws an exception if the part name has empty segments. [M1.3]\r
-        * \r
-        * Throws an exception if a segment any characters other than pchar\r
-        * characters. [M1.6]\r
-        * \r
-        * Throws an exception if a segment contain percent-encoded forward slash\r
-        * ('/'), or backward slash ('\') characters. [M1.7]\r
-        * \r
-        * Throws an exception if a segment contain percent-encoded unreserved\r
-        * characters. [M1.8]\r
-        * \r
-        * Throws an exception if the specified part name's segments end with a dot\r
-        * ('.') character. [M1.9]\r
-        * \r
-        * Throws an exception if a segment doesn't include at least one non-dot\r
-        * character. [M1.10]\r
-        * \r
-        * @param partUri\r
-        *            The part name to check.\r
-        * @throws InvalidFormatException\r
-        *             if the specified URI contain an empty segments or if one the\r
-        *             segments contained in the part name, ends with a dot ('.')\r
-        *             character.\r
-        */\r
-       private static void throwExceptionIfPartNameHaveInvalidSegments(URI partUri)\r
-                       throws InvalidFormatException {\r
-               if (partUri == null || "".equals(partUri)) {\r
-                       throw new IllegalArgumentException("partUri");\r
-               }\r
-\r
-               // Split the URI into several part and analyze each\r
-               String[] segments = partUri.toASCIIString().split("/");\r
-               if (segments.length <= 1 || !segments[0].equals(""))\r
-                       throw new InvalidFormatException(\r
-                                       "A part name shall not have empty segments [M1.3]: "\r
-                                                       + partUri.getPath());\r
-\r
-               for (int i = 1; i < segments.length; ++i) {\r
-                       String seg = segments[i];\r
-                       if (seg == null || "".equals(seg)) {\r
-                               throw new InvalidFormatException(\r
-                                               "A part name shall not have empty segments [M1.3]: "\r
-                                                               + partUri.getPath());\r
-                       }\r
-\r
-                       if (seg.endsWith(".")) {\r
-                               throw new InvalidFormatException(\r
-                                               "A segment shall not end with a dot ('.') character [M1.9]: "\r
-                                                               + partUri.getPath());\r
-                       }\r
-\r
-                       if ("".equals(seg.replaceAll("\\\\.", ""))) {\r
-                               // Normally will never been invoked with the previous\r
-                               // implementation rule [M1.9]\r
-                               throw new InvalidFormatException(\r
-                                               "A segment shall include at least one non-dot character. [M1.10]: "\r
-                                                               + partUri.getPath());\r
-                       }\r
-\r
-                       /*\r
-                        * Check for rule M1.6, M1.7, M1.8\r
-                        */\r
-                       checkPCharCompliance(seg);\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Throws an exception if a segment any characters other than pchar\r
-        * characters. [M1.6]\r
-        * \r
-        * Throws an exception if a segment contain percent-encoded forward slash\r
-        * ('/'), or backward slash ('\') characters. [M1.7]\r
-        * \r
-        * Throws an exception if a segment contain percent-encoded unreserved\r
-        * characters. [M1.8]\r
-        * \r
-        * @param segment\r
-        *            The segment to check\r
-        */\r
-       private static void checkPCharCompliance(String segment)\r
-                       throws InvalidFormatException {\r
-               boolean errorFlag;\r
-               for (int i = 0; i < segment.length(); ++i) {\r
-                       char c = segment.charAt(i);\r
-                       errorFlag = true;\r
-\r
-                       /* Check rule M1.6 */\r
-\r
-                       // Check for digit or letter\r
-                       if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')\r
-                                       || (c >= '0' && c <= '9')) {\r
-                               errorFlag = false;\r
-                       } else {\r
-                               // Check "-", ".", "_", "~"\r
-                               for (int j = 0; j < RFC3986_PCHAR_UNRESERVED_SUP.length; ++j) {\r
-                                       if (c == RFC3986_PCHAR_UNRESERVED_SUP[j].charAt(0)) {\r
-                                               errorFlag = false;\r
-                                               break;\r
-                                       }\r
-                               }\r
-\r
-                               // Check ":", "@"\r
-                               for (int j = 0; errorFlag\r
-                                               && j < RFC3986_PCHAR_AUTHORIZED_SUP.length; ++j) {\r
-                                       if (c == RFC3986_PCHAR_AUTHORIZED_SUP[j].charAt(0)) {\r
-                                               errorFlag = false;\r
-                                       }\r
-                               }\r
-\r
-                               // Check "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="\r
-                               for (int j = 0; errorFlag\r
-                                               && j < RFC3986_PCHAR_SUB_DELIMS.length; ++j) {\r
-                                       if (c == RFC3986_PCHAR_SUB_DELIMS[j].charAt(0)) {\r
-                                               errorFlag = false;\r
-                                       }\r
-                               }\r
-                       }\r
-\r
-                       if (errorFlag && c == '%') {\r
-                               // We certainly found an encoded character, check for length\r
-                               // now ( '%' HEXDIGIT HEXDIGIT)\r
-                               if (((segment.length() - i) < 2)) {\r
-                                       throw new InvalidFormatException("The segment " + segment\r
-                                                       + " contain invalid encoded character !");\r
-                               }\r
-\r
-                               // If not percent encoded character error occur then reset the\r
-                               // flag -> the character is valid\r
-                               errorFlag = false;\r
-\r
-                               // Decode the encoded character\r
-                               char decodedChar = (char) Integer.parseInt(segment.substring(\r
-                                               i + 1, i + 3), 16);\r
-                               i += 2;\r
-\r
-                               /* Check rule M1.7 */\r
-                               if (decodedChar == '/' || decodedChar == '\\')\r
-                                       throw new InvalidFormatException(\r
-                                                       "A segment shall not contain percent-encoded forward slash ('/'), or backward slash ('\') characters. [M1.7]");\r
-\r
-                               /* Check rule M1.8 */\r
-\r
-                               // Check for unreserved character like define in RFC3986\r
-                               if ((decodedChar >= 'A' && decodedChar <= 'Z')\r
-                                               || (decodedChar >= 'a' && decodedChar <= 'z')\r
-                                               || (decodedChar >= '0' && decodedChar <= '9'))\r
-                                       errorFlag = true;\r
-\r
-                               // Check for unreserved character "-", ".", "_", "~"\r
-                               for (int j = 0; !errorFlag\r
-                                               && j < RFC3986_PCHAR_UNRESERVED_SUP.length; ++j) {\r
-                                       if (c == RFC3986_PCHAR_UNRESERVED_SUP[j].charAt(0)) {\r
-                                               errorFlag = true;\r
-                                               break;\r
-                                       }\r
-                               }\r
-                               if (errorFlag)\r
-                                       throw new InvalidFormatException(\r
-                                                       "A segment shall not contain percent-encoded unreserved characters. [M1.8]");\r
-                       }\r
-\r
-                       if (errorFlag)\r
-                               throw new InvalidFormatException(\r
-                                               "A segment shall not hold any characters other than pchar characters. [M1.6]");\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Throws an exception if the specified part name doesn't start with a\r
-        * forward slash character '/'. [M1.4]\r
-        * \r
-        * @param partUri\r
-        *            The part name to check.\r
-        * @throws InvalidFormatException\r
-        *             If the specified part name doesn't start with a forward slash\r
-        *             character '/'.\r
-        */\r
-       private static void throwExceptionIfPartNameNotStartsWithForwardSlashChar(\r
-                       URI partUri) throws InvalidFormatException {\r
-               String uriPath = partUri.getPath();\r
-               if (uriPath.length() > 0\r
-                               && uriPath.charAt(0) != PackagingURIHelper.FORWARD_SLASH_CHAR)\r
-                       throw new InvalidFormatException(\r
-                                       "A part name shall start with a forward slash ('/') character [M1.4]: "\r
-                                                       + partUri.getPath());\r
-       }\r
-\r
-       /**\r
-        * Throws an exception if the specified part name ends with a forwar slash\r
-        * character '/'. [M1.5]\r
-        * \r
-        * @param partUri\r
-        *            The part name to check.\r
-        * @throws InvalidFormatException\r
-        *             If the specified part name ends with a forwar slash character\r
-        *             '/'.\r
-        */\r
-       private static void throwExceptionIfPartNameEndsWithForwardSlashChar(\r
-                       URI partUri) throws InvalidFormatException {\r
-               String uriPath = partUri.getPath();\r
-               if (uriPath.length() > 0\r
-                               && uriPath.charAt(uriPath.length() - 1) == PackagingURIHelper.FORWARD_SLASH_CHAR)\r
-                       throw new InvalidFormatException(\r
-                                       "A part name shall not have a forward slash as the last character [M1.5]: "\r
-                                                       + partUri.getPath());\r
-       }\r
-\r
-       /**\r
-        * Throws an exception if the specified URI is absolute.\r
-        * \r
-        * @param partUri\r
-        *            The URI to check.\r
-        * @throws InvalidFormatException\r
-        *             Throws if the specified URI is absolute.\r
-        */\r
-       private static void throwExceptionIfAbsoluteUri(URI partUri)\r
-                       throws InvalidFormatException {\r
-               if (partUri.isAbsolute())\r
-                       throw new InvalidFormatException("Absolute URI forbidden: "\r
-                                       + partUri);\r
-       }\r
-\r
-       /**\r
-        * Compare two part name following the rule M1.12 :\r
-        * \r
-        * Part name equivalence is determined by comparing part names as\r
-        * case-insensitive ASCII strings. Packages shall not contain equivalent\r
-        * part names and package implementers shall neither create nor recognize\r
-        * packages with equivalent part names. [M1.12]\r
-        */\r
-       public int compareTo(PackagePartName otherPartName) {\r
-               if (otherPartName == null)\r
-                       return -1;\r
-               return this.partNameURI.toASCIIString().toLowerCase().compareTo(\r
-                               otherPartName.partNameURI.toASCIIString().toLowerCase());\r
-       }\r
-\r
-       /**\r
-        * Retrieves the extension of the part name if any. If there is no extension\r
-        * returns an empty String. Example : '/document/content.xml' => 'xml'\r
-        * \r
-        * @return The extension of the part name.\r
-        */\r
-       public String getExtension() {\r
-               String fragment = this.partNameURI.getPath();\r
-               if (fragment.length() > 0) {\r
-                       int i = fragment.lastIndexOf(".");\r
-                       if (i > -1)\r
-                               return fragment.substring(i + 1);\r
-               }\r
-               return "";\r
-       }\r
-\r
-       /**\r
-        * Get this part name.\r
-        * \r
-        * @return The name of this part name.\r
-        */\r
-       public String getName() {\r
-               return this.partNameURI.toASCIIString();\r
-       }\r
-\r
-       /**\r
-        * Part name equivalence is determined by comparing part names as\r
-        * case-insensitive ASCII strings. Packages shall not contain equivalent\r
-        * part names and package implementers shall neither create nor recognize\r
-        * packages with equivalent part names. [M1.12]\r
-        */\r
-       @Override\r
-       public boolean equals(Object otherPartName) {\r
-               if (otherPartName == null\r
-                               || !(otherPartName instanceof PackagePartName))\r
-                       return false;\r
-               return this.partNameURI.toASCIIString().toLowerCase().equals(\r
-                               ((PackagePartName) otherPartName).partNameURI.toASCIIString()\r
-                                               .toLowerCase());\r
-       }\r
-\r
-       @Override\r
-       public int hashCode() {\r
-               return this.partNameURI.toASCIIString().toLowerCase().hashCode();\r
-       }\r
-\r
-       @Override\r
-       public String toString() {\r
-               return getName();\r
-       }\r
-\r
-       /* Getters and setters */\r
-\r
-       /**\r
-        * Part name property getter.\r
-        * \r
-        * @return This part name URI.\r
-        */\r
-       public URI getURI() {\r
-               return this.partNameURI;\r
-       }\r
-}\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.openxml4j.opc;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException;
+
+/**
+ * An immutable Open Packaging Convention compliant part name.
+ *
+ * @author Julien Chable
+ *
+ * @see <a href="http://www.ietf.org/rfc/rfc3986.txt">http://www.ietf.org/rfc/rfc3986.txt</a>
+ */
+public final class PackagePartName implements Comparable<PackagePartName> {
+
+       /**
+        * Part name stored as an URI.
+        */
+       private URI partNameURI;
+
+       /*
+        * URI Characters definition (RFC 3986)
+        */
+
+       /**
+        * Reserved characters for sub delimitations.
+        */
+       private static String[] RFC3986_PCHAR_SUB_DELIMS = { "!", "$", "&", "'",
+                       "(", ")", "*", "+", ",", ";", "=" };
+
+       /**
+        * Unreserved character (+ ALPHA & DIGIT).
+        */
+       private static String[] RFC3986_PCHAR_UNRESERVED_SUP = { "-", ".", "_", "~" };
+
+       /**
+        * Authorized reserved characters for pChar.
+        */
+       private static String[] RFC3986_PCHAR_AUTHORIZED_SUP = { ":", "@" };
+
+       /**
+        * Flag to know if this part name is from a relationship part name.
+        */
+       private boolean isRelationship;
+
+       /**
+        * Constructor. Makes a ValidPartName object from a java.net.URI
+        *
+        * @param uri
+        *            The URI to validate and to transform into ValidPartName.
+        * @param checkConformance
+        *            Flag to specify if the contructor have to validate the OPC
+        *            conformance. Must be always <code>true</code> except for
+        *            special URI like '/' which is needed for internal use by
+        *            OpenXML4J but is not valid.
+        * @throws InvalidFormatException
+        *             Throw if the specified part name is not conform to Open
+        *             Packaging Convention specifications.
+        * @see java.net.URI
+        */
+       PackagePartName(URI uri, boolean checkConformance)
+                       throws InvalidFormatException {
+               if (checkConformance) {
+                       throwExceptionIfInvalidPartUri(uri);
+               } else {
+                       if (!PackagingURIHelper.PACKAGE_ROOT_URI.equals(uri)) {
+                               throw new OpenXML4JRuntimeException(
+                                               "OCP conformance must be check for ALL part name except special cases : ['/']");
+                       }
+               }
+               this.partNameURI = uri;
+               this.isRelationship = isRelationshipPartURI(this.partNameURI);
+       }
+
+       /**
+        * Constructor. Makes a ValidPartName object from a String part name.
+        *
+        * @param partName
+        *            Part name to valid and to create.
+        * @param checkConformance
+        *            Flag to specify if the contructor have to validate the OPC
+        *            conformance. Must be always <code>true</code> except for
+        *            special URI like '/' which is needed for internal use by
+        *            OpenXML4J but is not valid.
+        * @throws InvalidFormatException
+        *             Throw if the specified part name is not conform to Open
+        *             Packaging Convention specifications.
+        */
+       PackagePartName(String partName, boolean checkConformance)
+                       throws InvalidFormatException {
+               URI partURI;
+               try {
+                       partURI = new URI(partName);
+               } catch (URISyntaxException e) {
+                       throw new IllegalArgumentException(
+                                       "partName argmument is not a valid OPC part name !");
+               }
+
+               if (checkConformance) {
+                       throwExceptionIfInvalidPartUri(partURI);
+               } else {
+                       if (!PackagingURIHelper.PACKAGE_ROOT_URI.equals(partURI)) {
+                               throw new OpenXML4JRuntimeException(
+                                               "OCP conformance must be check for ALL part name except special cases : ['/']");
+                       }
+               }
+               this.partNameURI = partURI;
+               this.isRelationship = isRelationshipPartURI(this.partNameURI);
+       }
+
+       /**
+        * Check if the specified part name is a relationship part name.
+        *
+        * @param partUri
+        *            The URI to check.
+        * @return <code>true</code> if this part name respect the relationship
+        *         part naming convention else <code>false</code>.
+        */
+       private boolean isRelationshipPartURI(URI partUri) {
+               if (partUri == null)
+                       throw new IllegalArgumentException("partUri");
+
+               return partUri.getPath().matches(
+                               "^.*/" + PackagingURIHelper.RELATIONSHIP_PART_SEGMENT_NAME + "/.*\\"
+                                               + PackagingURIHelper.RELATIONSHIP_PART_EXTENSION_NAME
+                                               + "$");
+       }
+
+       /**
+        * Know if this part name is a relationship part name.
+        *
+        * @return <code>true</code> if this part name respect the relationship
+        *         part naming convention else <code>false</code>.
+        */
+       public boolean isRelationshipPartURI() {
+               return this.isRelationship;
+       }
+
+       /**
+        * Throws an exception (of any kind) if the specified part name does not
+        * follow the Open Packaging Convention specifications naming rules.
+        *
+        * @param partUri
+        *            The part name to check.
+        * @throws Exception
+        *             Throws if the part name is invalid.
+        */
+       private static void throwExceptionIfInvalidPartUri(URI partUri)
+                       throws InvalidFormatException {
+               if (partUri == null)
+                       throw new IllegalArgumentException("partUri");
+               // Check if the part name URI is empty [M1.1]
+               throwExceptionIfEmptyURI(partUri);
+
+               // Check if the part name URI is absolute
+               throwExceptionIfAbsoluteUri(partUri);
+
+               // Check if the part name URI starts with a forward slash [M1.4]
+               throwExceptionIfPartNameNotStartsWithForwardSlashChar(partUri);
+
+               // Check if the part name URI ends with a forward slash [M1.5]
+               throwExceptionIfPartNameEndsWithForwardSlashChar(partUri);
+
+               // Check if the part name does not have empty segments. [M1.3]
+               // Check if a segment ends with a dot ('.') character. [M1.9]
+               throwExceptionIfPartNameHaveInvalidSegments(partUri);
+       }
+
+       /**
+        * Throws an exception if the specified URI is empty. [M1.1]
+        *
+        * @param partURI
+        *            Part URI to check.
+        * @throws InvalidFormatException
+        *             If the specified URI is empty.
+        */
+       private static void throwExceptionIfEmptyURI(URI partURI)
+                       throws InvalidFormatException {
+               if (partURI == null)
+                       throw new IllegalArgumentException("partURI");
+
+               String uriPath = partURI.getPath();
+               if (uriPath.length() == 0
+                               || ((uriPath.length() == 1) && (uriPath.charAt(0) == PackagingURIHelper.FORWARD_SLASH_CHAR)))
+                       throw new InvalidFormatException(
+                                       "A part name shall not be empty [M1.1]: "
+                                                       + partURI.getPath());
+       }
+
+       /**
+        * Throws an exception if the part name has empty segments. [M1.3]
+        *
+        * Throws an exception if a segment any characters other than pchar
+        * characters. [M1.6]
+        *
+        * Throws an exception if a segment contain percent-encoded forward slash
+        * ('/'), or backward slash ('\') characters. [M1.7]
+        *
+        * Throws an exception if a segment contain percent-encoded unreserved
+        * characters. [M1.8]
+        *
+        * Throws an exception if the specified part name's segments end with a dot
+        * ('.') character. [M1.9]
+        *
+        * Throws an exception if a segment doesn't include at least one non-dot
+        * character. [M1.10]
+        *
+        * @param partUri
+        *            The part name to check.
+        * @throws InvalidFormatException
+        *             if the specified URI contain an empty segments or if one the
+        *             segments contained in the part name, ends with a dot ('.')
+        *             character.
+        */
+       private static void throwExceptionIfPartNameHaveInvalidSegments(URI partUri)
+                       throws InvalidFormatException {
+               if (partUri == null || "".equals(partUri)) {
+                       throw new IllegalArgumentException("partUri");
+               }
+
+               // Split the URI into several part and analyze each
+               String[] segments = partUri.toASCIIString().split("/");
+               if (segments.length <= 1 || !segments[0].equals(""))
+                       throw new InvalidFormatException(
+                                       "A part name shall not have empty segments [M1.3]: "
+                                                       + partUri.getPath());
+
+               for (int i = 1; i < segments.length; ++i) {
+                       String seg = segments[i];
+                       if (seg == null || "".equals(seg)) {
+                               throw new InvalidFormatException(
+                                               "A part name shall not have empty segments [M1.3]: "
+                                                               + partUri.getPath());
+                       }
+
+                       if (seg.endsWith(".")) {
+                               throw new InvalidFormatException(
+                                               "A segment shall not end with a dot ('.') character [M1.9]: "
+                                                               + partUri.getPath());
+                       }
+
+                       if ("".equals(seg.replaceAll("\\\\.", ""))) {
+                               // Normally will never been invoked with the previous
+                               // implementation rule [M1.9]
+                               throw new InvalidFormatException(
+                                               "A segment shall include at least one non-dot character. [M1.10]: "
+                                                               + partUri.getPath());
+                       }
+
+                       // Check for rule M1.6, M1.7, M1.8
+                       checkPCharCompliance(seg);
+               }
+       }
+
+       /**
+        * Throws an exception if a segment any characters other than pchar
+        * characters. [M1.6]
+        *
+        * Throws an exception if a segment contain percent-encoded forward slash
+        * ('/'), or backward slash ('\') characters. [M1.7]
+        *
+        * Throws an exception if a segment contain percent-encoded unreserved
+        * characters. [M1.8]
+        *
+        * @param segment
+        *            The segment to check
+        */
+       private static void checkPCharCompliance(String segment)
+                       throws InvalidFormatException {
+               boolean errorFlag;
+               for (int i = 0; i < segment.length(); ++i) {
+                       char c = segment.charAt(i);
+                       errorFlag = true;
+
+                       /* Check rule M1.6 */
+
+                       // Check for digit or letter
+                       if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
+                                       || (c >= '0' && c <= '9')) {
+                               errorFlag = false;
+                       } else {
+                               // Check "-", ".", "_", "~"
+                               for (int j = 0; j < RFC3986_PCHAR_UNRESERVED_SUP.length; ++j) {
+                                       if (c == RFC3986_PCHAR_UNRESERVED_SUP[j].charAt(0)) {
+                                               errorFlag = false;
+                                               break;
+                                       }
+                               }
+
+                               // Check ":", "@"
+                               for (int j = 0; errorFlag
+                                               && j < RFC3986_PCHAR_AUTHORIZED_SUP.length; ++j) {
+                                       if (c == RFC3986_PCHAR_AUTHORIZED_SUP[j].charAt(0)) {
+                                               errorFlag = false;
+                                       }
+                               }
+
+                               // Check "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
+                               for (int j = 0; errorFlag
+                                               && j < RFC3986_PCHAR_SUB_DELIMS.length; ++j) {
+                                       if (c == RFC3986_PCHAR_SUB_DELIMS[j].charAt(0)) {
+                                               errorFlag = false;
+                                       }
+                               }
+                       }
+
+                       if (errorFlag && c == '%') {
+                               // We certainly found an encoded character, check for length
+                               // now ( '%' HEXDIGIT HEXDIGIT)
+                               if (((segment.length() - i) < 2)) {
+                                       throw new InvalidFormatException("The segment " + segment
+                                                       + " contain invalid encoded character !");
+                               }
+
+                               // If not percent encoded character error occur then reset the
+                               // flag -> the character is valid
+                               errorFlag = false;
+
+                               // Decode the encoded character
+                               char decodedChar = (char) Integer.parseInt(segment.substring(
+                                               i + 1, i + 3), 16);
+                               i += 2;
+
+                               /* Check rule M1.7 */
+                               if (decodedChar == '/' || decodedChar == '\\')
+                                       throw new InvalidFormatException(
+                                                       "A segment shall not contain percent-encoded forward slash ('/'), or backward slash ('\') characters. [M1.7]");
+
+                               /* Check rule M1.8 */
+
+                               // Check for unreserved character like define in RFC3986
+                               if ((decodedChar >= 'A' && decodedChar <= 'Z')
+                                               || (decodedChar >= 'a' && decodedChar <= 'z')
+                                               || (decodedChar >= '0' && decodedChar <= '9'))
+                                       errorFlag = true;
+
+                               // Check for unreserved character "-", ".", "_", "~"
+                               for (int j = 0; !errorFlag
+                                               && j < RFC3986_PCHAR_UNRESERVED_SUP.length; ++j) {
+                                       if (c == RFC3986_PCHAR_UNRESERVED_SUP[j].charAt(0)) {
+                                               errorFlag = true;
+                                               break;
+                                       }
+                               }
+                               if (errorFlag)
+                                       throw new InvalidFormatException(
+                                                       "A segment shall not contain percent-encoded unreserved characters. [M1.8]");
+                       }
+
+                       if (errorFlag)
+                               throw new InvalidFormatException(
+                                               "A segment shall not hold any characters other than pchar characters. [M1.6]");
+               }
+       }
+
+       /**
+        * Throws an exception if the specified part name doesn't start with a
+        * forward slash character '/'. [M1.4]
+        *
+        * @param partUri
+        *            The part name to check.
+        * @throws InvalidFormatException
+        *             If the specified part name doesn't start with a forward slash
+        *             character '/'.
+        */
+       private static void throwExceptionIfPartNameNotStartsWithForwardSlashChar(
+                       URI partUri) throws InvalidFormatException {
+               String uriPath = partUri.getPath();
+               if (uriPath.length() > 0
+                               && uriPath.charAt(0) != PackagingURIHelper.FORWARD_SLASH_CHAR)
+                       throw new InvalidFormatException(
+                                       "A part name shall start with a forward slash ('/') character [M1.4]: "
+                                                       + partUri.getPath());
+       }
+
+       /**
+        * Throws an exception if the specified part name ends with a forwar slash
+        * character '/'. [M1.5]
+        *
+        * @param partUri
+        *            The part name to check.
+        * @throws InvalidFormatException
+        *             If the specified part name ends with a forwar slash character
+        *             '/'.
+        */
+       private static void throwExceptionIfPartNameEndsWithForwardSlashChar(
+                       URI partUri) throws InvalidFormatException {
+               String uriPath = partUri.getPath();
+               if (uriPath.length() > 0
+                               && uriPath.charAt(uriPath.length() - 1) == PackagingURIHelper.FORWARD_SLASH_CHAR)
+                       throw new InvalidFormatException(
+                                       "A part name shall not have a forward slash as the last character [M1.5]: "
+                                                       + partUri.getPath());
+       }
+
+       /**
+        * Throws an exception if the specified URI is absolute.
+        *
+        * @param partUri
+        *            The URI to check.
+        * @throws InvalidFormatException
+        *             Throws if the specified URI is absolute.
+        */
+       private static void throwExceptionIfAbsoluteUri(URI partUri)
+                       throws InvalidFormatException {
+               if (partUri.isAbsolute())
+                       throw new InvalidFormatException("Absolute URI forbidden: "
+                                       + partUri);
+       }
+
+       /**
+        * Compare two part name following the rule M1.12 :
+        *
+        * Part name equivalence is determined by comparing part names as
+        * case-insensitive ASCII strings. Packages shall not contain equivalent
+        * part names and package implementers shall neither create nor recognize
+        * packages with equivalent part names. [M1.12]
+        */
+       public int compareTo(PackagePartName otherPartName) {
+               if (otherPartName == null)
+                       return -1;
+               return this.partNameURI.toASCIIString().toLowerCase().compareTo(
+                               otherPartName.partNameURI.toASCIIString().toLowerCase());
+       }
+
+       /**
+        * Retrieves the extension of the part name if any. If there is no extension
+        * returns an empty String. Example : '/document/content.xml' => 'xml'
+        *
+        * @return The extension of the part name.
+        */
+       public String getExtension() {
+               String fragment = this.partNameURI.getPath();
+               if (fragment.length() > 0) {
+                       int i = fragment.lastIndexOf(".");
+                       if (i > -1)
+                               return fragment.substring(i + 1);
+               }
+               return "";
+       }
+
+       /**
+        * Get this part name.
+        *
+        * @return The name of this part name.
+        */
+       public String getName() {
+               return this.partNameURI.toASCIIString();
+       }
+
+       /**
+        * Part name equivalence is determined by comparing part names as
+        * case-insensitive ASCII strings. Packages shall not contain equivalent
+        * part names and package implementers shall neither create nor recognize
+        * packages with equivalent part names. [M1.12]
+        */
+       @Override
+       public boolean equals(Object otherPartName) {
+               if (otherPartName == null
+                               || !(otherPartName instanceof PackagePartName))
+                       return false;
+               return this.partNameURI.toASCIIString().toLowerCase().equals(
+                               ((PackagePartName) otherPartName).partNameURI.toASCIIString()
+                                               .toLowerCase());
+       }
+
+       @Override
+       public int hashCode() {
+               return this.partNameURI.toASCIIString().toLowerCase().hashCode();
+       }
+
+       @Override
+       public String toString() {
+               return getName();
+       }
+
+       /* Getters and setters */
+
+       /**
+        * Part name property getter.
+        *
+        * @return This part name URI.
+        */
+       public URI getURI() {
+               return this.partNameURI;
+       }
+}
index e5ecaacc452fd5787d605e2e832d0c50c98dbe64..e36c0251911a2127e5abfdc6a270e7a35bc7d8fe 100755 (executable)
@@ -1,77 +1,77 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-/**\r
- * Relationship types.\r
- * \r
- * @author Julien Chable\r
- * @version 0.2\r
- */\r
-public interface PackageRelationshipTypes {\r
-\r
-       /**\r
-        * Core properties relationship type.\r
-        */\r
-       String CORE_PROPERTIES = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";\r
-\r
-       /**\r
-        * Digital signature relationship type.\r
-        */\r
-       String DIGITAL_SIGNATURE = "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature";\r
-\r
-       /**\r
-        * Digital signature certificate relationship type.\r
-        */\r
-       String DIGITAL_SIGNATURE_CERTIFICATE = "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/certificate";\r
-\r
-       /**\r
-        * Digital signature origin relationship type.\r
-        */\r
-       String DIGITAL_SIGNATURE_ORIGIN = "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin";\r
-\r
-       /**\r
-        * Thumbnail relationship type.\r
-        */\r
-       String THUMBNAIL = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail";\r
-\r
-       /**\r
-        * Extended properties relationship type.\r
-        */\r
-       String EXTENDED_PROPERTIES = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties";\r
-\r
-       /**\r
-        * Core properties relationship type.\r
-        */\r
-       String CORE_DOCUMENT = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";\r
-       \r
-       /**\r
-        * Custom XML relationship type.\r
-        */\r
-       String CUSTOM_XML = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml";\r
-\r
-       /**\r
-        * Image type.\r
-        */\r
-       String IMAGE_PART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";\r
-\r
-       /**\r
-        * Style type.\r
-        */\r
-       String STYLE_PART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";\r
-}\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.openxml4j.opc;
+
+/**
+ * Relationship types.
+ *
+ * @author Julien Chable
+ * @version 0.2
+ */
+public interface PackageRelationshipTypes {
+
+       /**
+        * Core properties relationship type.
+        */
+       String CORE_PROPERTIES = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
+
+       /**
+        * Digital signature relationship type.
+        */
+       String DIGITAL_SIGNATURE = "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature";
+
+       /**
+        * Digital signature certificate relationship type.
+        */
+       String DIGITAL_SIGNATURE_CERTIFICATE = "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/certificate";
+
+       /**
+        * Digital signature origin relationship type.
+        */
+       String DIGITAL_SIGNATURE_ORIGIN = "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin";
+
+       /**
+        * Thumbnail relationship type.
+        */
+       String THUMBNAIL = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail";
+
+       /**
+        * Extended properties relationship type.
+        */
+       String EXTENDED_PROPERTIES = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties";
+
+       /**
+        * Core properties relationship type.
+        */
+       String CORE_DOCUMENT = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
+
+       /**
+        * Custom XML relationship type.
+        */
+       String CUSTOM_XML = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml";
+
+       /**
+        * Image type.
+        */
+       String IMAGE_PART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
+
+       /**
+        * Style type.
+        */
+       String STYLE_PART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
+}
index 58f6066aad5291e6be908fe94a847511d41c84e1..b53903df9207ceb19a8443d4a37a79291a682e68 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-import java.net.URI;\r
-import java.net.URISyntaxException;\r
-\r
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;\r
-import org.apache.poi.openxml4j.exceptions.InvalidOperationException;\r
-\r
-/**\r
- * Helper for part and pack URI.\r
- * \r
- * @author Julien Chable, CDubet, Kim Ung\r
- * @version 0.1\r
- */\r
-public final class PackagingURIHelper {\r
-\r
-       /**\r
-        * Package root URI.\r
-        */\r
-       private static URI packageRootUri;\r
-\r
-       /**\r
-        * Extension name of a relationship part.\r
-        */\r
-       public static final String RELATIONSHIP_PART_EXTENSION_NAME;\r
-\r
-       /**\r
-        * Segment name of a relationship part.\r
-        */\r
-       public static final String RELATIONSHIP_PART_SEGMENT_NAME;\r
-\r
-       /**\r
-        * Segment name of the package properties folder.\r
-        */\r
-       public static final String PACKAGE_PROPERTIES_SEGMENT_NAME;\r
-\r
-       /**\r
-        * Core package properties art name.\r
-        */\r
-       public static final String PACKAGE_CORE_PROPERTIES_NAME;\r
-\r
-       /**\r
-        * Forward slash URI separator.\r
-        */\r
-       public static final char FORWARD_SLASH_CHAR;\r
-\r
-       /**\r
-        * Forward slash URI separator.\r
-        */\r
-       public static final String FORWARD_SLASH_STRING;\r
-\r
-       /**\r
-        * Package relationships part URI\r
-        */\r
-       public static final URI PACKAGE_RELATIONSHIPS_ROOT_URI;\r
-\r
-       /**\r
-        * Package relationships part name.\r
-        */\r
-       public static final PackagePartName PACKAGE_RELATIONSHIPS_ROOT_PART_NAME;\r
-\r
-       /**\r
-        * Core properties part URI.\r
-        */\r
-       public static final URI CORE_PROPERTIES_URI;\r
-\r
-       /**\r
-        * Core properties partname.\r
-        */\r
-       public static final PackagePartName CORE_PROPERTIES_PART_NAME;\r
-\r
-       /**\r
-        * Root package URI.\r
-        */\r
-       public static final URI PACKAGE_ROOT_URI;\r
-\r
-       /**\r
-        * Root package part name.\r
-        */\r
-       public static final PackagePartName PACKAGE_ROOT_PART_NAME;\r
-\r
-       /* Static initialization */\r
-       static {\r
-               RELATIONSHIP_PART_SEGMENT_NAME = "_rels";\r
-               RELATIONSHIP_PART_EXTENSION_NAME = ".rels";\r
-               FORWARD_SLASH_CHAR = '/';\r
-               FORWARD_SLASH_STRING = "/";\r
-               PACKAGE_PROPERTIES_SEGMENT_NAME = "docProps";\r
-               PACKAGE_CORE_PROPERTIES_NAME = "core.xml";\r
-\r
-               // Make URI\r
-               URI uriPACKAGE_ROOT_URI = null;\r
-               URI uriPACKAGE_RELATIONSHIPS_ROOT_URI = null;\r
-               URI uriPACKAGE_PROPERTIES_URI = null;\r
-               try {\r
-                       uriPACKAGE_ROOT_URI = new URI("/");\r
-                       uriPACKAGE_RELATIONSHIPS_ROOT_URI = new URI(FORWARD_SLASH_CHAR\r
-                                       + RELATIONSHIP_PART_SEGMENT_NAME + FORWARD_SLASH_CHAR\r
-                                       + RELATIONSHIP_PART_EXTENSION_NAME);\r
-                       packageRootUri = new URI("/");\r
-                       uriPACKAGE_PROPERTIES_URI = new URI(FORWARD_SLASH_CHAR\r
-                                       + PACKAGE_PROPERTIES_SEGMENT_NAME + FORWARD_SLASH_CHAR\r
-                                       + PACKAGE_CORE_PROPERTIES_NAME);\r
-               } catch (URISyntaxException e) {\r
-                       // Should never happen in production as all data are fixed\r
-               }\r
-               PACKAGE_ROOT_URI = uriPACKAGE_ROOT_URI;\r
-               PACKAGE_RELATIONSHIPS_ROOT_URI = uriPACKAGE_RELATIONSHIPS_ROOT_URI;\r
-               CORE_PROPERTIES_URI = uriPACKAGE_PROPERTIES_URI;\r
-\r
-               // Make part name from previous URI\r
-               PackagePartName tmpPACKAGE_ROOT_PART_NAME = null;\r
-               PackagePartName tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME = null;\r
-               PackagePartName tmpCORE_PROPERTIES_URI = null;\r
-               try {\r
-                       tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME = createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI);\r
-                       tmpCORE_PROPERTIES_URI = createPartName(CORE_PROPERTIES_URI);\r
-                       tmpPACKAGE_ROOT_PART_NAME = new PackagePartName(PACKAGE_ROOT_URI,\r
-                                       false);\r
-               } catch (InvalidFormatException e) {\r
-                       // Should never happen in production as all data are fixed\r
-               }\r
-               PACKAGE_RELATIONSHIPS_ROOT_PART_NAME = tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME;\r
-               CORE_PROPERTIES_PART_NAME = tmpCORE_PROPERTIES_URI;\r
-               PACKAGE_ROOT_PART_NAME = tmpPACKAGE_ROOT_PART_NAME;\r
-       }\r
-\r
-       /**\r
-        * Gets the URI for the package root.\r
-        * \r
-        * @return URI of the package root.\r
-        */\r
-       public static URI getPackageRootUri() {\r
-               return packageRootUri;\r
-       }\r
-\r
-       /**\r
-        * Know if the specified URI is a relationship part name.\r
-        * \r
-        * @param partUri\r
-        *            URI to check.\r
-        * @return <i>true</i> if the URI <i>false</i>.\r
-        */\r
-       public static boolean isRelationshipPartURI(URI partUri) {\r
-               if (partUri == null)\r
-                       throw new IllegalArgumentException("partUri");\r
-\r
-               return partUri.getPath().matches(\r
-                               ".*" + RELATIONSHIP_PART_SEGMENT_NAME + ".*"\r
-                                               + RELATIONSHIP_PART_EXTENSION_NAME + "$");\r
-       }\r
-\r
-       /**\r
-        * Get file name from the specified URI.\r
-        */\r
-       public static String getFilename(URI uri) {\r
-               if (uri != null) {\r
-                       String path = uri.getPath();\r
-                       int len = path.length();\r
-                       int num2 = len;\r
-                       while (--num2 >= 0) {\r
-                               char ch1 = path.charAt(num2);\r
-                               if (ch1 == PackagingURIHelper.FORWARD_SLASH_CHAR)\r
-                                       return path.substring(num2 + 1, len);\r
-                       }\r
-               }\r
-               return "";\r
-       }\r
-\r
-       /**\r
-        * Get the file name without the trailing extension.\r
-        */\r
-       public static String getFilenameWithoutExtension(URI uri) {\r
-               String filename = getFilename(uri);\r
-               int dotIndex = filename.lastIndexOf(".");\r
-               if (dotIndex == -1)\r
-                       return filename;\r
-               return filename.substring(0, dotIndex);\r
-       }\r
-\r
-       /**\r
-        * Get the directory path from the specified URI.\r
-        */\r
-       public static URI getPath(URI uri) {\r
-               if (uri != null) {\r
-                       String path = uri.getPath();\r
-                       int len = path.length();\r
-                       int num2 = len;\r
-                       while (--num2 >= 0) {\r
-                               char ch1 = path.charAt(num2);\r
-                               if (ch1 == PackagingURIHelper.FORWARD_SLASH_CHAR) {\r
-                                       try {\r
-                                               return new URI(path.substring(0, num2));\r
-                                       } catch (URISyntaxException e) {\r
-                                               return null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-               return null;\r
-       }\r
-\r
-       /**\r
-        * Combine two URIs.\r
-        * \r
-        * @param prefix the prefix URI\r
-        * @param suffix the suffix URI\r
-        *\r
-        * @return the combined URI\r
-        */\r
-       public static URI combine(URI prefix, URI suffix) {\r
-               URI retUri = null;\r
-               try {\r
-                       retUri = new URI(combine(prefix.getPath(), suffix.getPath()));\r
-               } catch (URISyntaxException e) {\r
-                       throw new IllegalArgumentException(\r
-                                       "Prefix and suffix can't be combine !");\r
-               }\r
-               return retUri;\r
-       }\r
-\r
-       /**\r
-        * Combine a string URI with a prefix and a suffix.\r
-        */\r
-       public static String combine(String prefix, String suffix) {\r
-               if (!prefix.endsWith("" + FORWARD_SLASH_CHAR)\r
-                               && !suffix.startsWith("" + FORWARD_SLASH_CHAR))\r
-                       return prefix + FORWARD_SLASH_CHAR + suffix;\r
-               else if ((!prefix.endsWith("" + FORWARD_SLASH_CHAR)\r
-                               && suffix.startsWith("" + FORWARD_SLASH_CHAR) || (prefix\r
-                               .endsWith("" + FORWARD_SLASH_CHAR) && !suffix.startsWith(""\r
-                               + FORWARD_SLASH_CHAR))))\r
-                       return prefix + suffix;\r
-               else\r
-                       return "";\r
-       }\r
-\r
-       /**\r
-        * Fully relativize the source part URI against the target part URI.\r
-        * \r
-        * @param sourceURI\r
-        *            The source part URI.\r
-        * @param targetURI\r
-        *            The target part URI.\r
-        * @return A fully relativize part name URI ('word/media/image1.gif',\r
-        *         '/word/document.xml' => 'media/image1.gif') else\r
-        *         <code>null</code>.\r
-        */\r
-       public static URI relativizeURI(URI sourceURI, URI targetURI) {\r
-               StringBuilder retVal = new StringBuilder();\r
-               String[] segmentsSource = sourceURI.getPath().split("/", -1);\r
-               String[] segmentsTarget = targetURI.getPath().split("/", -1);\r
-\r
-               // If the source URI is empty\r
-               if (segmentsSource.length == 0) {\r
-                       throw new IllegalArgumentException(\r
-                                       "Can't relativize an empty source URI !");\r
-               }\r
-\r
-               // If target URI is empty\r
-               if (segmentsTarget.length == 0) {\r
-                       throw new IllegalArgumentException(\r
-                                       "Can't relativize an empty target URI !");\r
-               }\r
-               \r
-               // If the source is the root, then the relativized\r
-               //  form must actually be an absolute URI\r
-               if(sourceURI.toString().equals("/")) {\r
-                       return targetURI;\r
-               }\r
-\r
-\r
-               // Relativize the source URI against the target URI.\r
-               // First up, figure out how many steps along we can go\r
-               // and still have them be the same\r
-               int segmentsTheSame = 0;\r
-               for (int i = 0; i < segmentsSource.length && i < segmentsTarget.length; i++) {\r
-                       if (segmentsSource[i].equals(segmentsTarget[i])) {\r
-                               // Match so far, good\r
-                               segmentsTheSame++;\r
-                       } else {\r
-                               break;\r
-                       }\r
-               }\r
-\r
-               // If we didn't have a good match or at least except a first empty element\r
-               if ((segmentsTheSame == 0 || segmentsTheSame == 1) && \r
-                               segmentsSource[0].equals("") && segmentsTarget[0].equals("")) {\r
-                       for (int i = 0; i < segmentsSource.length - 2; i++) {\r
-                               retVal.append("../");\r
-                       }\r
-                       for (int i = 0; i < segmentsTarget.length; i++) {\r
-                               if (segmentsTarget[i].equals(""))\r
-                                       continue;\r
-                               retVal.append(segmentsTarget[i]);\r
-                               if (i != segmentsTarget.length - 1)\r
-                                       retVal.append("/");\r
-                       }\r
-\r
-                       try {\r
-                               return new URI(retVal.toString());\r
-                       } catch (Exception e) {\r
-                               System.err.println(e);\r
-                               return null;\r
-                       }\r
-               }\r
-\r
-               // Special case for where the two are the same\r
-               if (segmentsTheSame == segmentsSource.length\r
-                               && segmentsTheSame == segmentsTarget.length) {\r
-                       retVal.append("");\r
-               } else {\r
-                       // Matched for so long, but no more\r
-\r
-                       // Do we need to go up a directory or two from\r
-                       // the source to get here?\r
-                       // (If it's all the way up, then don't bother!)\r
-                       if (segmentsTheSame == 1) {\r
-                               retVal.append("/");\r
-                       } else {\r
-                               for (int j = segmentsTheSame; j < segmentsSource.length - 1; j++) {\r
-                                       retVal.append("../");\r
-                               }\r
-                       }\r
-\r
-                       // Now go from here on down\r
-                       for (int j = segmentsTheSame; j < segmentsTarget.length; j++) {\r
-                               if (retVal.length() > 0\r
-                                               && retVal.charAt(retVal.length() - 1) != '/') {\r
-                                       retVal.append("/");\r
-                               }\r
-                               retVal.append(segmentsTarget[j]);\r
-                       }\r
-               }\r
-\r
-               try {\r
-                       return new URI(retVal.toString());\r
-               } catch (Exception e) {\r
-                       System.err.println(e);\r
-                       return null;\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Resolve a source uri against a target.\r
-        * \r
-        * @param sourcePartUri\r
-        *            The source URI.\r
-        * @param targetUri\r
-        *            The target URI.\r
-        * @return The resolved URI.\r
-        */\r
-       public static URI resolvePartUri(URI sourcePartUri, URI targetUri) {\r
-               if (sourcePartUri == null || sourcePartUri.isAbsolute()) {\r
-                       throw new IllegalArgumentException("sourcePartUri invalid - "\r
-                                       + sourcePartUri);\r
-               }\r
-\r
-               if (targetUri == null || targetUri.isAbsolute()) {\r
-                       throw new IllegalArgumentException("targetUri invalid - "\r
-                                       + targetUri);\r
-               }\r
-\r
-               return sourcePartUri.resolve(targetUri);\r
-       }\r
-\r
-       /**\r
-        * Get URI from a string path.\r
-        */\r
-       public static URI getURIFromPath(String path) {\r
-               URI retUri = null;\r
-               try {\r
-                       retUri = new URI(path);\r
-               } catch (URISyntaxException e) {\r
-                       throw new IllegalArgumentException("path");\r
-               }\r
-               return retUri;\r
-       }\r
-\r
-       /**\r
-        * Get the source part URI from a specified relationships part.\r
-        * \r
-        * @param relationshipPartUri\r
-        *            The relationship part use to retrieve the source part.\r
-        * @return The source part URI from the specified relationships part.\r
-        */\r
-       public static URI getSourcePartUriFromRelationshipPartUri(\r
-                       URI relationshipPartUri) {\r
-               if (relationshipPartUri == null)\r
-                       throw new IllegalArgumentException(\r
-                                       "Must not be null");\r
-\r
-               if (!isRelationshipPartURI(relationshipPartUri))\r
-                       throw new IllegalArgumentException(\r
-                                       "Must be a relationship part");\r
-\r
-               if (relationshipPartUri.compareTo(PACKAGE_RELATIONSHIPS_ROOT_URI) == 0)\r
-                       return PACKAGE_ROOT_URI;\r
-\r
-               String filename = relationshipPartUri.getPath();\r
-               String filenameWithoutExtension = getFilenameWithoutExtension(relationshipPartUri);\r
-               filename = filename\r
-                               .substring(0, ((filename.length() - filenameWithoutExtension\r
-                                               .length()) - RELATIONSHIP_PART_EXTENSION_NAME.length()));\r
-               filename = filename.substring(0, filename.length()\r
-                               - RELATIONSHIP_PART_SEGMENT_NAME.length() - 1);\r
-               filename = combine(filename, filenameWithoutExtension);\r
-               return getURIFromPath(filename);\r
-       }\r
-\r
-       /**\r
-        * Create an OPC compliant part name by throwing an exception if the URI is\r
-        * not valid.\r
-        * \r
-        * @param partUri\r
-        *            The part name URI to validate.\r
-        * @return A valid part name object, else <code>null</code>.\r
-        * @throws InvalidFormatException\r
-        *             Throws if the specified URI is not OPC compliant.\r
-        */\r
-       public static PackagePartName createPartName(URI partUri)\r
-                       throws InvalidFormatException {\r
-               if (partUri == null)\r
-                       throw new IllegalArgumentException("partName");\r
-\r
-               return new PackagePartName(partUri, true);\r
-       }\r
-\r
-       /**\r
-        * Create an OPC compliant part name.\r
-        * \r
-        * @param partName\r
-        *            The part name to validate.\r
-        * @return The correspondant part name if valid, else <code>null</code>.\r
-        * @throws InvalidFormatException\r
-        *             Throws if the specified part name is not OPC compliant.\r
-        * @see #createPartName(URI)\r
-        */\r
-       public static PackagePartName createPartName(String partName)\r
-                       throws InvalidFormatException {\r
-               URI partNameURI;\r
-               try {\r
-                       partNameURI = new URI(partName);\r
-               } catch (URISyntaxException e) {\r
-                       throw new InvalidFormatException(e.getMessage());\r
-               }\r
-               return createPartName(partNameURI);\r
-       }\r
-\r
-       /**\r
-        * Create an OPC compliant part name by resolving it using a base part.\r
-        * \r
-        * @param partName\r
-        *            The part name to validate.\r
-        * @param relativePart\r
-        *            The relative base part.\r
-        * @return The correspondant part name if valid, else <code>null</code>.\r
-        * @throws InvalidFormatException\r
-        *             Throws if the specified part name is not OPC compliant.\r
-        * @see #createPartName(URI)\r
-        */\r
-       public static PackagePartName createPartName(String partName,\r
-                       PackagePart relativePart) throws InvalidFormatException {\r
-               URI newPartNameURI;\r
-               try {\r
-                       newPartNameURI = resolvePartUri(\r
-                                       relativePart.getPartName().getURI(), new URI(partName));\r
-               } catch (URISyntaxException e) {\r
-                       throw new InvalidFormatException(e.getMessage());\r
-               }\r
-               return createPartName(newPartNameURI);\r
-       }\r
-\r
-       /**\r
-        * Create an OPC compliant part name by resolving it using a base part.\r
-        * \r
-        * @param partName\r
-        *            The part name URI to validate.\r
-        * @param relativePart\r
-        *            The relative base part.\r
-        * @return The correspondant part name if valid, else <code>null</code>.\r
-        * @throws InvalidFormatException\r
-        *             Throws if the specified part name is not OPC compliant.\r
-        * @see #createPartName(URI)\r
-        */\r
-       public static PackagePartName createPartName(URI partName,\r
-                       PackagePart relativePart) throws InvalidFormatException {\r
-               URI newPartNameURI = resolvePartUri(\r
-                               relativePart.getPartName().getURI(), partName);\r
-               return createPartName(newPartNameURI);\r
-       }\r
-\r
-       /**\r
-        * Validate a part URI by returning a boolean.\r
-        * ([M1.1],[M1.3],[M1.4],[M1.5],[M1.6])\r
-        * \r
-        * (OPC Specifications 8.1.1 Part names) :\r
-        * \r
-        * Part Name Syntax\r
-        * \r
-        * The part name grammar is defined as follows:\r
-        * \r
-        * <i>part_name = 1*( "/" segment )\r
-        * \r
-        * segment = 1*( pchar )</i>\r
-        * \r
-        * \r
-        * (pchar is defined in RFC 3986)\r
-        * \r
-        * @param partUri\r
-        *            The URI to validate.\r
-        * @return <b>true</b> if the URI is valid to the OPC Specifications, else\r
-        *         <b>false</b>\r
-        * \r
-        * @see #createPartName(URI)\r
-        */\r
-       public static boolean isValidPartName(URI partUri) {\r
-               if (partUri == null)\r
-                       throw new IllegalArgumentException("partUri");\r
-\r
-               try {\r
-                       createPartName(partUri);\r
-                       return true;\r
-               } catch (Exception e) {\r
-                       return false;\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Decode a URI by converting all percent encoded character into a String\r
-        * character.\r
-        * \r
-        * @param uri\r
-        *            The URI to decode.\r
-        * @return The specified URI in a String with converted percent encoded\r
-        *         characters.\r
-        */\r
-       public static String decodeURI(URI uri) {\r
-               StringBuffer retVal = new StringBuffer();\r
-               String uriStr = uri.toASCIIString();\r
-               char c;\r
-               for (int i = 0; i < uriStr.length(); ++i) {\r
-                       c = uriStr.charAt(i);\r
-                       if (c == '%') {\r
-                               // We certainly found an encoded character, check for length\r
-                               // now ( '%' HEXDIGIT HEXDIGIT)\r
-                               if (((uriStr.length() - i) < 2)) {\r
-                                       throw new IllegalArgumentException("The uri " + uriStr\r
-                                                       + " contain invalid encoded character !");\r
-                               }\r
-\r
-                               // Decode the encoded character\r
-                               char decodedChar = (char) Integer.parseInt(uriStr.substring(\r
-                                               i + 1, i + 3), 16);\r
-                               retVal.append(decodedChar);\r
-                               i += 2;\r
-                               continue;\r
-                       }\r
-                       retVal.append(c);\r
-               }\r
-               return retVal.toString();\r
-       }\r
-\r
-       /**\r
-        * Build a part name where the relationship should be stored ((ex\r
-        * /word/document.xml -> /word/_rels/document.xml.rels)\r
-        * \r
-        * @param partName\r
-        *            Source part URI\r
-        * @return the full path (as URI) of the relation file\r
-        * @throws InvalidOperationException\r
-        *             Throws if the specified URI is a relationshp part.\r
-        */\r
-       public static PackagePartName getRelationshipPartName(\r
-                       PackagePartName partName) {\r
-               if (partName == null)\r
-                       throw new IllegalArgumentException("partName");\r
-\r
-               if (PackagingURIHelper.PACKAGE_ROOT_URI.getPath() == partName.getURI()\r
-                               .getPath())\r
-                       return PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME;\r
-\r
-               if (partName.isRelationshipPartURI())\r
-                       throw new InvalidOperationException("Can't be a relationship part");\r
-\r
-               String fullPath = partName.getURI().getPath();\r
-               String filename = getFilename(partName.getURI());\r
-               fullPath = fullPath.substring(0, fullPath.length() - filename.length());\r
-               fullPath = combine(fullPath,\r
-                               PackagingURIHelper.RELATIONSHIP_PART_SEGMENT_NAME);\r
-               fullPath = combine(fullPath, filename);\r
-               fullPath = fullPath\r
-                               + PackagingURIHelper.RELATIONSHIP_PART_EXTENSION_NAME;\r
-\r
-               PackagePartName retPartName;\r
-               try {\r
-                       retPartName = createPartName(fullPath);\r
-               } catch (InvalidFormatException e) {\r
-                       // Should never happen in production as all data are fixed but in\r
-                       // case of return null:\r
-                       return null;\r
-               }\r
-               return retPartName;\r
-       }\r
-}\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.openxml4j.opc;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
+
+/**
+ * Helper for part and pack URI.
+ *
+ * @author Julien Chable, CDubet, Kim Ung
+ * @version 0.1
+ */
+public final class PackagingURIHelper {
+
+       /**
+        * Package root URI.
+        */
+       private static URI packageRootUri;
+
+       /**
+        * Extension name of a relationship part.
+        */
+       public static final String RELATIONSHIP_PART_EXTENSION_NAME;
+
+       /**
+        * Segment name of a relationship part.
+        */
+       public static final String RELATIONSHIP_PART_SEGMENT_NAME;
+
+       /**
+        * Segment name of the package properties folder.
+        */
+       public static final String PACKAGE_PROPERTIES_SEGMENT_NAME;
+
+       /**
+        * Core package properties art name.
+        */
+       public static final String PACKAGE_CORE_PROPERTIES_NAME;
+
+       /**
+        * Forward slash URI separator.
+        */
+       public static final char FORWARD_SLASH_CHAR;
+
+       /**
+        * Forward slash URI separator.
+        */
+       public static final String FORWARD_SLASH_STRING;
+
+       /**
+        * Package relationships part URI
+        */
+       public static final URI PACKAGE_RELATIONSHIPS_ROOT_URI;
+
+       /**
+        * Package relationships part name.
+        */
+       public static final PackagePartName PACKAGE_RELATIONSHIPS_ROOT_PART_NAME;
+
+       /**
+        * Core properties part URI.
+        */
+       public static final URI CORE_PROPERTIES_URI;
+
+       /**
+        * Core properties partname.
+        */
+       public static final PackagePartName CORE_PROPERTIES_PART_NAME;
+
+       /**
+        * Root package URI.
+        */
+       public static final URI PACKAGE_ROOT_URI;
+
+       /**
+        * Root package part name.
+        */
+       public static final PackagePartName PACKAGE_ROOT_PART_NAME;
+
+       /* Static initialization */
+       static {
+               RELATIONSHIP_PART_SEGMENT_NAME = "_rels";
+               RELATIONSHIP_PART_EXTENSION_NAME = ".rels";
+               FORWARD_SLASH_CHAR = '/';
+               FORWARD_SLASH_STRING = "/";
+               PACKAGE_PROPERTIES_SEGMENT_NAME = "docProps";
+               PACKAGE_CORE_PROPERTIES_NAME = "core.xml";
+
+               // Make URI
+               URI uriPACKAGE_ROOT_URI = null;
+               URI uriPACKAGE_RELATIONSHIPS_ROOT_URI = null;
+               URI uriPACKAGE_PROPERTIES_URI = null;
+               try {
+                       uriPACKAGE_ROOT_URI = new URI("/");
+                       uriPACKAGE_RELATIONSHIPS_ROOT_URI = new URI(FORWARD_SLASH_CHAR
+                                       + RELATIONSHIP_PART_SEGMENT_NAME + FORWARD_SLASH_CHAR
+                                       + RELATIONSHIP_PART_EXTENSION_NAME);
+                       packageRootUri = new URI("/");
+                       uriPACKAGE_PROPERTIES_URI = new URI(FORWARD_SLASH_CHAR
+                                       + PACKAGE_PROPERTIES_SEGMENT_NAME + FORWARD_SLASH_CHAR
+                                       + PACKAGE_CORE_PROPERTIES_NAME);
+               } catch (URISyntaxException e) {
+                       // Should never happen in production as all data are fixed
+               }
+               PACKAGE_ROOT_URI = uriPACKAGE_ROOT_URI;
+               PACKAGE_RELATIONSHIPS_ROOT_URI = uriPACKAGE_RELATIONSHIPS_ROOT_URI;
+               CORE_PROPERTIES_URI = uriPACKAGE_PROPERTIES_URI;
+
+               // Make part name from previous URI
+               PackagePartName tmpPACKAGE_ROOT_PART_NAME = null;
+               PackagePartName tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME = null;
+               PackagePartName tmpCORE_PROPERTIES_URI = null;
+               try {
+                       tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME = createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI);
+                       tmpCORE_PROPERTIES_URI = createPartName(CORE_PROPERTIES_URI);
+                       tmpPACKAGE_ROOT_PART_NAME = new PackagePartName(PACKAGE_ROOT_URI,
+                                       false);
+               } catch (InvalidFormatException e) {
+                       // Should never happen in production as all data are fixed
+               }
+               PACKAGE_RELATIONSHIPS_ROOT_PART_NAME = tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME;
+               CORE_PROPERTIES_PART_NAME = tmpCORE_PROPERTIES_URI;
+               PACKAGE_ROOT_PART_NAME = tmpPACKAGE_ROOT_PART_NAME;
+       }
+
+       /**
+        * Gets the URI for the package root.
+        *
+        * @return URI of the package root.
+        */
+       public static URI getPackageRootUri() {
+               return packageRootUri;
+       }
+
+       /**
+        * Know if the specified URI is a relationship part name.
+        *
+        * @param partUri
+        *            URI to check.
+        * @return <i>true</i> if the URI <i>false</i>.
+        */
+       public static boolean isRelationshipPartURI(URI partUri) {
+               if (partUri == null)
+                       throw new IllegalArgumentException("partUri");
+
+               return partUri.getPath().matches(
+                               ".*" + RELATIONSHIP_PART_SEGMENT_NAME + ".*"
+                                               + RELATIONSHIP_PART_EXTENSION_NAME + "$");
+       }
+
+       /**
+        * Get file name from the specified URI.
+        */
+       public static String getFilename(URI uri) {
+               if (uri != null) {
+                       String path = uri.getPath();
+                       int len = path.length();
+                       int num2 = len;
+                       while (--num2 >= 0) {
+                               char ch1 = path.charAt(num2);
+                               if (ch1 == PackagingURIHelper.FORWARD_SLASH_CHAR)
+                                       return path.substring(num2 + 1, len);
+                       }
+               }
+               return "";
+       }
+
+       /**
+        * Get the file name without the trailing extension.
+        */
+       public static String getFilenameWithoutExtension(URI uri) {
+               String filename = getFilename(uri);
+               int dotIndex = filename.lastIndexOf(".");
+               if (dotIndex == -1)
+                       return filename;
+               return filename.substring(0, dotIndex);
+       }
+
+       /**
+        * Get the directory path from the specified URI.
+        */
+       public static URI getPath(URI uri) {
+               if (uri != null) {
+                       String path = uri.getPath();
+                       int len = path.length();
+                       int num2 = len;
+                       while (--num2 >= 0) {
+                               char ch1 = path.charAt(num2);
+                               if (ch1 == PackagingURIHelper.FORWARD_SLASH_CHAR) {
+                                       try {
+                                               return new URI(path.substring(0, num2));
+                                       } catch (URISyntaxException e) {
+                                               return null;
+                                       }
+                               }
+                       }
+               }
+               return null;
+       }
+
+       /**
+        * Combine two URIs.
+        *
+        * @param prefix the prefix URI
+        * @param suffix the suffix URI
+        *
+        * @return the combined URI
+        */
+       public static URI combine(URI prefix, URI suffix) {
+               URI retUri = null;
+               try {
+                       retUri = new URI(combine(prefix.getPath(), suffix.getPath()));
+               } catch (URISyntaxException e) {
+                       throw new IllegalArgumentException(
+                                       "Prefix and suffix can't be combine !");
+               }
+               return retUri;
+       }
+
+       /**
+        * Combine a string URI with a prefix and a suffix.
+        */
+       public static String combine(String prefix, String suffix) {
+               if (!prefix.endsWith("" + FORWARD_SLASH_CHAR)
+                               && !suffix.startsWith("" + FORWARD_SLASH_CHAR))
+                       return prefix + FORWARD_SLASH_CHAR + suffix;
+               else if ((!prefix.endsWith("" + FORWARD_SLASH_CHAR)
+                               && suffix.startsWith("" + FORWARD_SLASH_CHAR) || (prefix
+                               .endsWith("" + FORWARD_SLASH_CHAR) && !suffix.startsWith(""
+                               + FORWARD_SLASH_CHAR))))
+                       return prefix + suffix;
+               else
+                       return "";
+       }
+
+       /**
+        * Fully relativize the source part URI against the target part URI.
+        *
+        * @param sourceURI
+        *            The source part URI.
+        * @param targetURI
+        *            The target part URI.
+        * @return A fully relativize part name URI ('word/media/image1.gif',
+        *         '/word/document.xml' => 'media/image1.gif') else
+        *         <code>null</code>.
+        */
+       public static URI relativizeURI(URI sourceURI, URI targetURI) {
+               StringBuilder retVal = new StringBuilder();
+               String[] segmentsSource = sourceURI.getPath().split("/", -1);
+               String[] segmentsTarget = targetURI.getPath().split("/", -1);
+
+               // If the source URI is empty
+               if (segmentsSource.length == 0) {
+                       throw new IllegalArgumentException(
+                                       "Can't relativize an empty source URI !");
+               }
+
+               // If target URI is empty
+               if (segmentsTarget.length == 0) {
+                       throw new IllegalArgumentException(
+                                       "Can't relativize an empty target URI !");
+               }
+
+               // If the source is the root, then the relativized
+               //  form must actually be an absolute URI
+               if(sourceURI.toString().equals("/")) {
+                       return targetURI;
+               }
+
+
+               // Relativize the source URI against the target URI.
+               // First up, figure out how many steps along we can go
+               // and still have them be the same
+               int segmentsTheSame = 0;
+               for (int i = 0; i < segmentsSource.length && i < segmentsTarget.length; i++) {
+                       if (segmentsSource[i].equals(segmentsTarget[i])) {
+                               // Match so far, good
+                               segmentsTheSame++;
+                       } else {
+                               break;
+                       }
+               }
+
+               // If we didn't have a good match or at least except a first empty element
+               if ((segmentsTheSame == 0 || segmentsTheSame == 1) &&
+                               segmentsSource[0].equals("") && segmentsTarget[0].equals("")) {
+                       for (int i = 0; i < segmentsSource.length - 2; i++) {
+                               retVal.append("../");
+                       }
+                       for (int i = 0; i < segmentsTarget.length; i++) {
+                               if (segmentsTarget[i].equals(""))
+                                       continue;
+                               retVal.append(segmentsTarget[i]);
+                               if (i != segmentsTarget.length - 1)
+                                       retVal.append("/");
+                       }
+
+                       try {
+                               return new URI(retVal.toString());
+                       } catch (Exception e) {
+                               System.err.println(e);
+                               return null;
+                       }
+               }
+
+               // Special case for where the two are the same
+               if (segmentsTheSame == segmentsSource.length
+                               && segmentsTheSame == segmentsTarget.length) {
+                       retVal.append("");
+               } else {
+                       // Matched for so long, but no more
+
+                       // Do we need to go up a directory or two from
+                       // the source to get here?
+                       // (If it's all the way up, then don't bother!)
+                       if (segmentsTheSame == 1) {
+                               retVal.append("/");
+                       } else {
+                               for (int j = segmentsTheSame; j < segmentsSource.length - 1; j++) {
+                                       retVal.append("../");
+                               }
+                       }
+
+                       // Now go from here on down
+                       for (int j = segmentsTheSame; j < segmentsTarget.length; j++) {
+                               if (retVal.length() > 0
+                                               && retVal.charAt(retVal.length() - 1) != '/') {
+                                       retVal.append("/");
+                               }
+                               retVal.append(segmentsTarget[j]);
+                       }
+               }
+
+               try {
+                       return new URI(retVal.toString());
+               } catch (Exception e) {
+                       System.err.println(e);
+                       return null;
+               }
+       }
+
+       /**
+        * Resolve a source uri against a target.
+        *
+        * @param sourcePartUri
+        *            The source URI.
+        * @param targetUri
+        *            The target URI.
+        * @return The resolved URI.
+        */
+       public static URI resolvePartUri(URI sourcePartUri, URI targetUri) {
+               if (sourcePartUri == null || sourcePartUri.isAbsolute()) {
+                       throw new IllegalArgumentException("sourcePartUri invalid - "
+                                       + sourcePartUri);
+               }
+
+               if (targetUri == null || targetUri.isAbsolute()) {
+                       throw new IllegalArgumentException("targetUri invalid - "
+                                       + targetUri);
+               }
+
+               return sourcePartUri.resolve(targetUri);
+       }
+
+       /**
+        * Get URI from a string path.
+        */
+       public static URI getURIFromPath(String path) {
+               URI retUri = null;
+               try {
+                       retUri = new URI(path);
+               } catch (URISyntaxException e) {
+                       throw new IllegalArgumentException("path");
+               }
+               return retUri;
+       }
+
+       /**
+        * Get the source part URI from a specified relationships part.
+        *
+        * @param relationshipPartUri
+        *            The relationship part use to retrieve the source part.
+        * @return The source part URI from the specified relationships part.
+        */
+       public static URI getSourcePartUriFromRelationshipPartUri(
+                       URI relationshipPartUri) {
+               if (relationshipPartUri == null)
+                       throw new IllegalArgumentException(
+                                       "Must not be null");
+
+               if (!isRelationshipPartURI(relationshipPartUri))
+                       throw new IllegalArgumentException(
+                                       "Must be a relationship part");
+
+               if (relationshipPartUri.compareTo(PACKAGE_RELATIONSHIPS_ROOT_URI) == 0)
+                       return PACKAGE_ROOT_URI;
+
+               String filename = relationshipPartUri.getPath();
+               String filenameWithoutExtension = getFilenameWithoutExtension(relationshipPartUri);
+               filename = filename
+                               .substring(0, ((filename.length() - filenameWithoutExtension
+                                               .length()) - RELATIONSHIP_PART_EXTENSION_NAME.length()));
+               filename = filename.substring(0, filename.length()
+                               - RELATIONSHIP_PART_SEGMENT_NAME.length() - 1);
+               filename = combine(filename, filenameWithoutExtension);
+               return getURIFromPath(filename);
+       }
+
+       /**
+        * Create an OPC compliant part name by throwing an exception if the URI is
+        * not valid.
+        *
+        * @param partUri
+        *            The part name URI to validate.
+        * @return A valid part name object, else <code>null</code>.
+        * @throws InvalidFormatException
+        *             Throws if the specified URI is not OPC compliant.
+        */
+       public static PackagePartName createPartName(URI partUri)
+                       throws InvalidFormatException {
+               if (partUri == null)
+                       throw new IllegalArgumentException("partName");
+
+               return new PackagePartName(partUri, true);
+       }
+
+       /**
+        * Create an OPC compliant part name.
+        *
+        * @param partName
+        *            The part name to validate.
+        * @return The correspondant part name if valid, else <code>null</code>.
+        * @throws InvalidFormatException
+        *             Throws if the specified part name is not OPC compliant.
+        * @see #createPartName(URI)
+        */
+       public static PackagePartName createPartName(String partName)
+                       throws InvalidFormatException {
+               URI partNameURI;
+               try {
+                       partNameURI = new URI(partName);
+               } catch (URISyntaxException e) {
+                       throw new InvalidFormatException(e.getMessage());
+               }
+               return createPartName(partNameURI);
+       }
+
+       /**
+        * Create an OPC compliant part name by resolving it using a base part.
+        *
+        * @param partName
+        *            The part name to validate.
+        * @param relativePart
+        *            The relative base part.
+        * @return The correspondant part name if valid, else <code>null</code>.
+        * @throws InvalidFormatException
+        *             Throws if the specified part name is not OPC compliant.
+        * @see #createPartName(URI)
+        */
+       public static PackagePartName createPartName(String partName,
+                       PackagePart relativePart) throws InvalidFormatException {
+               URI newPartNameURI;
+               try {
+                       newPartNameURI = resolvePartUri(
+                                       relativePart.getPartName().getURI(), new URI(partName));
+               } catch (URISyntaxException e) {
+                       throw new InvalidFormatException(e.getMessage());
+               }
+               return createPartName(newPartNameURI);
+       }
+
+       /**
+        * Create an OPC compliant part name by resolving it using a base part.
+        *
+        * @param partName
+        *            The part name URI to validate.
+        * @param relativePart
+        *            The relative base part.
+        * @return The correspondant part name if valid, else <code>null</code>.
+        * @throws InvalidFormatException
+        *             Throws if the specified part name is not OPC compliant.
+        * @see #createPartName(URI)
+        */
+       public static PackagePartName createPartName(URI partName,
+                       PackagePart relativePart) throws InvalidFormatException {
+               URI newPartNameURI = resolvePartUri(
+                               relativePart.getPartName().getURI(), partName);
+               return createPartName(newPartNameURI);
+       }
+
+       /**
+        * Validate a part URI by returning a boolean.
+        * ([M1.1],[M1.3],[M1.4],[M1.5],[M1.6])
+        *
+        * (OPC Specifications 8.1.1 Part names) :
+        *
+        * Part Name Syntax
+        *
+        * The part name grammar is defined as follows:
+        *
+        * <i>part_name = 1*( "/" segment )
+        *
+        * segment = 1*( pchar )</i>
+        *
+        *
+        * (pchar is defined in RFC 3986)
+        *
+        * @param partUri
+        *            The URI to validate.
+        * @return <b>true</b> if the URI is valid to the OPC Specifications, else
+        *         <b>false</b>
+        *
+        * @see #createPartName(URI)
+        */
+       public static boolean isValidPartName(URI partUri) {
+               if (partUri == null)
+                       throw new IllegalArgumentException("partUri");
+
+               try {
+                       createPartName(partUri);
+                       return true;
+               } catch (Exception e) {
+                       return false;
+               }
+       }
+
+       /**
+        * Decode a URI by converting all percent encoded character into a String
+        * character.
+        *
+        * @param uri
+        *            The URI to decode.
+        * @return The specified URI in a String with converted percent encoded
+        *         characters.
+        */
+       public static String decodeURI(URI uri) {
+               StringBuffer retVal = new StringBuffer();
+               String uriStr = uri.toASCIIString();
+               char c;
+               for (int i = 0; i < uriStr.length(); ++i) {
+                       c = uriStr.charAt(i);
+                       if (c == '%') {
+                               // We certainly found an encoded character, check for length
+                               // now ( '%' HEXDIGIT HEXDIGIT)
+                               if (((uriStr.length() - i) < 2)) {
+                                       throw new IllegalArgumentException("The uri " + uriStr
+                                                       + " contain invalid encoded character !");
+                               }
+
+                               // Decode the encoded character
+                               char decodedChar = (char) Integer.parseInt(uriStr.substring(
+                                               i + 1, i + 3), 16);
+                               retVal.append(decodedChar);
+                               i += 2;
+                               continue;
+                       }
+                       retVal.append(c);
+               }
+               return retVal.toString();
+       }
+
+       /**
+        * Build a part name where the relationship should be stored ((ex
+        * /word/document.xml -> /word/_rels/document.xml.rels)
+        *
+        * @param partName
+        *            Source part URI
+        * @return the full path (as URI) of the relation file
+        * @throws InvalidOperationException
+        *             Throws if the specified URI is a relationshp part.
+        */
+       public static PackagePartName getRelationshipPartName(
+                       PackagePartName partName) {
+               if (partName == null)
+                       throw new IllegalArgumentException("partName");
+
+               if (PackagingURIHelper.PACKAGE_ROOT_URI.getPath() == partName.getURI()
+                               .getPath())
+                       return PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME;
+
+               if (partName.isRelationshipPartURI())
+                       throw new InvalidOperationException("Can't be a relationship part");
+
+               String fullPath = partName.getURI().getPath();
+               String filename = getFilename(partName.getURI());
+               fullPath = fullPath.substring(0, fullPath.length() - filename.length());
+               fullPath = combine(fullPath,
+                               PackagingURIHelper.RELATIONSHIP_PART_SEGMENT_NAME);
+               fullPath = combine(fullPath, filename);
+               fullPath = fullPath
+                               + PackagingURIHelper.RELATIONSHIP_PART_EXTENSION_NAME;
+
+               PackagePartName retPartName;
+               try {
+                       retPartName = createPartName(fullPath);
+               } catch (InvalidFormatException e) {
+                       // Should never happen in production as all data are fixed but in
+                       // case of return null:
+                       return null;
+               }
+               return retPartName;
+       }
+}
index 1d55c7bb7fe9e7b652049cdff8b54350cd50837d..a02264ea68aa78c33baeb91364e45d71598d3be0 100755 (executable)
@@ -1,77 +1,77 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-import java.io.InputStream;\r
-import java.io.OutputStream;\r
-\r
-import org.dom4j.Document;\r
-import org.dom4j.io.OutputFormat;\r
-import org.dom4j.io.XMLWriter;\r
-\r
-public final class StreamHelper {\r
-\r
-       private StreamHelper() {\r
-               // Do nothing\r
-       }\r
-\r
-       /**\r
-        * Turning the DOM4j object in the specified output stream.\r
-        * \r
-        * @param xmlContent\r
-        *            The XML document.\r
-        * @param outStream\r
-        *            The OutputStream in which the XML document will be written.\r
-        * @return <b>true</b> if the xml is successfully written in the stream,\r
-        *         else <b>false</b>.\r
-        */\r
-       public static boolean saveXmlInStream(Document xmlContent,\r
-                       OutputStream outStream) {\r
-               try {\r
-                       OutputFormat outformat = OutputFormat.createPrettyPrint();\r
-                       outformat.setEncoding("UTF-8");\r
-                       XMLWriter writer = new XMLWriter(outStream, outformat);\r
-                       writer.write(xmlContent);\r
-               } catch (Exception e) {\r
-                       return false;\r
-               }\r
-               return true;\r
-       }\r
-\r
-       /**\r
-        * Copy the input stream into the output stream.\r
-        * \r
-        * @param inStream\r
-        *            The source stream.\r
-        * @param outStream\r
-        *            The destination stream.\r
-        * @return <b>true</b> if the operation succeed, else return <b>false</b>.\r
-        */\r
-       public static boolean copyStream(InputStream inStream, OutputStream outStream) {\r
-               try {\r
-                       byte[] buffer = new byte[1024];\r
-                       int bytesRead;\r
-                       while ((bytesRead = inStream.read(buffer)) >= 0) {\r
-                               outStream.write(buffer, 0, bytesRead);\r
-                       }\r
-               } catch (Exception e) {\r
-                       return false;\r
-               }\r
-               return true;\r
-       }\r
-}\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.openxml4j.opc;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.dom4j.Document;
+import org.dom4j.io.OutputFormat;
+import org.dom4j.io.XMLWriter;
+
+public final class StreamHelper {
+
+       private StreamHelper() {
+               // Do nothing
+       }
+
+       /**
+        * Turning the DOM4j object in the specified output stream.
+        *
+        * @param xmlContent
+        *            The XML document.
+        * @param outStream
+        *            The OutputStream in which the XML document will be written.
+        * @return <b>true</b> if the xml is successfully written in the stream,
+        *         else <b>false</b>.
+        */
+       public static boolean saveXmlInStream(Document xmlContent,
+                       OutputStream outStream) {
+               try {
+                       OutputFormat outformat = OutputFormat.createPrettyPrint();
+                       outformat.setEncoding("UTF-8");
+                       XMLWriter writer = new XMLWriter(outStream, outformat);
+                       writer.write(xmlContent);
+               } catch (Exception e) {
+                       return false;
+               }
+               return true;
+       }
+
+       /**
+        * Copy the input stream into the output stream.
+        *
+        * @param inStream
+        *            The source stream.
+        * @param outStream
+        *            The destination stream.
+        * @return <b>true</b> if the operation succeed, else return <b>false</b>.
+        */
+       public static boolean copyStream(InputStream inStream, OutputStream outStream) {
+               try {
+                       byte[] buffer = new byte[1024];
+                       int bytesRead;
+                       while ((bytesRead = inStream.read(buffer)) >= 0) {
+                               outStream.write(buffer, 0, bytesRead);
+                       }
+               } catch (Exception e) {
+                       return false;
+               }
+               return true;
+       }
+}
index 12a5a55ffa544f545e5d829b977a16c97d989621..834c2ad66e0e71321064808cf36ad30b378bb829 100755 (executable)
@@ -1,32 +1,32 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-/**\r
- * Specifies whether the target of a PackageRelationship is inside or outside a\r
- * Package.\r
- * \r
- * @author Julien Chable\r
- * @version 1.0\r
- */\r
-public enum TargetMode {\r
-       /** The relationship references a resource that is external to the package. */\r
-       INTERNAL,\r
-       /** The relationship references a part that is inside the package. */\r
-       EXTERNAL\r
-}\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.openxml4j.opc;
+
+/**
+ * Specifies whether the target of a PackageRelationship is inside or outside a
+ * Package.
+ *
+ * @author Julien Chable
+ * @version 1.0
+ */
+public enum TargetMode {
+       /** The relationship references a resource that is external to the package. */
+       INTERNAL,
+       /** The relationship references a part that is inside the package. */
+       EXTERNAL
+}
index f3e9a578cedc38375a5f920aec289076925ccbbf..6e676cc9b26f0c480979e2a7961705e30f370a6e 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc;\r
-\r
-import java.io.File;\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.io.OutputStream;\r
-import java.net.URI;\r
-import java.util.Enumeration;\r
-import java.util.zip.ZipEntry;\r
-import java.util.zip.ZipFile;\r
-import java.util.zip.ZipInputStream;\r
-import java.util.zip.ZipOutputStream;\r
-\r
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;\r
-import org.apache.poi.openxml4j.exceptions.InvalidOperationException;\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;\r
-import org.apache.poi.openxml4j.opc.internal.FileHelper;\r
-import org.apache.poi.openxml4j.opc.internal.MemoryPackagePart;\r
-import org.apache.poi.openxml4j.opc.internal.PartMarshaller;\r
-import org.apache.poi.openxml4j.opc.internal.ZipContentTypeManager;\r
-import org.apache.poi.openxml4j.opc.internal.ZipHelper;\r
-import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPackagePropertiesMarshaller;\r
-import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPartMarshaller;\r
-import org.apache.poi.openxml4j.util.ZipEntrySource;\r
-import org.apache.poi.openxml4j.util.ZipFileZipEntrySource;\r
-import org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource;\r
-import org.apache.poi.util.POILogger;\r
-import org.apache.poi.util.POILogFactory;\r
-\r
-/**\r
- * Physical zip package.\r
- * \r
- * @author Julien Chable\r
- * @version 0.2\r
- */\r
-public final class ZipPackage extends Package {\r
-\r
-    private static POILogger logger = POILogFactory.getLogger(ZipPackage.class);\r
-\r
-       /**\r
-        * Zip archive, as either a file on disk,\r
-        *  or a stream \r
-        */\r
-       private final ZipEntrySource zipArchive;\r
-\r
-       /**\r
-        * Constructor. Creates a new ZipPackage.\r
-        */\r
-       public ZipPackage() {\r
-               super(defaultPackageAccess);\r
-               this.zipArchive = null;\r
-       }\r
-\r
-       /**\r
-        * Constructor. <b>Operation not supported.</b>\r
-        * \r
-        * @param in\r
-        *            Zip input stream to load.\r
-        * @param access\r
-        * @throws IllegalArgumentException\r
-        *             If the specified input stream not an instance of\r
-        *             ZipInputStream.\r
-        */\r
-       ZipPackage(InputStream in, PackageAccess access) throws IOException {\r
-               super(access);\r
-               this.zipArchive = new ZipInputStreamZipEntrySource(\r
-                               new ZipInputStream(in)\r
-               );\r
-       }\r
-\r
-       /**\r
-        * Constructor. Opens a Zip based Open XML document.\r
-        * \r
-        * @param path\r
-        *            The path of the file to open or create.\r
-        * @param access\r
-        *            The package access mode.\r
-        * @throws InvalidFormatException\r
-        *             If the content type part parsing encounters an error.\r
-        */\r
-       ZipPackage(String path, PackageAccess access) throws InvalidFormatException {\r
-               super(access);\r
-               \r
-               ZipFile zipFile = ZipHelper.openZipFile(path);\r
-               if (zipFile == null)\r
-                       throw new InvalidOperationException(\r
-                                       "Can't open the specified file: '" + path + "'");\r
-               this.zipArchive = new ZipFileZipEntrySource(zipFile); \r
-       }\r
-       \r
-       /**\r
-        * Retrieves the parts from this package. We assume that the package has not\r
-        * been yet inspect to retrieve all the parts, this method will open the\r
-        * archive and look for all parts contain inside it. If the package part\r
-        * list is not empty, it will be emptied.\r
-        * \r
-        * @return All parts contain in this package.\r
-        * @throws InvalidFormatException\r
-        *             Throws if the package is not valid.\r
-        */\r
-       @Override\r
-       protected PackagePart[] getPartsImpl() throws InvalidFormatException {\r
-               if (this.partList == null) {\r
-                       // The package has just been created, we create an empty part\r
-                       // list.\r
-                       this.partList = new PackagePartCollection();\r
-               }\r
-\r
-               if (this.zipArchive == null) {\r
-                       return this.partList.values().toArray(\r
-                                       new PackagePart[this.partList.values().size()]);\r
-               } else {\r
-                       // First we need to parse the content type part\r
-                       Enumeration<? extends ZipEntry> entries = this.zipArchive.getEntries();\r
-                       while (entries.hasMoreElements()) {\r
-                               ZipEntry entry = entries.nextElement();\r
-                               if (entry.getName().equals(\r
-                                               ContentTypeManager.CONTENT_TYPES_PART_NAME)) {\r
-                                       try {\r
-                                               this.contentTypeManager = new ZipContentTypeManager(\r
-                                                               getZipArchive().getInputStream(entry), this);\r
-                                       } catch (IOException e) {\r
-                                               throw new InvalidFormatException(e.getMessage());\r
-                                       }\r
-                                       break;\r
-                               }\r
-                       }\r
-\r
-                       // At this point, we should have loaded the content type part\r
-                       if (this.contentTypeManager == null) {\r
-                               throw new InvalidFormatException(\r
-                                               "Package should contain a content type part [M1.13]");\r
-                       }\r
-                       \r
-                       // Now create all the relationships\r
-                       // (Need to create relationships before other\r
-                       //  parts, otherwise we might create a part before\r
-                       //  its relationship exists, and then it won't tie up)\r
-                       entries = this.zipArchive.getEntries();\r
-                       while (entries.hasMoreElements()) {\r
-                               ZipEntry entry = (ZipEntry) entries.nextElement();\r
-                               PackagePartName partName = buildPartName(entry);\r
-                               if(partName == null) continue;\r
-                               \r
-                               // Only proceed for Relationships at this stage\r
-                               String contentType = contentTypeManager.getContentType(partName);\r
-                               if (contentType != null && contentType.equals(ContentTypes.RELATIONSHIPS_PART)) {\r
-                                       try {\r
-                                               partList.put(partName, new ZipPackagePart(this, entry,\r
-                                                       partName, contentType));\r
-                                       } catch (InvalidOperationException e) {\r
-                                               throw new InvalidFormatException(e.getMessage());\r
-                                       }\r
-                               }\r
-                       }\r
-\r
-                       // Then we can go through all the other parts\r
-                       entries = this.zipArchive.getEntries();\r
-                       while (entries.hasMoreElements()) {\r
-                               ZipEntry entry = (ZipEntry) entries.nextElement();\r
-                               PackagePartName partName = buildPartName(entry);\r
-                               if(partName == null) continue;\r
-\r
-                               String contentType = contentTypeManager\r
-                                               .getContentType(partName);\r
-                               if (contentType != null && contentType.equals(ContentTypes.RELATIONSHIPS_PART)) {\r
-                                       // Already handled\r
-                               }\r
-                               else if (contentType != null) {\r
-                                       try {\r
-                                               partList.put(partName, new ZipPackagePart(this, entry,\r
-                                                               partName, contentType));\r
-                                       } catch (InvalidOperationException e) {\r
-                                               throw new InvalidFormatException(e.getMessage());\r
-                                       }\r
-                               } else {\r
-                                       throw new InvalidFormatException(\r
-                                                       "The part "\r
-                                                                       + partName.getURI().getPath()\r
-                                                                       + " does not have any content type ! Rule: Package require content types when retrieving a part from a package. [M.1.14]");\r
-                               }\r
-                       }\r
-                       \r
-                       return (ZipPackagePart[]) partList.values().toArray(\r
-                                       new ZipPackagePart[partList.size()]);\r
-               }\r
-       }\r
-       \r
-       /**\r
-        * Builds a PackagePartName for the given ZipEntry,\r
-        *  or null if it's the content types / invalid part\r
-        */\r
-       private PackagePartName buildPartName(ZipEntry entry) {\r
-               try {\r
-                       // We get an error when we parse [Content_Types].xml\r
-                       // because it's not a valid URI.\r
-                       if (entry.getName().equals(\r
-                                       ContentTypeManager.CONTENT_TYPES_PART_NAME)) {\r
-                               return null;\r
-                       } else {\r
-                               return PackagingURIHelper.createPartName(ZipHelper\r
-                                               .getOPCNameFromZipItemName(entry.getName()));\r
-                       }\r
-               } catch (Exception e) {\r
-                       // We assume we can continue, even in degraded mode ...\r
-                       logger.log(POILogger.WARN,"Entry "\r
-                                                       + entry.getName()\r
-                                                       + " is not valid, so this part won't be add to the package.");\r
-                       return null;\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Create a new MemoryPackagePart from the specified URI and content type\r
-        * \r
-        * \r
-        * aram partName The part URI.\r
-        * \r
-        * @param contentType\r
-        *            The part content type.\r
-        * @return The newly created zip package part, else <b>null</b>.\r
-        */\r
-       @Override\r
-       protected PackagePart createPartImpl(PackagePartName partName,\r
-                       String contentType, boolean loadRelationships) {\r
-               if (contentType == null)\r
-                       throw new IllegalArgumentException("contentType");\r
-\r
-               if (partName == null)\r
-                       throw new IllegalArgumentException("partName");\r
-\r
-               try {\r
-                       return new MemoryPackagePart(this, partName, contentType,\r
-                                       loadRelationships);\r
-               } catch (InvalidFormatException e) {\r
-                       // TODO - don't use system.err.  Is it valid to return null when this exception occurs?\r
-                       System.err.println(e); \r
-                       return null;\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Delete a part from the package\r
-        * \r
-        * @throws IllegalArgumentException\r
-        *             Throws if the part URI is nulll or invalid.\r
-        */\r
-       @Override\r
-       protected void removePartImpl(PackagePartName partName) {\r
-               if (partName == null)\r
-                       throw new IllegalArgumentException("partUri");\r
-       }\r
-\r
-       /**\r
-        * Flush the package. Do nothing.\r
-        */\r
-       @Override\r
-       protected void flushImpl() {\r
-               // Do nothing\r
-       }\r
-\r
-       /**\r
-        * Close and save the package.\r
-        * \r
-        * @see #close()\r
-        */\r
-       @Override\r
-       protected void closeImpl() throws IOException {\r
-               // Flush the package\r
-               flush();\r
-\r
-               // Save the content\r
-               if (this.originalPackagePath != null\r
-                               && !"".equals(this.originalPackagePath)) {\r
-                       File targetFile = new File(this.originalPackagePath);\r
-                       if (targetFile.exists()) {\r
-                               // Case of a package previously open\r
-\r
-                               File tempFile = File.createTempFile(\r
-                                               generateTempFileName(FileHelper\r
-                                                               .getDirectory(targetFile)), ".tmp");\r
-\r
-                               // Save the final package to a temporary file\r
-                               try {\r
-                                       save(tempFile);\r
-                                       this.zipArchive.close(); // Close the zip archive to be\r
-                                       // able to delete it\r
-                                       FileHelper.copyFile(tempFile, targetFile);\r
-                               } finally {\r
-                                       // Either the save operation succeed or not, we delete the\r
-                                       // temporary file\r
-                                       if (!tempFile.delete()) {\r
-                                               logger\r
-                                                               .log(POILogger.WARN,"The temporary file: '"\r
-                                                                               + targetFile.getAbsolutePath()\r
-                                                                               + "' cannot be deleted ! Make sure that no other application use it.");\r
-                                       }\r
-                               }\r
-                       } else {\r
-                               throw new InvalidOperationException(\r
-                                               "Can't close a package not previously open with the open() method !");\r
-                       }\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Create a unique identifier to be use as a temp file name.\r
-        * \r
-        * @return A unique identifier use to be use as a temp file name.\r
-        */\r
-       private synchronized String generateTempFileName(File directory) {\r
-               File tmpFilename;\r
-               do {\r
-                       tmpFilename = new File(directory.getAbsoluteFile() + File.separator\r
-                                       + "OpenXML4J" + System.nanoTime());\r
-               } while (tmpFilename.exists());\r
-               return FileHelper.getFilename(tmpFilename.getAbsoluteFile());\r
-       }\r
-\r
-       /**\r
-        * Close the package without saving the document. Discard all the changes\r
-        * made to this package.\r
-        */\r
-       @Override\r
-       protected void revertImpl() {\r
-               try {\r
-                       if (this.zipArchive != null)\r
-                               this.zipArchive.close();\r
-               } catch (IOException e) {\r
-                       // Do nothing, user dont have to know\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Implement the getPart() method to retrieve a part from its URI in the\r
-        * current package\r
-        * \r
-        * \r
-        * @see #getPart(PackageRelationship)\r
-        */\r
-       @Override\r
-       protected PackagePart getPartImpl(PackagePartName partName) {\r
-               if (partList.containsKey(partName)) {\r
-                       return partList.get(partName);\r
-               }\r
-               return null;\r
-       }\r
-\r
-       /**\r
-        * Save this package into the specified stream\r
-        * \r
-        * \r
-        * @param outputStream\r
-        *            The stream use to save this package.\r
-        * \r
-        * @see #save(OutputStream)\r
-        */\r
-       @Override\r
-       public void saveImpl(OutputStream outputStream) {\r
-               // Check that the document was open in write mode\r
-               throwExceptionIfReadOnly();\r
-               ZipOutputStream zos = null;\r
-\r
-               try {\r
-                       if (!(outputStream instanceof ZipOutputStream))\r
-                               zos = new ZipOutputStream(outputStream);\r
-                       else\r
-                               zos = (ZipOutputStream) outputStream;\r
-\r
-                       // If the core properties part does not exist in the part list,\r
-                       // we save it as well\r
-                       if (this.getPartsByRelationshipType(\r
-                                       PackageRelationshipTypes.CORE_PROPERTIES).size() == 0) {\r
-                               logger.log(POILogger.DEBUG,"Save core properties part");\r
-\r
-                               // We have to save the core properties part ...\r
-                               new ZipPackagePropertiesMarshaller().marshall(\r
-                                               this.packageProperties, zos);\r
-                               // ... and to add its relationship ...\r
-                               this.relationships.addRelationship(this.packageProperties\r
-                                               .getPartName().getURI(), TargetMode.INTERNAL,\r
-                                               PackageRelationshipTypes.CORE_PROPERTIES, null);\r
-                               // ... and the content if it has not been added yet.\r
-                               if (!this.contentTypeManager\r
-                                               .isContentTypeRegister(ContentTypes.CORE_PROPERTIES_PART)) {\r
-                                       this.contentTypeManager.addContentType(\r
-                                                       this.packageProperties.getPartName(),\r
-                                                       ContentTypes.CORE_PROPERTIES_PART);\r
-                               }\r
-                       }\r
-\r
-                       // Save package relationships part.\r
-                       logger.log(POILogger.DEBUG,"Save package relationships");\r
-                       ZipPartMarshaller.marshallRelationshipPart(this.getRelationships(),\r
-                                       PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME,\r
-                                       zos);\r
-\r
-                       // Save content type part.\r
-                       logger.log(POILogger.DEBUG,"Save content types part");\r
-                       this.contentTypeManager.save(zos);\r
-\r
-                       // Save parts.\r
-                       for (PackagePart part : getParts()) {\r
-                               // If the part is a relationship part, we don't save it, it's\r
-                               // the source part that will do the job.\r
-                               if (part.isRelationshipPart())\r
-                                       continue;\r
-\r
-                               logger.log(POILogger.DEBUG,"Save part '"\r
-                                               + ZipHelper.getZipItemNameFromOPCName(part\r
-                                                               .getPartName().getName()) + "'");\r
-                               PartMarshaller marshaller = partMarshallers\r
-                                               .get(part.contentType);\r
-                               if (marshaller != null) {\r
-                                       if (!marshaller.marshall(part, zos)) {\r
-                                               throw new OpenXML4JException(\r
-                                                               "The part "\r
-                                                                               + part.getPartName().getURI()\r
-                                                                               + " fail to be saved in the stream with marshaller "\r
-                                                                               + marshaller);\r
-                                       }\r
-                               } else {\r
-                                       if (!defaultPartMarshaller.marshall(part, zos))\r
-                                               throw new OpenXML4JException(\r
-                                                               "The part "\r
-                                                                               + part.getPartName().getURI()\r
-                                                                               + " fail to be saved in the stream with marshaller "\r
-                                                                               + defaultPartMarshaller);\r
-                               }\r
-                       }\r
-                       zos.close();\r
-               } catch (Exception e) {\r
-                       logger\r
-                                       .log(POILogger.ERROR,"Fail to save: an error occurs while saving the package : "\r
-                                                       + e.getMessage());\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Get the zip archive\r
-        * \r
-        * @return The zip archive.\r
-        */\r
-       public ZipEntrySource getZipArchive() {\r
-               return zipArchive;\r
-       }\r
-}\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.openxml4j.opc;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Enumeration;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
+import org.apache.poi.openxml4j.opc.internal.FileHelper;
+import org.apache.poi.openxml4j.opc.internal.MemoryPackagePart;
+import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
+import org.apache.poi.openxml4j.opc.internal.ZipContentTypeManager;
+import org.apache.poi.openxml4j.opc.internal.ZipHelper;
+import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPackagePropertiesMarshaller;
+import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPartMarshaller;
+import org.apache.poi.openxml4j.util.ZipEntrySource;
+import org.apache.poi.openxml4j.util.ZipFileZipEntrySource;
+import org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource;
+import org.apache.poi.util.POILogger;
+import org.apache.poi.util.POILogFactory;
+
+/**
+ * Physical zip package.
+ *
+ * @author Julien Chable
+ */
+public final class ZipPackage extends Package {
+
+       private static POILogger logger = POILogFactory.getLogger(ZipPackage.class);
+
+       /**
+        * Zip archive, as either a file on disk,
+        *  or a stream
+        */
+       private final ZipEntrySource zipArchive;
+
+       /**
+        * Constructor. Creates a new ZipPackage.
+        */
+       public ZipPackage() {
+               super(defaultPackageAccess);
+               this.zipArchive = null;
+       }
+
+       /**
+        * Constructor. <b>Operation not supported.</b>
+        *
+        * @param in
+        *            Zip input stream to load.
+        * @param access
+        * @throws IllegalArgumentException
+        *             If the specified input stream not an instance of
+        *             ZipInputStream.
+        */
+       ZipPackage(InputStream in, PackageAccess access) throws IOException {
+               super(access);
+               this.zipArchive = new ZipInputStreamZipEntrySource(
+                               new ZipInputStream(in)
+               );
+       }
+
+       /**
+        * Constructor. Opens a Zip based Open XML document.
+        *
+        * @param path
+        *            The path of the file to open or create.
+        * @param access
+        *            The package access mode.
+        * @throws InvalidFormatException
+        *             If the content type part parsing encounters an error.
+        */
+       ZipPackage(String path, PackageAccess access) throws InvalidFormatException {
+               super(access);
+
+               ZipFile zipFile = ZipHelper.openZipFile(path);
+               if (zipFile == null)
+                       throw new InvalidOperationException(
+                                       "Can't open the specified file: '" + path + "'");
+               this.zipArchive = new ZipFileZipEntrySource(zipFile);
+       }
+
+       /**
+        * Retrieves the parts from this package. We assume that the package has not
+        * been yet inspect to retrieve all the parts, this method will open the
+        * archive and look for all parts contain inside it. If the package part
+        * list is not empty, it will be emptied.
+        *
+        * @return All parts contain in this package.
+        * @throws InvalidFormatException
+        *             Throws if the package is not valid.
+        */
+       @Override
+       protected PackagePart[] getPartsImpl() throws InvalidFormatException {
+               if (this.partList == null) {
+                       // The package has just been created, we create an empty part
+                       // list.
+                       this.partList = new PackagePartCollection();
+               }
+
+               if (this.zipArchive == null) {
+                       return this.partList.values().toArray(
+                                       new PackagePart[this.partList.values().size()]);
+               }
+               // First we need to parse the content type part
+               Enumeration<? extends ZipEntry> entries = this.zipArchive.getEntries();
+               while (entries.hasMoreElements()) {
+                       ZipEntry entry = entries.nextElement();
+                       if (entry.getName().equals(
+                                       ContentTypeManager.CONTENT_TYPES_PART_NAME)) {
+                               try {
+                                       this.contentTypeManager = new ZipContentTypeManager(
+                                                       getZipArchive().getInputStream(entry), this);
+                               } catch (IOException e) {
+                                       throw new InvalidFormatException(e.getMessage());
+                               }
+                               break;
+                       }
+               }
+
+               // At this point, we should have loaded the content type part
+               if (this.contentTypeManager == null) {
+                       throw new InvalidFormatException(
+                                       "Package should contain a content type part [M1.13]");
+               }
+
+               // Now create all the relationships
+               // (Need to create relationships before other
+               //  parts, otherwise we might create a part before
+               //  its relationship exists, and then it won't tie up)
+               entries = this.zipArchive.getEntries();
+               while (entries.hasMoreElements()) {
+                       ZipEntry entry = entries.nextElement();
+                       PackagePartName partName = buildPartName(entry);
+                       if(partName == null) continue;
+
+                       // Only proceed for Relationships at this stage
+                       String contentType = contentTypeManager.getContentType(partName);
+                       if (contentType != null && contentType.equals(ContentTypes.RELATIONSHIPS_PART)) {
+                               try {
+                                       partList.put(partName, new ZipPackagePart(this, entry,
+                                               partName, contentType));
+                               } catch (InvalidOperationException e) {
+                                       throw new InvalidFormatException(e.getMessage());
+                               }
+                       }
+               }
+
+               // Then we can go through all the other parts
+               entries = this.zipArchive.getEntries();
+               while (entries.hasMoreElements()) {
+                       ZipEntry entry = entries.nextElement();
+                       PackagePartName partName = buildPartName(entry);
+                       if(partName == null) continue;
+
+                       String contentType = contentTypeManager
+                                       .getContentType(partName);
+                       if (contentType != null && contentType.equals(ContentTypes.RELATIONSHIPS_PART)) {
+                               // Already handled
+                       }
+                       else if (contentType != null) {
+                               try {
+                                       partList.put(partName, new ZipPackagePart(this, entry,
+                                                       partName, contentType));
+                               } catch (InvalidOperationException e) {
+                                       throw new InvalidFormatException(e.getMessage());
+                               }
+                       } else {
+                               throw new InvalidFormatException(
+                                               "The part "
+                                                               + partName.getURI().getPath()
+                                                               + " does not have any content type ! Rule: Package require content types when retrieving a part from a package. [M.1.14]");
+                       }
+               }
+
+               return partList.values().toArray(new ZipPackagePart[partList.size()]);
+       }
+
+       /**
+        * Builds a PackagePartName for the given ZipEntry,
+        *  or null if it's the content types / invalid part
+        */
+       private PackagePartName buildPartName(ZipEntry entry) {
+               try {
+                       // We get an error when we parse [Content_Types].xml
+                       // because it's not a valid URI.
+                       if (entry.getName().equals(
+                                       ContentTypeManager.CONTENT_TYPES_PART_NAME)) {
+                               return null;
+                       }
+                       return PackagingURIHelper.createPartName(ZipHelper
+                                       .getOPCNameFromZipItemName(entry.getName()));
+               } catch (Exception e) {
+                       // We assume we can continue, even in degraded mode ...
+                       logger.log(POILogger.WARN,"Entry "
+                                                       + entry.getName()
+                                                       + " is not valid, so this part won't be add to the package.");
+                       return null;
+               }
+       }
+
+       /**
+        * Create a new MemoryPackagePart from the specified URI and content type
+        *
+        *
+        * aram partName The part URI.
+        *
+        * @param contentType
+        *            The part content type.
+        * @return The newly created zip package part, else <b>null</b>.
+        */
+       @Override
+       protected PackagePart createPartImpl(PackagePartName partName,
+                       String contentType, boolean loadRelationships) {
+               if (contentType == null)
+                       throw new IllegalArgumentException("contentType");
+
+               if (partName == null)
+                       throw new IllegalArgumentException("partName");
+
+               try {
+                       return new MemoryPackagePart(this, partName, contentType,
+                                       loadRelationships);
+               } catch (InvalidFormatException e) {
+                       // TODO - don't use system.err.  Is it valid to return null when this exception occurs?
+                       System.err.println(e);
+                       return null;
+               }
+       }
+
+       /**
+        * Delete a part from the package
+        *
+        * @throws IllegalArgumentException
+        *             Throws if the part URI is nulll or invalid.
+        */
+       @Override
+       protected void removePartImpl(PackagePartName partName) {
+               if (partName == null)
+                       throw new IllegalArgumentException("partUri");
+       }
+
+       /**
+        * Flush the package. Do nothing.
+        */
+       @Override
+       protected void flushImpl() {
+               // Do nothing
+       }
+
+       /**
+        * Close and save the package.
+        *
+        * @see #close()
+        */
+       @Override
+       protected void closeImpl() throws IOException {
+               // Flush the package
+               flush();
+
+               // Save the content
+               if (this.originalPackagePath != null
+                               && !"".equals(this.originalPackagePath)) {
+                       File targetFile = new File(this.originalPackagePath);
+                       if (targetFile.exists()) {
+                               // Case of a package previously open
+
+                               File tempFile = File.createTempFile(
+                                               generateTempFileName(FileHelper
+                                                               .getDirectory(targetFile)), ".tmp");
+
+                               // Save the final package to a temporary file
+                               try {
+                                       save(tempFile);
+                                       this.zipArchive.close(); // Close the zip archive to be
+                                       // able to delete it
+                                       FileHelper.copyFile(tempFile, targetFile);
+                               } finally {
+                                       // Either the save operation succeed or not, we delete the
+                                       // temporary file
+                                       if (!tempFile.delete()) {
+                                               logger
+                                                               .log(POILogger.WARN,"The temporary file: '"
+                                                                               + targetFile.getAbsolutePath()
+                                                                               + "' cannot be deleted ! Make sure that no other application use it.");
+                                       }
+                               }
+                       } else {
+                               throw new InvalidOperationException(
+                                               "Can't close a package not previously open with the open() method !");
+                       }
+               }
+       }
+
+       /**
+        * Create a unique identifier to be use as a temp file name.
+        *
+        * @return A unique identifier use to be use as a temp file name.
+        */
+       private synchronized String generateTempFileName(File directory) {
+               File tmpFilename;
+               do {
+                       tmpFilename = new File(directory.getAbsoluteFile() + File.separator
+                                       + "OpenXML4J" + System.nanoTime());
+               } while (tmpFilename.exists());
+               return FileHelper.getFilename(tmpFilename.getAbsoluteFile());
+       }
+
+       /**
+        * Close the package without saving the document. Discard all the changes
+        * made to this package.
+        */
+       @Override
+       protected void revertImpl() {
+               try {
+                       if (this.zipArchive != null)
+                               this.zipArchive.close();
+               } catch (IOException e) {
+                       // Do nothing, user dont have to know
+               }
+       }
+
+       /**
+        * Implement the getPart() method to retrieve a part from its URI in the
+        * current package
+        *
+        *
+        * @see #getPart(PackageRelationship)
+        */
+       @Override
+       protected PackagePart getPartImpl(PackagePartName partName) {
+               if (partList.containsKey(partName)) {
+                       return partList.get(partName);
+               }
+               return null;
+       }
+
+       /**
+        * Save this package into the specified stream
+        *
+        *
+        * @param outputStream
+        *            The stream use to save this package.
+        *
+        * @see #save(OutputStream)
+        */
+       @Override
+       public void saveImpl(OutputStream outputStream) {
+               // Check that the document was open in write mode
+               throwExceptionIfReadOnly();
+               ZipOutputStream zos = null;
+
+               try {
+                       if (!(outputStream instanceof ZipOutputStream))
+                               zos = new ZipOutputStream(outputStream);
+                       else
+                               zos = (ZipOutputStream) outputStream;
+
+                       // If the core properties part does not exist in the part list,
+                       // we save it as well
+                       if (this.getPartsByRelationshipType(
+                                       PackageRelationshipTypes.CORE_PROPERTIES).size() == 0) {
+                               logger.log(POILogger.DEBUG,"Save core properties part");
+
+                               // We have to save the core properties part ...
+                               new ZipPackagePropertiesMarshaller().marshall(
+                                               this.packageProperties, zos);
+                               // ... and to add its relationship ...
+                               this.relationships.addRelationship(this.packageProperties
+                                               .getPartName().getURI(), TargetMode.INTERNAL,
+                                               PackageRelationshipTypes.CORE_PROPERTIES, null);
+                               // ... and the content if it has not been added yet.
+                               if (!this.contentTypeManager
+                                               .isContentTypeRegister(ContentTypes.CORE_PROPERTIES_PART)) {
+                                       this.contentTypeManager.addContentType(
+                                                       this.packageProperties.getPartName(),
+                                                       ContentTypes.CORE_PROPERTIES_PART);
+                               }
+                       }
+
+                       // Save package relationships part.
+                       logger.log(POILogger.DEBUG,"Save package relationships");
+                       ZipPartMarshaller.marshallRelationshipPart(this.getRelationships(),
+                                       PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME,
+                                       zos);
+
+                       // Save content type part.
+                       logger.log(POILogger.DEBUG,"Save content types part");
+                       this.contentTypeManager.save(zos);
+
+                       // Save parts.
+                       for (PackagePart part : getParts()) {
+                               // If the part is a relationship part, we don't save it, it's
+                               // the source part that will do the job.
+                               if (part.isRelationshipPart())
+                                       continue;
+
+                               logger.log(POILogger.DEBUG,"Save part '"
+                                               + ZipHelper.getZipItemNameFromOPCName(part
+                                                               .getPartName().getName()) + "'");
+                               PartMarshaller marshaller = partMarshallers
+                                               .get(part.contentType);
+                               if (marshaller != null) {
+                                       if (!marshaller.marshall(part, zos)) {
+                                               throw new OpenXML4JException(
+                                                               "The part "
+                                                                               + part.getPartName().getURI()
+                                                                               + " fail to be saved in the stream with marshaller "
+                                                                               + marshaller);
+                                       }
+                               } else {
+                                       if (!defaultPartMarshaller.marshall(part, zos))
+                                               throw new OpenXML4JException(
+                                                               "The part "
+                                                                               + part.getPartName().getURI()
+                                                                               + " fail to be saved in the stream with marshaller "
+                                                                               + defaultPartMarshaller);
+                               }
+                       }
+                       zos.close();
+               } catch (Exception e) {
+                       logger
+                                       .log(POILogger.ERROR,"Fail to save: an error occurs while saving the package : "
+                                                       + e.getMessage());
+               }
+       }
+
+       /**
+        * Get the zip archive
+        *
+        * @return The zip archive.
+        */
+       public ZipEntrySource getZipArchive() {
+               return zipArchive;
+       }
+}
index 5f40940b47310e8b607e2bedfc6296565e510c5c..ecf45af5497ea72e3c5ca4506586076fae953c2a 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal;\r
-\r
-import java.io.UnsupportedEncodingException;\r
-import java.util.Hashtable;\r
-import java.util.regex.Matcher;\r
-import java.util.regex.Pattern;\r
-\r
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;\r
-\r
-/**\r
- * Represents a immutable MIME ContentType value (RFC 2616 &#167;3.7)\r
- * <p>\r
- * media-type = type "/" subtype *( ";" parameter ) type = token<br>\r
- * subtype = token<br>\r
- * </p><p>\r
- * Rule M1.13 : Package implementers shall only create and only recognize parts\r
- * with a content type; format designers shall specify a content type for each\r
- * part included in the format. Content types for package parts shall fit the\r
- * definition and syntax for media types as specified in RFC 2616, \&#167;3.7.\r
- * </p><p>\r
- * Rule M1.14: Content types shall not use linear white space either between the\r
- * type and subtype or between an attribute and its value. Content types also\r
- * shall not have leading or trailing white spaces. Package implementers shall\r
- * create only such content types and shall require such content types when\r
- * retrieving a part from a package; format designers shall specify only such\r
- * content types for inclusion in the format.\r
- * </p>\r
- * @author Julien Chable\r
- * @version 0.1\r
- * \r
- * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">http://www.ietf.org/rfc/rfc2045.txt</a>\r
- * @see <a href="http://www.ietf.org/rfc/rfc2616.txt">http://www.ietf.org/rfc/rfc2616.txt</a>\r
- */\r
-public final class ContentType {\r
-\r
-       /**\r
-        * Type in Type/Subtype.\r
-        */\r
-       private String type;\r
-\r
-       /**\r
-        * Subtype\r
-        */\r
-       private String subType;\r
-\r
-       /**\r
-        * Parameters\r
-        */\r
-       private Hashtable<String, String> parameters;\r
-\r
-       /**\r
-        * Media type compiled pattern for parameters.\r
-        */\r
-       private final static Pattern patternMediaType;\r
-\r
-       static {\r
-               /*\r
-                * token = 1*<any CHAR except CTLs or separators>\r
-                * \r
-                * separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" |\r
-                * <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT\r
-                * \r
-                * CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>\r
-                * \r
-                * CHAR = <any US-ASCII character (octets 0 - 127)>\r
-                */\r
-               String token = "[\\x21-\\x7E&&[^\\(\\)<>@,;:\\\\/\"\\[\\]\\?={}\\x20\\x09]]";\r
-\r
-               /*\r
-                * parameter = attribute "=" value\r
-                * \r
-                * attribute = token\r
-                * \r
-                * value = token | quoted-string\r
-                */\r
-               // Keep for future use with parameter:\r
-               // String parameter = "(" + token + "+)=(\"?" + token + "+\"?)";\r
-               /*\r
-                * Pattern for media type.\r
-                * \r
-                * Don't allow comment, rule M1.15: The package implementer shall\r
-                * require a content type that does not include comments and the format\r
-                * designer shall specify such a content type.\r
-                * \r
-                * comment = "(" *( ctext | quoted-pair | comment ) ")"\r
-                * \r
-                * ctext = <any TEXT excluding "(" and ")">\r
-                * \r
-                * TEXT = <any OCTET except CTLs, but including LWS>\r
-                * \r
-                * LWS = [CRLF] 1*( SP | HT )\r
-                * \r
-                * CR = <US-ASCII CR, carriage return (13)>\r
-                * \r
-                * LF = <US-ASCII LF, linefeed (10)>\r
-                * \r
-                * SP = <US-ASCII SP, space (32)>\r
-                * \r
-                * HT = <US-ASCII HT, horizontal-tab (9)>\r
-                * \r
-                * quoted-pair = "\" CHAR\r
-                */\r
-\r
-               // Keep for future use with parameter:\r
-               // patternMediaType = Pattern.compile("^(" + token + "+)/(" + token\r
-               // + "+)(;" + parameter + ")*$");\r
-               patternMediaType = Pattern.compile("^(" + token + "+)/(" + token\r
-                               + "+)$");\r
-       }\r
-\r
-       /**\r
-        * Constructor. Check the input with the RFC 2616 grammar.\r
-        * \r
-        * @param contentType\r
-        *            The content type to store.\r
-        * @throws InvalidFormatException\r
-        *             If the specified content type is not valid with RFC 2616.\r
-        */\r
-       public ContentType(String contentType) throws InvalidFormatException {\r
-               // Conversion en US-ASCII\r
-               String contentTypeASCII = null;\r
-               try {\r
-                       contentTypeASCII = new String(contentType.getBytes(), "US-ASCII");\r
-               } catch (UnsupportedEncodingException e) {\r
-                       throw new InvalidFormatException(\r
-                                       "The specified content type is not an ASCII value.");\r
-               }\r
-\r
-               Matcher mMediaType = patternMediaType.matcher(contentTypeASCII);\r
-               if (!mMediaType.matches())\r
-                       throw new InvalidFormatException(\r
-                                       "The specified content type '"\r
-                                                       + contentType\r
-                                                       + "' is not compliant with RFC 2616: malformed content type.");\r
-\r
-               // Type/subtype\r
-               if (mMediaType.groupCount() >= 2) {\r
-                       this.type = mMediaType.group(1);\r
-                       this.subType = mMediaType.group(2);\r
-                       // Parameters\r
-                       this.parameters = new Hashtable<String, String>(1);\r
-                       for (int i = 4; i <= mMediaType.groupCount()\r
-                                       && (mMediaType.group(i) != null); i += 2) {\r
-                               this.parameters.put(mMediaType.group(i), mMediaType\r
-                                               .group(i + 1));\r
-                       }\r
-               }\r
-       }\r
-\r
-       @Override\r
-       public final String toString() {\r
-               StringBuffer retVal = new StringBuffer();\r
-               retVal.append(this.getType());\r
-               retVal.append("/");\r
-               retVal.append(this.getSubType());\r
-               // Keep for future implementation if needed\r
-               // for (String key : parameters.keySet()) {\r
-               // retVal.append(";");\r
-               // retVal.append(key);\r
-               // retVal.append("=");\r
-               // retVal.append(parameters.get(key));\r
-               // }\r
-               return retVal.toString();\r
-       }\r
-\r
-       @Override\r
-       public boolean equals(Object obj) {\r
-               return (!(obj instanceof ContentType))\r
-                               || (this.toString().equalsIgnoreCase(obj.toString()));\r
-       }\r
-\r
-       @Override\r
-       public int hashCode() {\r
-               return this.toString().hashCode();\r
-       }\r
-\r
-       /* Getters */\r
-\r
-       /**\r
-        * Get the subtype.\r
-        * \r
-        * @return The subtype of this content type.\r
-        */\r
-       public String getSubType() {\r
-               return this.subType;\r
-       }\r
-\r
-       /**\r
-        * Get the type.\r
-        * \r
-        * @return The type of this content type.\r
-        */\r
-       public String getType() {\r
-               return this.type;\r
-       }\r
-\r
-       /**\r
-        * Gets the value associated to the specified key.\r
-        * \r
-        * @param key\r
-        *            The key of the key/value pair.\r
-        * @return The value associated to the specified key.\r
-        */\r
-       public String getParameters(String key) {\r
-               return parameters.get(key);\r
-       }\r
-}\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.openxml4j.opc.internal;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Hashtable;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+
+/**
+ * Represents a immutable MIME ContentType value (RFC 2616 &#167;3.7)
+ * <p>
+ * media-type = type "/" subtype *( ";" parameter ) type = token<br>
+ * subtype = token<br>
+ * </p><p>
+ * Rule M1.13 : Package implementers shall only create and only recognize parts
+ * with a content type; format designers shall specify a content type for each
+ * part included in the format. Content types for package parts shall fit the
+ * definition and syntax for media types as specified in RFC 2616, \&#167;3.7.
+ * </p><p>
+ * Rule M1.14: Content types shall not use linear white space either between the
+ * type and subtype or between an attribute and its value. Content types also
+ * shall not have leading or trailing white spaces. Package implementers shall
+ * create only such content types and shall require such content types when
+ * retrieving a part from a package; format designers shall specify only such
+ * content types for inclusion in the format.
+ * </p>
+ * @author Julien Chable
+ * @version 0.1
+ *
+ * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">http://www.ietf.org/rfc/rfc2045.txt</a>
+ * @see <a href="http://www.ietf.org/rfc/rfc2616.txt">http://www.ietf.org/rfc/rfc2616.txt</a>
+ */
+public final class ContentType {
+
+       /**
+        * Type in Type/Subtype.
+        */
+       private String type;
+
+       /**
+        * Subtype
+        */
+       private String subType;
+
+       /**
+        * Parameters
+        */
+       private Hashtable<String, String> parameters;
+
+       /**
+        * Media type compiled pattern for parameters.
+        */
+       private final static Pattern patternMediaType;
+
+       static {
+               /*
+                * token = 1*<any CHAR except CTLs or separators>
+                *
+                * separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" |
+                * <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT
+                *
+                * CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
+                *
+                * CHAR = <any US-ASCII character (octets 0 - 127)>
+                */
+               String token = "[\\x21-\\x7E&&[^\\(\\)<>@,;:\\\\/\"\\[\\]\\?={}\\x20\\x09]]";
+
+               /*
+                * parameter = attribute "=" value
+                *
+                * attribute = token
+                *
+                * value = token | quoted-string
+                */
+               // Keep for future use with parameter:
+               // String parameter = "(" + token + "+)=(\"?" + token + "+\"?)";
+               /*
+                * Pattern for media type.
+                *
+                * Don't allow comment, rule M1.15: The package implementer shall
+                * require a content type that does not include comments and the format
+                * designer shall specify such a content type.
+                *
+                * comment = "(" *( ctext | quoted-pair | comment ) ")"
+                *
+                * ctext = <any TEXT excluding "(" and ")">
+                *
+                * TEXT = <any OCTET except CTLs, but including LWS>
+                *
+                * LWS = [CRLF] 1*( SP | HT )
+                *
+                * CR = <US-ASCII CR, carriage return (13)>
+                *
+                * LF = <US-ASCII LF, linefeed (10)>
+                *
+                * SP = <US-ASCII SP, space (32)>
+                *
+                * HT = <US-ASCII HT, horizontal-tab (9)>
+                *
+                * quoted-pair = "\" CHAR
+                */
+
+               // Keep for future use with parameter:
+               // patternMediaType = Pattern.compile("^(" + token + "+)/(" + token
+               // + "+)(;" + parameter + ")*$");
+               patternMediaType = Pattern.compile("^(" + token + "+)/(" + token
+                               + "+)$");
+       }
+
+       /**
+        * Constructor. Check the input with the RFC 2616 grammar.
+        *
+        * @param contentType
+        *            The content type to store.
+        * @throws InvalidFormatException
+        *             If the specified content type is not valid with RFC 2616.
+        */
+       public ContentType(String contentType) throws InvalidFormatException {
+               // Conversion en US-ASCII
+               String contentTypeASCII = null;
+               try {
+                       contentTypeASCII = new String(contentType.getBytes(), "US-ASCII");
+               } catch (UnsupportedEncodingException e) {
+                       throw new InvalidFormatException(
+                                       "The specified content type is not an ASCII value.");
+               }
+
+               Matcher mMediaType = patternMediaType.matcher(contentTypeASCII);
+               if (!mMediaType.matches())
+                       throw new InvalidFormatException(
+                                       "The specified content type '"
+                                                       + contentType
+                                                       + "' is not compliant with RFC 2616: malformed content type.");
+
+               // Type/subtype
+               if (mMediaType.groupCount() >= 2) {
+                       this.type = mMediaType.group(1);
+                       this.subType = mMediaType.group(2);
+                       // Parameters
+                       this.parameters = new Hashtable<String, String>(1);
+                       for (int i = 4; i <= mMediaType.groupCount()
+                                       && (mMediaType.group(i) != null); i += 2) {
+                               this.parameters.put(mMediaType.group(i), mMediaType
+                                               .group(i + 1));
+                       }
+               }
+       }
+
+       @Override
+       public final String toString() {
+               StringBuffer retVal = new StringBuffer();
+               retVal.append(this.getType());
+               retVal.append("/");
+               retVal.append(this.getSubType());
+               // Keep for future implementation if needed
+               // for (String key : parameters.keySet()) {
+               // retVal.append(";");
+               // retVal.append(key);
+               // retVal.append("=");
+               // retVal.append(parameters.get(key));
+               // }
+               return retVal.toString();
+       }
+
+       @Override
+       public boolean equals(Object obj) {
+               return (!(obj instanceof ContentType))
+                               || (this.toString().equalsIgnoreCase(obj.toString()));
+       }
+
+       @Override
+       public int hashCode() {
+               return this.toString().hashCode();
+       }
+
+       /* Getters */
+
+       /**
+        * Get the subtype.
+        *
+        * @return The subtype of this content type.
+        */
+       public String getSubType() {
+               return this.subType;
+       }
+
+       /**
+        * Get the type.
+        *
+        * @return The type of this content type.
+        */
+       public String getType() {
+               return this.type;
+       }
+
+       /**
+        * Gets the value associated to the specified key.
+        *
+        * @param key
+        *            The key of the key/value pair.
+        * @return The value associated to the specified key.
+        */
+       public String getParameters(String key) {
+               return parameters.get(key);
+       }
+}
index ad311573729942eec9cb3073e1ba8bf4a1e733fc..cc41e43520db8b669dcbc90d08365aafa734ba5d 100755 (executable)
@@ -1,91 +1,91 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal;\r
-\r
-import java.io.File;\r
-import java.io.FileInputStream;\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-import java.nio.channels.FileChannel;\r
-\r
-/**\r
- * Provide useful method to manage file.\r
- * \r
- * @author Julien Chable\r
- * @version 0.1\r
- */\r
-public final class FileHelper {\r
-\r
-       /**\r
-        * Get the directory part of the specified file path.\r
-        * \r
-        * @param f\r
-        *            File to process.\r
-        * @return The directory path from the specified\r
-        */\r
-       public static File getDirectory(File f) {\r
-               if (f != null) {\r
-                       String path = f.getPath();\r
-                       int len = path.length();\r
-                       int num2 = len;\r
-                       while (--num2 >= 0) {\r
-                               char ch1 = path.charAt(num2);\r
-                               if (ch1 == File.separatorChar) {\r
-                                       return new File(path.substring(0, num2));\r
-                               }\r
-                       }\r
-               }\r
-               return null;\r
-       }\r
-\r
-       /**\r
-        * Copy a file.\r
-        * \r
-        * @param in\r
-        *            The source file.\r
-        * @param out\r
-        *            The target location.\r
-        * @throws IOException\r
-        *             If an I/O error occur.\r
-        */\r
-       public static void copyFile(File in, File out) throws IOException {\r
-               FileChannel sourceChannel = new FileInputStream(in).getChannel();\r
-               FileChannel destinationChannel = new FileOutputStream(out).getChannel();\r
-               sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);\r
-               sourceChannel.close();\r
-               destinationChannel.close();\r
-       }\r
-\r
-       /**\r
-        * Get file name from the specified File object.\r
-        */\r
-       public static String getFilename(File file) {\r
-               if (file != null) {\r
-                       String path = file.getPath();\r
-                       int len = path.length();\r
-                       int num2 = len;\r
-                       while (--num2 >= 0) {\r
-                               char ch1 = path.charAt(num2);\r
-                               if (ch1 == File.separatorChar)\r
-                                       return path.substring(num2 + 1, len);\r
-                       }\r
-               }\r
-               return "";\r
-       }\r
-\r
-}\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.openxml4j.opc.internal;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.channels.FileChannel;
+
+/**
+ * Provide useful method to manage file.
+ *
+ * @author Julien Chable
+ * @version 0.1
+ */
+public final class FileHelper {
+
+       /**
+        * Get the directory part of the specified file path.
+        *
+        * @param f
+        *            File to process.
+        * @return The directory path from the specified
+        */
+       public static File getDirectory(File f) {
+               if (f != null) {
+                       String path = f.getPath();
+                       int len = path.length();
+                       int num2 = len;
+                       while (--num2 >= 0) {
+                               char ch1 = path.charAt(num2);
+                               if (ch1 == File.separatorChar) {
+                                       return new File(path.substring(0, num2));
+                               }
+                       }
+               }
+               return null;
+       }
+
+       /**
+        * Copy a file.
+        *
+        * @param in
+        *            The source file.
+        * @param out
+        *            The target location.
+        * @throws IOException
+        *             If an I/O error occur.
+        */
+       public static void copyFile(File in, File out) throws IOException {
+               FileChannel sourceChannel = new FileInputStream(in).getChannel();
+               FileChannel destinationChannel = new FileOutputStream(out).getChannel();
+               sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
+               sourceChannel.close();
+               destinationChannel.close();
+       }
+
+       /**
+        * Get file name from the specified File object.
+        */
+       public static String getFilename(File file) {
+               if (file != null) {
+                       String path = file.getPath();
+                       int len = path.length();
+                       int num2 = len;
+                       while (--num2 >= 0) {
+                               char ch1 = path.charAt(num2);
+                               if (ch1 == File.separatorChar)
+                                       return path.substring(num2 + 1, len);
+                       }
+               }
+               return "";
+       }
+
+}
index debe3d185ecd1c1aad7ef307f3e399b7e5a387d1..ed0bc6a74a3c5d969a3577bbd62645e9b6d52887 100755 (executable)
@@ -1,96 +1,96 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal;\r
-\r
-import java.io.ByteArrayOutputStream;\r
-import java.io.IOException;\r
-import java.io.OutputStream;\r
-\r
-/**\r
- * Build an output stream for MemoryPackagePart.\r
- * \r
- * @author Julien Chable\r
- * @version 1.0\r
- */\r
-public final class MemoryPackagePartOutputStream extends OutputStream {\r
-\r
-       private MemoryPackagePart part;\r
-\r
-       private ByteArrayOutputStream buff;\r
-\r
-       public MemoryPackagePartOutputStream(MemoryPackagePart part) {\r
-               this.part = part;\r
-               buff = new ByteArrayOutputStream();\r
-       }\r
-\r
-       @Override\r
-       public void write(int b) throws IOException {\r
-               buff.write(b);\r
-       }\r
-\r
-       /**\r
-        * Close this stream and flush the content.\r
-        * @see #flush() \r
-        */\r
-       @Override\r
-       public void close() throws IOException {\r
-               this.flush();\r
-       }\r
-\r
-       /**\r
-        * Flush this output stream. This method is called by the close() method.\r
-        * Warning : don't call this method for output consistency.\r
-        * @see #close()\r
-        */\r
-       @Override\r
-       public void flush() throws IOException {\r
-               buff.flush();\r
-               if (part.data != null) {\r
-                       byte[] newArray = new byte[part.data.length + buff.size()];\r
-                       // copy the previous contents of part.data in newArray\r
-                       System.arraycopy(part.data, 0, newArray, 0, part.data.length);\r
-\r
-                       // append the newly added data\r
-                       byte[] buffArr = buff.toByteArray();\r
-                       System.arraycopy(buffArr, 0, newArray, part.data.length,\r
-                                       buffArr.length);\r
-\r
-                       // save the result as new data\r
-                       part.data = newArray;\r
-               } else {\r
-                       // was empty, just fill it\r
-                       part.data = buff.toByteArray();\r
-               }\r
-               \r
-               /* \r
-                * Clear this streams buffer, in case flush() is called a second time\r
-                * Fix bug 1921637 - provided by Rainer Schwarze\r
-                */\r
-               buff.reset();\r
-       }\r
-\r
-       @Override\r
-       public void write(byte[] b, int off, int len) throws IOException {\r
-               buff.write(b, off, len);\r
-       }\r
-\r
-       @Override\r
-       public void write(byte[] b) throws IOException {\r
-               buff.write(b);\r
-       }\r
-}\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.openxml4j.opc.internal;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * Build an output stream for MemoryPackagePart.
+ *
+ * @author Julien Chable
+ * @version 1.0
+ */
+public final class MemoryPackagePartOutputStream extends OutputStream {
+
+       private MemoryPackagePart part;
+
+       private ByteArrayOutputStream buff;
+
+       public MemoryPackagePartOutputStream(MemoryPackagePart part) {
+               this.part = part;
+               buff = new ByteArrayOutputStream();
+       }
+
+       @Override
+       public void write(int b) throws IOException {
+               buff.write(b);
+       }
+
+       /**
+        * Close this stream and flush the content.
+        * @see #flush()
+        */
+       @Override
+       public void close() throws IOException {
+               this.flush();
+       }
+
+       /**
+        * Flush this output stream. This method is called by the close() method.
+        * Warning : don't call this method for output consistency.
+        * @see #close()
+        */
+       @Override
+       public void flush() throws IOException {
+               buff.flush();
+               if (part.data != null) {
+                       byte[] newArray = new byte[part.data.length + buff.size()];
+                       // copy the previous contents of part.data in newArray
+                       System.arraycopy(part.data, 0, newArray, 0, part.data.length);
+
+                       // append the newly added data
+                       byte[] buffArr = buff.toByteArray();
+                       System.arraycopy(buffArr, 0, newArray, part.data.length,
+                                       buffArr.length);
+
+                       // save the result as new data
+                       part.data = newArray;
+               } else {
+                       // was empty, just fill it
+                       part.data = buff.toByteArray();
+               }
+
+               /*
+                * Clear this streams buffer, in case flush() is called a second time
+                * Fix bug 1921637 - provided by Rainer Schwarze
+                */
+               buff.reset();
+       }
+
+       @Override
+       public void write(byte[] b, int off, int len) throws IOException {
+               buff.write(b, off, len);
+       }
+
+       @Override
+       public void write(byte[] b) throws IOException {
+               buff.write(b);
+       }
+}
index 70bbcae6b6f1a4ba5274d9fd52c1f17deb03ed29..e30d71783adcf7f07ce7fa4866d2961a039b5c80 100755 (executable)
@@ -1,49 +1,49 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal;\r
-\r
-import java.io.OutputStream;\r
-\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-\r
-/**\r
- * Object implemented this interface are considered as part marshaller. A part\r
- * marshaller is responsible to marshall a part in order to be save in a\r
- * package.\r
- * \r
- * @author Julien Chable\r
- * @version 0.1\r
- */\r
-public interface PartMarshaller {\r
-\r
-       /**\r
-        * Save the content of the package in the stream\r
-        * \r
-        * @param part\r
-        *            Part to marshall.\r
-        * @param out\r
-        *            The output stream into which the part will be marshall.\r
-        * @return <b>false</b> if any marshall error occurs, else <b>true</b>\r
-        * @throws OpenXML4JException\r
-        *             Throws only if any other exceptions are thrown by inner\r
-        *             methods.\r
-        */\r
-       public boolean marshall(PackagePart part, OutputStream out)\r
-                       throws OpenXML4JException;\r
-}\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.openxml4j.opc.internal;
+
+import java.io.OutputStream;
+
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.PackagePart;
+
+/**
+ * Object implemented this interface are considered as part marshaller. A part
+ * marshaller is responsible to marshall a part in order to be save in a
+ * package.
+ *
+ * @author Julien Chable
+ * @version 0.1
+ */
+public interface PartMarshaller {
+
+       /**
+        * Save the content of the package in the stream
+        *
+        * @param part
+        *            Part to marshall.
+        * @param out
+        *            The output stream into which the part will be marshall.
+        * @return <b>false</b> if any marshall error occurs, else <b>true</b>
+        * @throws OpenXML4JException
+        *             Throws only if any other exceptions are thrown by inner
+        *             methods.
+        */
+       public boolean marshall(PackagePart part, OutputStream out)
+                       throws OpenXML4JException;
+}
index 0b17cb89263e83ae4f8b60a2e5268be92435150a..e5487a6381cce0f622e07ffae682c3f361e231ec 100755 (executable)
@@ -1,50 +1,50 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal;\r
-\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-\r
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.apache.poi.openxml4j.opc.internal.unmarshallers.UnmarshallContext;\r
-\r
-/**\r
- * Object implemented this interface are considered as part unmarshaller. A part\r
- * unmarshaller is responsible to unmarshall a part in order to load it from a\r
- * package.\r
- * \r
- * @author Julien Chable\r
- * @version 0.1\r
- */\r
-public interface PartUnmarshaller {\r
-\r
-       /**\r
-        * Save the content of the package in the stream\r
-        * \r
-        * @param in\r
-        *            The input stream from which the part will be unmarshall.\r
-        * @return The part freshly unmarshall from the input stream.\r
-        * @throws OpenXML4JException\r
-        *             Throws only if any other exceptions are thrown by inner\r
-        *             methods.\r
-        */\r
-       public PackagePart unmarshall(UnmarshallContext context, InputStream in)\r
-                       throws InvalidFormatException, IOException;\r
-}\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.openxml4j.opc.internal;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.PackagePart;
+import org.apache.poi.openxml4j.opc.internal.unmarshallers.UnmarshallContext;
+
+/**
+ * Object implemented this interface are considered as part unmarshaller. A part
+ * unmarshaller is responsible to unmarshall a part in order to load it from a
+ * package.
+ *
+ * @author Julien Chable
+ * @version 0.1
+ */
+public interface PartUnmarshaller {
+
+       /**
+        * Save the content of the package in the stream
+        *
+        * @param in
+        *            The input stream from which the part will be unmarshall.
+        * @return The part freshly unmarshall from the input stream.
+        * @throws OpenXML4JException
+        *             Throws only if any other exceptions are thrown by inner
+        *             methods.
+        */
+       public PackagePart unmarshall(UnmarshallContext context, InputStream in)
+                       throws InvalidFormatException, IOException;
+}
index 10b2339ec4838c5b7785a0ebf4a16bef45ccd835..ab867ad250da68947bd843c4bb9e18f23017ec05 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal;\r
-\r
-import java.io.File;\r
-import java.io.IOException;\r
-import java.net.URI;\r
-import java.net.URISyntaxException;\r
-import java.util.Enumeration;\r
-import java.util.zip.ZipEntry;\r
-import java.util.zip.ZipFile;\r
-\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.PackageRelationship;\r
-import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;\r
-import org.apache.poi.openxml4j.opc.ZipPackage;\r
-\r
-public final class ZipHelper {\r
-\r
-       /**\r
-        * Forward slash use to convert part name between OPC and zip item naming\r
-        * conventions.\r
-        */\r
-       private final static String FORWARD_SLASH = "/";\r
-       \r
-       /**\r
-        * Buffer to read data from file. Use big buffer to improve performaces. the\r
-        * InputStream class is reading only 8192 bytes per read call (default value\r
-        * set by sun)\r
-        */\r
-       public static final int READ_WRITE_FILE_BUFFER_SIZE = 8192;\r
-\r
-       /**\r
-        * Prevent this class to be instancied.\r
-        */\r
-       private ZipHelper() {\r
-               // Do nothing\r
-       }\r
-\r
-       /**\r
-        * Retrieve the zip entry of the core properties part.\r
-        * \r
-        * @throws OpenXML4JException\r
-        *             Throws if internal error occurs.\r
-        */\r
-       public static ZipEntry getCorePropertiesZipEntry(ZipPackage pkg)\r
-                       throws OpenXML4JException {\r
-               PackageRelationship corePropsRel = pkg.getRelationshipsByType(\r
-                               PackageRelationshipTypes.CORE_PROPERTIES).getRelationship(0);\r
-\r
-               if (corePropsRel == null)\r
-                       return null;\r
-\r
-               return new ZipEntry(corePropsRel.getTargetURI().getPath());\r
-       }\r
-\r
-       /**\r
-        * Retrieve the Zip entry of the content types part.\r
-        */\r
-       public static ZipEntry getContentTypeZipEntry(ZipPackage pkg) {\r
-               Enumeration entries = pkg.getZipArchive().getEntries();\r
-               // Enumerate through the Zip entries until we find the one named\r
-               // '[Content_Types].xml'.\r
-               while (entries.hasMoreElements()) {\r
-                       ZipEntry entry = (ZipEntry) entries.nextElement();\r
-                       if (entry.getName().equals(\r
-                                       ContentTypeManager.CONTENT_TYPES_PART_NAME))\r
-                               return entry;\r
-               }\r
-               return null;\r
-       }\r
-\r
-       /**\r
-        * Convert a zip name into an OPC name by adding a leading forward slash to\r
-        * the specified item name.\r
-        * \r
-        * @param zipItemName\r
-        *            Zip item name to convert.\r
-        * @return An OPC compliant name.\r
-        */\r
-       public static String getOPCNameFromZipItemName(String zipItemName) {\r
-               if (zipItemName == null)\r
-                       throw new IllegalArgumentException("zipItemName");\r
-               if (zipItemName.startsWith(FORWARD_SLASH))\r
-                       return zipItemName;\r
-               else\r
-                       return FORWARD_SLASH + zipItemName;\r
-       }\r
-\r
-       /**\r
-        * Convert an OPC item name into a zip item name by removing any leading\r
-        * forward slash if it exist.\r
-        * \r
-        * @param opcItemName\r
-        *            The OPC item name to convert.\r
-        * @return A zip item name without any leading slashes.\r
-        */\r
-       public static String getZipItemNameFromOPCName(String opcItemName) {\r
-               if (opcItemName == null)\r
-                       throw new IllegalArgumentException("opcItemName");\r
-\r
-               String retVal = new String(opcItemName);\r
-               while (retVal.startsWith(FORWARD_SLASH))\r
-                       retVal = retVal.substring(1);\r
-               return retVal;\r
-       }\r
-\r
-       /**\r
-        * Convert an OPC item name into a zip URI by removing any leading forward\r
-        * slash if it exist.\r
-        * \r
-        * @param opcItemName\r
-        *            The OPC item name to convert.\r
-        * @return A zip URI without any leading slashes.\r
-        */\r
-       public static URI getZipURIFromOPCName(String opcItemName) {\r
-               if (opcItemName == null)\r
-                       throw new IllegalArgumentException("opcItemName");\r
-\r
-               String retVal = new String(opcItemName);\r
-               while (retVal.startsWith(FORWARD_SLASH))\r
-                       retVal = retVal.substring(1);\r
-               try {\r
-                       return new URI(retVal);\r
-               } catch (URISyntaxException e) {\r
-                       return null;\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Retrieve and open a zip file with the specified path.\r
-        * \r
-        * @param path\r
-        *            The file path.\r
-        * @return The zip archive freshly open.\r
-        */\r
-       public static ZipFile openZipFile(String path) {\r
-               File f = new File(path);\r
-               try {\r
-                       if (!f.exists()) {\r
-                               return null;\r
-                       }\r
-                       return new ZipFile(f);\r
-               } catch (IOException ioe) {\r
-                       return null;\r
-               }\r
-       }\r
-}\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.openxml4j.opc.internal;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Enumeration;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.PackageRelationship;
+import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
+import org.apache.poi.openxml4j.opc.ZipPackage;
+
+public final class ZipHelper {
+
+       /**
+        * Forward slash use to convert part name between OPC and zip item naming
+        * conventions.
+        */
+       private final static String FORWARD_SLASH = "/";
+
+       /**
+        * Buffer to read data from file. Use big buffer to improve performaces. the
+        * InputStream class is reading only 8192 bytes per read call (default value
+        * set by sun)
+        */
+       public static final int READ_WRITE_FILE_BUFFER_SIZE = 8192;
+
+       /**
+        * Prevent this class to be instancied.
+        */
+       private ZipHelper() {
+               // Do nothing
+       }
+
+       /**
+        * Retrieve the zip entry of the core properties part.
+        *
+        * @throws OpenXML4JException
+        *             Throws if internal error occurs.
+        */
+       public static ZipEntry getCorePropertiesZipEntry(ZipPackage pkg)
+                       throws OpenXML4JException {
+               PackageRelationship corePropsRel = pkg.getRelationshipsByType(
+                               PackageRelationshipTypes.CORE_PROPERTIES).getRelationship(0);
+
+               if (corePropsRel == null)
+                       return null;
+
+               return new ZipEntry(corePropsRel.getTargetURI().getPath());
+       }
+
+       /**
+        * Retrieve the Zip entry of the content types part.
+        */
+       public static ZipEntry getContentTypeZipEntry(ZipPackage pkg) {
+               Enumeration entries = pkg.getZipArchive().getEntries();
+               // Enumerate through the Zip entries until we find the one named
+               // '[Content_Types].xml'.
+               while (entries.hasMoreElements()) {
+                       ZipEntry entry = (ZipEntry) entries.nextElement();
+                       if (entry.getName().equals(
+                                       ContentTypeManager.CONTENT_TYPES_PART_NAME))
+                               return entry;
+               }
+               return null;
+       }
+
+       /**
+        * Convert a zip name into an OPC name by adding a leading forward slash to
+        * the specified item name.
+        *
+        * @param zipItemName
+        *            Zip item name to convert.
+        * @return An OPC compliant name.
+        */
+       public static String getOPCNameFromZipItemName(String zipItemName) {
+               if (zipItemName == null)
+                       throw new IllegalArgumentException("zipItemName");
+               if (zipItemName.startsWith(FORWARD_SLASH))
+                       return zipItemName;
+               else
+                       return FORWARD_SLASH + zipItemName;
+       }
+
+       /**
+        * Convert an OPC item name into a zip item name by removing any leading
+        * forward slash if it exist.
+        *
+        * @param opcItemName
+        *            The OPC item name to convert.
+        * @return A zip item name without any leading slashes.
+        */
+       public static String getZipItemNameFromOPCName(String opcItemName) {
+               if (opcItemName == null)
+                       throw new IllegalArgumentException("opcItemName");
+
+               String retVal = new String(opcItemName);
+               while (retVal.startsWith(FORWARD_SLASH))
+                       retVal = retVal.substring(1);
+               return retVal;
+       }
+
+       /**
+        * Convert an OPC item name into a zip URI by removing any leading forward
+        * slash if it exist.
+        *
+        * @param opcItemName
+        *            The OPC item name to convert.
+        * @return A zip URI without any leading slashes.
+        */
+       public static URI getZipURIFromOPCName(String opcItemName) {
+               if (opcItemName == null)
+                       throw new IllegalArgumentException("opcItemName");
+
+               String retVal = new String(opcItemName);
+               while (retVal.startsWith(FORWARD_SLASH))
+                       retVal = retVal.substring(1);
+               try {
+                       return new URI(retVal);
+               } catch (URISyntaxException e) {
+                       return null;
+               }
+       }
+
+       /**
+        * Retrieve and open a zip file with the specified path.
+        *
+        * @param path
+        *            The file path.
+        * @return The zip archive freshly open.
+        */
+       public static ZipFile openZipFile(String path) {
+               File f = new File(path);
+               try {
+                       if (!f.exists()) {
+                               return null;
+                       }
+                       return new ZipFile(f);
+               } catch (IOException ioe) {
+                       return null;
+               }
+       }
+}
index 8138cda8be11e95b97f96aebd09313d9d2197623..8cd2f7d245315b42997d2f8e87e5abdfb656af47 100755 (executable)
@@ -1,45 +1,45 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal.marshallers;\r
-\r
-import java.io.OutputStream;\r
-\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.apache.poi.openxml4j.opc.internal.PartMarshaller;\r
-\r
-/**\r
- * Default marshaller that specified that the part is responsible to marshall its content.\r
- * \r
- * @author Julien Chable\r
- * @version 1.0\r
- * @see PartMarshaller\r
- */\r
-public class DefaultMarshaller implements PartMarshaller {\r
-\r
-       /**\r
-        * Save part in the output stream by using the save() method of the part.\r
-        * \r
-        * @throws OpenXML4JException\r
-        *             If any error occur.\r
-        */\r
-       public boolean marshall(PackagePart part, OutputStream out)\r
-                       throws OpenXML4JException {\r
-               return part.save(out);\r
-       }\r
-}\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.openxml4j.opc.internal.marshallers;
+
+import java.io.OutputStream;
+
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.PackagePart;
+import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
+
+/**
+ * Default marshaller that specified that the part is responsible to marshall its content.
+ *
+ * @author Julien Chable
+ * @version 1.0
+ * @see PartMarshaller
+ */
+public final class DefaultMarshaller implements PartMarshaller {
+
+       /**
+        * Save part in the output stream by using the save() method of the part.
+        *
+        * @throws OpenXML4JException
+        *             If any error occur.
+        */
+       public boolean marshall(PackagePart part, OutputStream out)
+                       throws OpenXML4JException {
+               return part.save(out);
+       }
+}
index 438cc5dcbba0f1228f1f0ef1aff59a3fabfde7d9..1ad4d26b71ac85bc24e6d4e13a9fda26a678bb4c 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal.marshallers;\r
-\r
-import java.io.OutputStream;\r
-\r
-import org.dom4j.Document;\r
-import org.dom4j.DocumentHelper;\r
-import org.dom4j.Element;\r
-import org.dom4j.Namespace;\r
-import org.dom4j.QName;\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;\r
-import org.apache.poi.openxml4j.opc.internal.PartMarshaller;\r
-\r
-/**\r
- * Package properties marshaller.\r
- * \r
- * @author CDubet, Julien Chable\r
- * @version 1.0\r
- */\r
-public class PackagePropertiesMarshaller implements PartMarshaller {\r
-\r
-       private final static Namespace namespaceDC = new Namespace("dc",\r
-                       PackagePropertiesPart.NAMESPACE_DC_URI);\r
-\r
-       private final static Namespace namespaceCoreProperties = new Namespace("",\r
-                       PackagePropertiesPart.NAMESPACE_CP_URI);\r
-\r
-       private final static Namespace namespaceDcTerms = new Namespace("dcterms",\r
-                       PackagePropertiesPart.NAMESPACE_DCTERMS_URI);\r
-\r
-       private final static Namespace namespaceXSI = new Namespace("xsi",\r
-                       PackagePropertiesPart.NAMESPACE_XSI_URI);\r
-\r
-       protected static final String KEYWORD_CATEGORY = "category";\r
-\r
-       protected static final String KEYWORD_CONTENT_STATUS = "contentStatus";\r
-\r
-       protected static final String KEYWORD_CONTENT_TYPE = "contentType";\r
-\r
-       protected static final String KEYWORD_CREATED = "created";\r
-\r
-       protected static final String KEYWORD_CREATOR = "creator";\r
-\r
-       protected static final String KEYWORD_DESCRIPTION = "description";\r
-\r
-       protected static final String KEYWORD_IDENTIFIER = "identifier";\r
-\r
-       protected static final String KEYWORD_KEYWORDS = "keywords";\r
-\r
-       protected static final String KEYWORD_LANGUAGE = "language";\r
-\r
-       protected static final String KEYWORD_LAST_MODIFIED_BY = "lastModifiedBy";\r
-\r
-       protected static final String KEYWORD_LAST_PRINTED = "lastPrinted";\r
-\r
-       protected static final String KEYWORD_MODIFIED = "modified";\r
-\r
-       protected static final String KEYWORD_REVISION = "revision";\r
-\r
-       protected static final String KEYWORD_SUBJECT = "subject";\r
-\r
-       protected static final String KEYWORD_TITLE = "title";\r
-\r
-       protected static final String KEYWORD_VERSION = "version";\r
-\r
-       PackagePropertiesPart propsPart;\r
-\r
-       // The document\r
-       Document xmlDoc = null;\r
-\r
-       /**\r
-        * Marshall package core properties to an XML document. Always return\r
-        * <code>true</code>.\r
-        */\r
-       public boolean marshall(PackagePart part, OutputStream out)\r
-                       throws OpenXML4JException {\r
-               if (!(part instanceof PackagePropertiesPart))\r
-                       throw new IllegalArgumentException(\r
-                                       "'part' must be a PackagePropertiesPart instance.");\r
-               propsPart = (PackagePropertiesPart) part;\r
-\r
-               // Configure the document\r
-               xmlDoc = DocumentHelper.createDocument();\r
-               Element rootElem = xmlDoc.addElement(new QName("coreProperties",\r
-                               namespaceCoreProperties));\r
-               rootElem.addNamespace("cp", PackagePropertiesPart.NAMESPACE_CP_URI);\r
-               rootElem.addNamespace("dc", PackagePropertiesPart.NAMESPACE_DC_URI);\r
-               rootElem.addNamespace("dcterms",\r
-                               PackagePropertiesPart.NAMESPACE_DCTERMS_URI);\r
-               rootElem.addNamespace("xsi", PackagePropertiesPart.NAMESPACE_XSI_URI);\r
-\r
-               addCategory();\r
-               addContentStatus();\r
-               addContentType();\r
-               addCreated();\r
-               addCreator();\r
-               addDescription();\r
-               addIdentifier();\r
-               addKeywords();\r
-               addLanguage();\r
-               addLastModifiedBy();\r
-               addLastPrinted();\r
-               addModified();\r
-               addRevision();\r
-               addSubject();\r
-               addTitle();\r
-               addVersion();\r
-               return true;\r
-       }\r
-\r
-       /**\r
-        * Add category property element if needed.\r
-        */\r
-       private void addCategory() {\r
-               if (!propsPart.getCategoryProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_CATEGORY, namespaceCoreProperties));\r
-               if (elem == null) {\r
-                       // Missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_CATEGORY, namespaceCoreProperties));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getCategoryProperty().getValue());\r
-       }\r
-\r
-       /**\r
-        * Add content status property element if needed.\r
-        */\r
-       private void addContentStatus() {\r
-               if (!propsPart.getContentStatusProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_CONTENT_STATUS, namespaceCoreProperties));\r
-               if (elem == null) {\r
-                       // Missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_CONTENT_STATUS, namespaceCoreProperties));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getContentStatusProperty().getValue());\r
-       }\r
-\r
-       /**\r
-        * Add content type property element if needed.\r
-        */\r
-       private void addContentType() {\r
-               if (!propsPart.getContentTypeProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_CONTENT_TYPE, namespaceCoreProperties));\r
-               if (elem == null) {\r
-                       // Missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_CONTENT_TYPE, namespaceCoreProperties));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getContentTypeProperty().getValue());\r
-       }\r
-\r
-       /**\r
-        * Add created property element if needed.\r
-        */\r
-       private void addCreated() {\r
-               if (!propsPart.getCreatedProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_CREATED, namespaceDcTerms));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_CREATED, namespaceDcTerms));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addAttribute(new QName("type", namespaceXSI), "dcterms:W3CDTF");\r
-               elem.addText(propsPart.getCreatedPropertyString());\r
-       }\r
-\r
-       /**\r
-        * Add creator property element if needed.\r
-        */\r
-       private void addCreator() {\r
-               if (!propsPart.getCreatorProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_CREATOR, namespaceDC));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_CREATOR, namespaceDC));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getCreatorProperty().getValue());\r
-       }\r
-\r
-       /**\r
-        * Add description property element if needed.\r
-        */\r
-       private void addDescription() {\r
-               if (!propsPart.getDescriptionProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_DESCRIPTION, namespaceDC));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_DESCRIPTION, namespaceDC));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getDescriptionProperty().getValue());\r
-       }\r
-\r
-       /**\r
-        * Add identifier property element if needed.\r
-        */\r
-       private void addIdentifier() {\r
-               if (!propsPart.getIdentifierProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_IDENTIFIER, namespaceDC));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_IDENTIFIER, namespaceDC));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getIdentifierProperty().getValue());\r
-       }\r
-\r
-       /**\r
-        * Add keywords property element if needed.\r
-        */\r
-       private void addKeywords() {\r
-               if (!propsPart.getKeywordsProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_KEYWORDS, namespaceCoreProperties));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_KEYWORDS, namespaceCoreProperties));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getKeywordsProperty().getValue());\r
-       }\r
-\r
-       /**\r
-        * Add language property element if needed.\r
-        */\r
-       private void addLanguage() {\r
-               if (!propsPart.getLanguageProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_LANGUAGE, namespaceDC));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_LANGUAGE, namespaceDC));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getLanguageProperty().getValue());\r
-       }\r
-\r
-       /**\r
-        * Add 'last modified by' property if needed.\r
-        */\r
-       private void addLastModifiedBy() {\r
-               if (!propsPart.getLastModifiedByProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_LAST_MODIFIED_BY, namespaceCoreProperties));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement()\r
-                                       .addElement(\r
-                                                       new QName(KEYWORD_LAST_MODIFIED_BY,\r
-                                                                       namespaceCoreProperties));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getLastModifiedByProperty().getValue());\r
-       }\r
-\r
-       /**\r
-        * Add 'last printed' property if needed.\r
-        * \r
-        */\r
-       private void addLastPrinted() {\r
-               if (!propsPart.getLastPrintedProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_LAST_PRINTED, namespaceCoreProperties));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_LAST_PRINTED, namespaceCoreProperties));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getLastPrintedPropertyString());\r
-       }\r
-\r
-       /**\r
-        * Add modified property element if needed.\r
-        */\r
-       private void addModified() {\r
-               if (!propsPart.getModifiedProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_MODIFIED, namespaceDcTerms));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_MODIFIED, namespaceDcTerms));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addAttribute(new QName("type", namespaceXSI), "dcterms:W3CDTF");\r
-               elem.addText(propsPart.getModifiedPropertyString());\r
-       }\r
-\r
-       /**\r
-        * Add revision property if needed.\r
-        */\r
-       private void addRevision() {\r
-               if (!propsPart.getRevisionProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_REVISION, namespaceCoreProperties));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_REVISION, namespaceCoreProperties));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getRevisionProperty().getValue());\r
-       }\r
-\r
-       /**\r
-        * Add subject property if needed.\r
-        */\r
-       private void addSubject() {\r
-               if (!propsPart.getSubjectProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_SUBJECT, namespaceDC));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_SUBJECT, namespaceDC));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getSubjectProperty().getValue());\r
-       }\r
-\r
-       /**\r
-        * Add title property if needed.\r
-        */\r
-       private void addTitle() {\r
-               if (!propsPart.getTitleProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_TITLE, namespaceDC));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_TITLE, namespaceDC));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getTitleProperty().getValue());\r
-       }\r
-\r
-       private void addVersion() {\r
-               if (!propsPart.getVersionProperty().hasValue())\r
-                       return;\r
-\r
-               Element elem = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_VERSION, namespaceCoreProperties));\r
-               if (elem == null) {\r
-                       // missing, we add it\r
-                       elem = xmlDoc.getRootElement().addElement(\r
-                                       new QName(KEYWORD_VERSION, namespaceCoreProperties));\r
-               } else {\r
-                       elem.clearContent();// clear the old value\r
-               }\r
-               elem.addText(propsPart.getVersionProperty().getValue());\r
-       }\r
-}\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.openxml4j.opc.internal.marshallers;
+
+import java.io.OutputStream;
+
+import org.dom4j.Document;
+import org.dom4j.DocumentHelper;
+import org.dom4j.Element;
+import org.dom4j.Namespace;
+import org.dom4j.QName;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.PackagePart;
+import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
+import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
+
+/**
+ * Package properties marshaller.
+ *
+ * @author CDubet, Julien Chable
+ */
+public class PackagePropertiesMarshaller implements PartMarshaller {
+
+       private final static Namespace namespaceDC = new Namespace("dc",
+                       PackagePropertiesPart.NAMESPACE_DC_URI);
+
+       private final static Namespace namespaceCoreProperties = new Namespace("",
+                       PackagePropertiesPart.NAMESPACE_CP_URI);
+
+       private final static Namespace namespaceDcTerms = new Namespace("dcterms",
+                       PackagePropertiesPart.NAMESPACE_DCTERMS_URI);
+
+       private final static Namespace namespaceXSI = new Namespace("xsi",
+                       PackagePropertiesPart.NAMESPACE_XSI_URI);
+
+       protected static final String KEYWORD_CATEGORY = "category";
+
+       protected static final String KEYWORD_CONTENT_STATUS = "contentStatus";
+
+       protected static final String KEYWORD_CONTENT_TYPE = "contentType";
+
+       protected static final String KEYWORD_CREATED = "created";
+
+       protected static final String KEYWORD_CREATOR = "creator";
+
+       protected static final String KEYWORD_DESCRIPTION = "description";
+
+       protected static final String KEYWORD_IDENTIFIER = "identifier";
+
+       protected static final String KEYWORD_KEYWORDS = "keywords";
+
+       protected static final String KEYWORD_LANGUAGE = "language";
+
+       protected static final String KEYWORD_LAST_MODIFIED_BY = "lastModifiedBy";
+
+       protected static final String KEYWORD_LAST_PRINTED = "lastPrinted";
+
+       protected static final String KEYWORD_MODIFIED = "modified";
+
+       protected static final String KEYWORD_REVISION = "revision";
+
+       protected static final String KEYWORD_SUBJECT = "subject";
+
+       protected static final String KEYWORD_TITLE = "title";
+
+       protected static final String KEYWORD_VERSION = "version";
+
+       PackagePropertiesPart propsPart;
+
+       // The document
+       Document xmlDoc = null;
+
+       /**
+        * Marshall package core properties to an XML document. Always return
+        * <code>true</code>.
+        */
+       public boolean marshall(PackagePart part, OutputStream out)
+                       throws OpenXML4JException {
+               if (!(part instanceof PackagePropertiesPart))
+                       throw new IllegalArgumentException(
+                                       "'part' must be a PackagePropertiesPart instance.");
+               propsPart = (PackagePropertiesPart) part;
+
+               // Configure the document
+               xmlDoc = DocumentHelper.createDocument();
+               Element rootElem = xmlDoc.addElement(new QName("coreProperties",
+                               namespaceCoreProperties));
+               rootElem.addNamespace("cp", PackagePropertiesPart.NAMESPACE_CP_URI);
+               rootElem.addNamespace("dc", PackagePropertiesPart.NAMESPACE_DC_URI);
+               rootElem.addNamespace("dcterms",
+                               PackagePropertiesPart.NAMESPACE_DCTERMS_URI);
+               rootElem.addNamespace("xsi", PackagePropertiesPart.NAMESPACE_XSI_URI);
+
+               addCategory();
+               addContentStatus();
+               addContentType();
+               addCreated();
+               addCreator();
+               addDescription();
+               addIdentifier();
+               addKeywords();
+               addLanguage();
+               addLastModifiedBy();
+               addLastPrinted();
+               addModified();
+               addRevision();
+               addSubject();
+               addTitle();
+               addVersion();
+               return true;
+       }
+
+       /**
+        * Add category property element if needed.
+        */
+       private void addCategory() {
+               if (!propsPart.getCategoryProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_CATEGORY, namespaceCoreProperties));
+               if (elem == null) {
+                       // Missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_CATEGORY, namespaceCoreProperties));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getCategoryProperty().getValue());
+       }
+
+       /**
+        * Add content status property element if needed.
+        */
+       private void addContentStatus() {
+               if (!propsPart.getContentStatusProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_CONTENT_STATUS, namespaceCoreProperties));
+               if (elem == null) {
+                       // Missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_CONTENT_STATUS, namespaceCoreProperties));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getContentStatusProperty().getValue());
+       }
+
+       /**
+        * Add content type property element if needed.
+        */
+       private void addContentType() {
+               if (!propsPart.getContentTypeProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_CONTENT_TYPE, namespaceCoreProperties));
+               if (elem == null) {
+                       // Missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_CONTENT_TYPE, namespaceCoreProperties));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getContentTypeProperty().getValue());
+       }
+
+       /**
+        * Add created property element if needed.
+        */
+       private void addCreated() {
+               if (!propsPart.getCreatedProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_CREATED, namespaceDcTerms));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_CREATED, namespaceDcTerms));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addAttribute(new QName("type", namespaceXSI), "dcterms:W3CDTF");
+               elem.addText(propsPart.getCreatedPropertyString());
+       }
+
+       /**
+        * Add creator property element if needed.
+        */
+       private void addCreator() {
+               if (!propsPart.getCreatorProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_CREATOR, namespaceDC));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_CREATOR, namespaceDC));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getCreatorProperty().getValue());
+       }
+
+       /**
+        * Add description property element if needed.
+        */
+       private void addDescription() {
+               if (!propsPart.getDescriptionProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_DESCRIPTION, namespaceDC));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_DESCRIPTION, namespaceDC));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getDescriptionProperty().getValue());
+       }
+
+       /**
+        * Add identifier property element if needed.
+        */
+       private void addIdentifier() {
+               if (!propsPart.getIdentifierProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_IDENTIFIER, namespaceDC));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_IDENTIFIER, namespaceDC));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getIdentifierProperty().getValue());
+       }
+
+       /**
+        * Add keywords property element if needed.
+        */
+       private void addKeywords() {
+               if (!propsPart.getKeywordsProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_KEYWORDS, namespaceCoreProperties));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_KEYWORDS, namespaceCoreProperties));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getKeywordsProperty().getValue());
+       }
+
+       /**
+        * Add language property element if needed.
+        */
+       private void addLanguage() {
+               if (!propsPart.getLanguageProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_LANGUAGE, namespaceDC));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_LANGUAGE, namespaceDC));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getLanguageProperty().getValue());
+       }
+
+       /**
+        * Add 'last modified by' property if needed.
+        */
+       private void addLastModifiedBy() {
+               if (!propsPart.getLastModifiedByProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_LAST_MODIFIED_BY, namespaceCoreProperties));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement()
+                                       .addElement(
+                                                       new QName(KEYWORD_LAST_MODIFIED_BY,
+                                                                       namespaceCoreProperties));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getLastModifiedByProperty().getValue());
+       }
+
+       /**
+        * Add 'last printed' property if needed.
+        *
+        */
+       private void addLastPrinted() {
+               if (!propsPart.getLastPrintedProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_LAST_PRINTED, namespaceCoreProperties));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_LAST_PRINTED, namespaceCoreProperties));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getLastPrintedPropertyString());
+       }
+
+       /**
+        * Add modified property element if needed.
+        */
+       private void addModified() {
+               if (!propsPart.getModifiedProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_MODIFIED, namespaceDcTerms));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_MODIFIED, namespaceDcTerms));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addAttribute(new QName("type", namespaceXSI), "dcterms:W3CDTF");
+               elem.addText(propsPart.getModifiedPropertyString());
+       }
+
+       /**
+        * Add revision property if needed.
+        */
+       private void addRevision() {
+               if (!propsPart.getRevisionProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_REVISION, namespaceCoreProperties));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_REVISION, namespaceCoreProperties));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getRevisionProperty().getValue());
+       }
+
+       /**
+        * Add subject property if needed.
+        */
+       private void addSubject() {
+               if (!propsPart.getSubjectProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_SUBJECT, namespaceDC));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_SUBJECT, namespaceDC));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getSubjectProperty().getValue());
+       }
+
+       /**
+        * Add title property if needed.
+        */
+       private void addTitle() {
+               if (!propsPart.getTitleProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_TITLE, namespaceDC));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_TITLE, namespaceDC));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getTitleProperty().getValue());
+       }
+
+       private void addVersion() {
+               if (!propsPart.getVersionProperty().hasValue())
+                       return;
+
+               Element elem = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_VERSION, namespaceCoreProperties));
+               if (elem == null) {
+                       // missing, we add it
+                       elem = xmlDoc.getRootElement().addElement(
+                                       new QName(KEYWORD_VERSION, namespaceCoreProperties));
+               } else {
+                       elem.clearContent();// clear the old value
+               }
+               elem.addText(propsPart.getVersionProperty().getValue());
+       }
+}
index 39e8fa3f3d3a91a5ad037202a766130bf6c0bb4a..07123b22dc0befcd23a752eb1d845241a716256f 100755 (executable)
@@ -1,64 +1,63 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal.marshallers;\r
-\r
-import java.io.IOException;\r
-import java.io.OutputStream;\r
-import java.util.zip.ZipEntry;\r
-import java.util.zip.ZipOutputStream;\r
-\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.apache.poi.openxml4j.opc.StreamHelper;\r
-import org.apache.poi.openxml4j.opc.internal.ZipHelper;\r
-\r
-/**\r
- * Package core properties marshaller specialized for zipped package.\r
- * \r
- * @author Julien Chable\r
- * @version 1.0\r
- */\r
-public class ZipPackagePropertiesMarshaller extends PackagePropertiesMarshaller {\r
-\r
-       @Override\r
-       public boolean marshall(PackagePart part, OutputStream out)\r
-                       throws OpenXML4JException {\r
-               if (!(out instanceof ZipOutputStream)) {\r
-                       throw new IllegalArgumentException("ZipOutputStream expected!");\r
-               }\r
-               ZipOutputStream zos = (ZipOutputStream) out;\r
-\r
-               // Saving the part in the zip file\r
-               ZipEntry ctEntry = new ZipEntry(ZipHelper\r
-                               .getZipItemNameFromOPCName(part.getPartName().getURI()\r
-                                               .toString()));\r
-               try {\r
-                       // Save in ZIP\r
-                       zos.putNextEntry(ctEntry); // Add entry in ZIP\r
-                       super.marshall(part, out); // Marshall the properties inside a XML\r
-                       // Document\r
-                       if (!StreamHelper.saveXmlInStream(xmlDoc, out)) {\r
-                               return false;\r
-                       }\r
-                       zos.closeEntry();\r
-               } catch (IOException e) {\r
-                       throw new OpenXML4JException(e.getLocalizedMessage());\r
-               }\r
-               return true;\r
-       }\r
-}\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.openxml4j.opc.internal.marshallers;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.PackagePart;
+import org.apache.poi.openxml4j.opc.StreamHelper;
+import org.apache.poi.openxml4j.opc.internal.ZipHelper;
+
+/**
+ * Package core properties marshaller specialized for zipped package.
+ *
+ * @author Julien Chable
+ */
+public final class ZipPackagePropertiesMarshaller extends PackagePropertiesMarshaller {
+
+       @Override
+       public boolean marshall(PackagePart part, OutputStream out)
+                       throws OpenXML4JException {
+               if (!(out instanceof ZipOutputStream)) {
+                       throw new IllegalArgumentException("ZipOutputStream expected!");
+               }
+               ZipOutputStream zos = (ZipOutputStream) out;
+
+               // Saving the part in the zip file
+               ZipEntry ctEntry = new ZipEntry(ZipHelper
+                               .getZipItemNameFromOPCName(part.getPartName().getURI()
+                                               .toString()));
+               try {
+                       // Save in ZIP
+                       zos.putNextEntry(ctEntry); // Add entry in ZIP
+                       super.marshall(part, out); // Marshall the properties inside a XML
+                       // Document
+                       if (!StreamHelper.saveXmlInStream(xmlDoc, out)) {
+                               return false;
+                       }
+                       zos.closeEntry();
+               } catch (IOException e) {
+                       throw new OpenXML4JException(e.getLocalizedMessage());
+               }
+               return true;
+       }
+}
index c226ba5a42c9487904ba929ab006ce5e64128e84..b59a78b74c29d3873ad231901d51fe01ab257c5d 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal.marshallers;\r
-\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.io.OutputStream;\r
-import java.net.URI;\r
-import java.util.zip.ZipEntry;\r
-import java.util.zip.ZipOutputStream;\r
-\r
-import org.dom4j.Document;\r
-import org.dom4j.DocumentHelper;\r
-import org.dom4j.Element;\r
-import org.dom4j.Namespace;\r
-import org.dom4j.QName;\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.PackageNamespaces;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.apache.poi.openxml4j.opc.PackagePartName;\r
-import org.apache.poi.openxml4j.opc.PackageRelationship;\r
-import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;\r
-import org.apache.poi.openxml4j.opc.PackagingURIHelper;\r
-import org.apache.poi.openxml4j.opc.StreamHelper;\r
-import org.apache.poi.openxml4j.opc.TargetMode;\r
-import org.apache.poi.openxml4j.opc.internal.PartMarshaller;\r
-import org.apache.poi.openxml4j.opc.internal.ZipHelper;\r
-import org.apache.poi.util.POILogger;\r
-import org.apache.poi.util.POILogFactory;\r
-\r
-/**\r
- * Zip part marshaller. This marshaller is use to save any part in a zip stream.\r
- * \r
- * @author Julien Chable\r
- * @version 0.1\r
- */\r
-public class ZipPartMarshaller implements PartMarshaller {\r
-    private static POILogger logger = POILogFactory.getLogger(ZipPartMarshaller.class);\r
-\r
-       /**\r
-        * Save the specified part.\r
-        * \r
-        * @throws OpenXML4JException\r
-        *             Throws if an internal exception is thrown.\r
-        */\r
-       public boolean marshall(PackagePart part, OutputStream os)\r
-                       throws OpenXML4JException {\r
-               if (!(os instanceof ZipOutputStream)) {\r
-                       logger.log(POILogger.ERROR,"Unexpected class " + os.getClass().getName());\r
-                       throw new OpenXML4JException("ZipOutputStream expected !");\r
-                       // Normally should happen only in developpement phase, so just throw\r
-                       // exception\r
-               }\r
-\r
-               ZipOutputStream zos = (ZipOutputStream) os;\r
-               ZipEntry partEntry = new ZipEntry(ZipHelper\r
-                               .getZipItemNameFromOPCName(part.getPartName().getURI()\r
-                                               .getPath()));\r
-               try {\r
-                       // Create next zip entry\r
-                       zos.putNextEntry(partEntry);\r
-\r
-                       // Saving data in the ZIP file\r
-                       InputStream ins = part.getInputStream();\r
-                       byte[] buff = new byte[ZipHelper.READ_WRITE_FILE_BUFFER_SIZE];\r
-                       while (ins.available() > 0) {\r
-                               int resultRead = ins.read(buff);\r
-                               if (resultRead == -1) {\r
-                                       // End of file reached\r
-                                       break;\r
-                               } else {\r
-                                       zos.write(buff, 0, resultRead);\r
-                               }\r
-                       }\r
-                       zos.closeEntry();\r
-               } catch (IOException ioe) {\r
-                       logger.log(POILogger.ERROR,"Cannot write: " + part.getPartName() + ": in ZIP",\r
-                                       ioe);\r
-                       return false;\r
-               }\r
-\r
-               // Saving relationship part\r
-               if (part.hasRelationships()) {\r
-                       PackagePartName relationshipPartName = PackagingURIHelper\r
-                                       .getRelationshipPartName(part.getPartName());\r
-\r
-                       marshallRelationshipPart(part.getRelationships(),\r
-                                       relationshipPartName, zos);\r
-\r
-               }\r
-               return true;\r
-       }\r
-\r
-       /**\r
-        * Save relationships into the part.\r
-        * \r
-        * @param rels\r
-        *            The relationships collection to marshall.\r
-        * @param relPartName\r
-        *            Part name of the relationship part to marshall.\r
-        * @param zos\r
-        *            Zip output stream in which to save the XML content of the\r
-        *            relationships serialization.\r
-        */\r
-       public static boolean marshallRelationshipPart(\r
-                       PackageRelationshipCollection rels, PackagePartName relPartName,\r
-                       ZipOutputStream zos) {\r
-               // Building xml\r
-               Document xmlOutDoc = DocumentHelper.createDocument();\r
-               // make something like <Relationships\r
-               // xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\r
-               Namespace dfNs = Namespace.get("", PackageNamespaces.RELATIONSHIPS);\r
-               Element root = xmlOutDoc.addElement(new QName(\r
-                               PackageRelationship.RELATIONSHIPS_TAG_NAME, dfNs));\r
-\r
-               // <Relationship\r
-               // TargetMode="External"\r
-               // Id="rIdx"\r
-               // Target="http://www.custom.com/images/pic1.jpg"\r
-               // Type="http://www.custom.com/external-resource"/>\r
-\r
-               URI sourcePartURI = PackagingURIHelper\r
-                               .getSourcePartUriFromRelationshipPartUri(relPartName.getURI());\r
-\r
-               for (PackageRelationship rel : rels) {\r
-                       // the relationship element\r
-                       Element relElem = root\r
-                                       .addElement(PackageRelationship.RELATIONSHIP_TAG_NAME);\r
-\r
-                       // the relationship ID\r
-                       relElem.addAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel\r
-                                       .getId());\r
-\r
-                       // the relationship Type\r
-                       relElem.addAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel\r
-                                       .getRelationshipType());\r
-\r
-                       // the relationship Target\r
-                       String targetValue;\r
-                       URI uri = rel.getTargetURI();\r
-                       if (rel.getTargetMode() == TargetMode.EXTERNAL) {\r
-                               // Save the target as-is - we don't need to validate it,\r
-                               //  alter it etc\r
-                targetValue = uri.toString();\r
-\r
-                               // add TargetMode attribute (as it is external link external)\r
-                               relElem.addAttribute(\r
-                                               PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME,\r
-                                               "External");\r
-                       } else {\r
-                               targetValue = PackagingURIHelper.relativizeURI(\r
-                                               sourcePartURI, rel.getTargetURI()).getPath();\r
-                       }\r
-                       relElem.addAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME,\r
-                                       targetValue);\r
-               }\r
-\r
-               xmlOutDoc.normalize();\r
-\r
-               // String schemaFilename = Configuration.getPathForXmlSchema()+\r
-               // File.separator + "opc-relationships.xsd";\r
-\r
-               // Save part in zip\r
-               ZipEntry ctEntry = new ZipEntry(ZipHelper.getZipURIFromOPCName(\r
-                               relPartName.getURI().toASCIIString()).getPath());\r
-               try {\r
-                       zos.putNextEntry(ctEntry);\r
-                       if (!StreamHelper.saveXmlInStream(xmlOutDoc, zos)) {\r
-                               return false;\r
-                       }\r
-                       zos.closeEntry();\r
-               } catch (IOException e) {\r
-                       logger.log(POILogger.ERROR,"Cannot create zip entry " + relPartName, e);\r
-                       return false;\r
-               }\r
-               return true; // success\r
-       }\r
-}\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.openxml4j.opc.internal.marshallers;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URI;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.dom4j.Document;
+import org.dom4j.DocumentHelper;
+import org.dom4j.Element;
+import org.dom4j.Namespace;
+import org.dom4j.QName;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.PackageNamespaces;
+import org.apache.poi.openxml4j.opc.PackagePart;
+import org.apache.poi.openxml4j.opc.PackagePartName;
+import org.apache.poi.openxml4j.opc.PackageRelationship;
+import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
+import org.apache.poi.openxml4j.opc.PackagingURIHelper;
+import org.apache.poi.openxml4j.opc.StreamHelper;
+import org.apache.poi.openxml4j.opc.TargetMode;
+import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
+import org.apache.poi.openxml4j.opc.internal.ZipHelper;
+import org.apache.poi.util.POILogger;
+import org.apache.poi.util.POILogFactory;
+
+/**
+ * Zip part marshaller. This marshaller is use to save any part in a zip stream.
+ *
+ * @author Julien Chable
+ */
+public final class ZipPartMarshaller implements PartMarshaller {
+       private static POILogger logger = POILogFactory.getLogger(ZipPartMarshaller.class);
+
+       /**
+        * Save the specified part.
+        *
+        * @throws OpenXML4JException
+        *             Throws if an internal exception is thrown.
+        */
+       public boolean marshall(PackagePart part, OutputStream os)
+                       throws OpenXML4JException {
+               if (!(os instanceof ZipOutputStream)) {
+                       logger.log(POILogger.ERROR,"Unexpected class " + os.getClass().getName());
+                       throw new OpenXML4JException("ZipOutputStream expected !");
+                       // Normally should happen only in developement phase, so just throw
+                       // exception
+               }
+
+               ZipOutputStream zos = (ZipOutputStream) os;
+               ZipEntry partEntry = new ZipEntry(ZipHelper
+                               .getZipItemNameFromOPCName(part.getPartName().getURI()
+                                               .getPath()));
+               try {
+                       // Create next zip entry
+                       zos.putNextEntry(partEntry);
+
+                       // Saving data in the ZIP file
+                       InputStream ins = part.getInputStream();
+                       byte[] buff = new byte[ZipHelper.READ_WRITE_FILE_BUFFER_SIZE];
+                       while (ins.available() > 0) {
+                               int resultRead = ins.read(buff);
+                               if (resultRead == -1) {
+                                       // End of file reached
+                                       break;
+                               }
+                               zos.write(buff, 0, resultRead);
+                       }
+                       zos.closeEntry();
+               } catch (IOException ioe) {
+                       logger.log(POILogger.ERROR,"Cannot write: " + part.getPartName() + ": in ZIP",
+                                       ioe);
+                       return false;
+               }
+
+               // Saving relationship part
+               if (part.hasRelationships()) {
+                       PackagePartName relationshipPartName = PackagingURIHelper
+                                       .getRelationshipPartName(part.getPartName());
+
+                       marshallRelationshipPart(part.getRelationships(),
+                                       relationshipPartName, zos);
+
+               }
+               return true;
+       }
+
+       /**
+        * Save relationships into the part.
+        *
+        * @param rels
+        *            The relationships collection to marshall.
+        * @param relPartName
+        *            Part name of the relationship part to marshall.
+        * @param zos
+        *            Zip output stream in which to save the XML content of the
+        *            relationships serialization.
+        */
+       public static boolean marshallRelationshipPart(
+                       PackageRelationshipCollection rels, PackagePartName relPartName,
+                       ZipOutputStream zos) {
+               // Building xml
+               Document xmlOutDoc = DocumentHelper.createDocument();
+               // make something like <Relationships
+               // xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
+               Namespace dfNs = Namespace.get("", PackageNamespaces.RELATIONSHIPS);
+               Element root = xmlOutDoc.addElement(new QName(
+                               PackageRelationship.RELATIONSHIPS_TAG_NAME, dfNs));
+
+               // <Relationship
+               // TargetMode="External"
+               // Id="rIdx"
+               // Target="http://www.custom.com/images/pic1.jpg"
+               // Type="http://www.custom.com/external-resource"/>
+
+               URI sourcePartURI = PackagingURIHelper
+                               .getSourcePartUriFromRelationshipPartUri(relPartName.getURI());
+
+               for (PackageRelationship rel : rels) {
+                       // the relationship element
+                       Element relElem = root
+                                       .addElement(PackageRelationship.RELATIONSHIP_TAG_NAME);
+
+                       // the relationship ID
+                       relElem.addAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel
+                                       .getId());
+
+                       // the relationship Type
+                       relElem.addAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel
+                                       .getRelationshipType());
+
+                       // the relationship Target
+                       String targetValue;
+                       URI uri = rel.getTargetURI();
+                       if (rel.getTargetMode() == TargetMode.EXTERNAL) {
+                               // Save the target as-is - we don't need to validate it,
+                               //  alter it etc
+                               targetValue = uri.toString();
+
+                               // add TargetMode attribute (as it is external link external)
+                               relElem.addAttribute(
+                                               PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME,
+                                               "External");
+                       } else {
+                               targetValue = PackagingURIHelper.relativizeURI(
+                                               sourcePartURI, rel.getTargetURI()).getPath();
+                       }
+                       relElem.addAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME,
+                                       targetValue);
+               }
+
+               xmlOutDoc.normalize();
+
+               // String schemaFilename = Configuration.getPathForXmlSchema()+
+               // File.separator + "opc-relationships.xsd";
+
+               // Save part in zip
+               ZipEntry ctEntry = new ZipEntry(ZipHelper.getZipURIFromOPCName(
+                               relPartName.getURI().toASCIIString()).getPath());
+               try {
+                       zos.putNextEntry(ctEntry);
+                       if (!StreamHelper.saveXmlInStream(xmlOutDoc, zos)) {
+                               return false;
+                       }
+                       zos.closeEntry();
+               } catch (IOException e) {
+                       logger.log(POILogger.ERROR,"Cannot create zip entry " + relPartName, e);
+                       return false;
+               }
+               return true; // success
+       }
+}
index bce033e3e339dd9869b6f0c7da6a9f1ab8d982c7..19ba500f2eaea652bcf936f00adc568d86da5f60 100755 (executable)
@@ -1,78 +1,78 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal.signature;\r
-\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.io.OutputStream;\r
-\r
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.apache.poi.openxml4j.opc.internal.ContentType;\r
-\r
-/**\r
- * Digital certificate part.\r
- * \r
- * @author Julien Chable\r
- * @version 0.1\r
- */\r
-public final class DigitalCertificatePart extends PackagePart  {\r
-\r
-       public DigitalCertificatePart() throws InvalidFormatException{\r
-               super(null, null, new ContentType(""));\r
-               // Review constructor\r
-       }\r
-       \r
-       @Override\r
-       public void close() {\r
-               // TODO Auto-generated method stub\r
-               \r
-       }\r
-\r
-       @Override\r
-       public void flush() {\r
-               // TODO Auto-generated method stub\r
-               \r
-       }\r
-\r
-       @Override\r
-       protected InputStream getInputStreamImpl() throws IOException {\r
-               // TODO Auto-generated method stub\r
-               return null;\r
-       }\r
-\r
-       @Override\r
-       protected OutputStream getOutputStreamImpl() {\r
-               // TODO Auto-generated method stub\r
-               return null;\r
-       }\r
-\r
-       @Override\r
-       public boolean load(InputStream ios) throws InvalidFormatException {\r
-               // TODO Auto-generated method stub\r
-               return false;\r
-       }\r
-\r
-       @Override\r
-       public boolean save(OutputStream zos) throws OpenXML4JException {\r
-               // TODO Auto-generated method stub\r
-               return false;\r
-       }\r
-\r
-}\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.openxml4j.opc.internal.signature;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.PackagePart;
+import org.apache.poi.openxml4j.opc.internal.ContentType;
+
+/**
+ * Digital certificate part.
+ *
+ * @author Julien Chable
+ * @version 0.1
+ */
+public final class DigitalCertificatePart extends PackagePart  {
+
+       public DigitalCertificatePart() throws InvalidFormatException{
+               super(null, null, new ContentType(""));
+               // Review constructor
+       }
+
+       @Override
+       public void close() {
+               // TODO Auto-generated method stub
+
+       }
+
+       @Override
+       public void flush() {
+               // TODO Auto-generated method stub
+
+       }
+
+       @Override
+       protected InputStream getInputStreamImpl() throws IOException {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+       @Override
+       protected OutputStream getOutputStreamImpl() {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+       @Override
+       public boolean load(InputStream ios) throws InvalidFormatException {
+               // TODO Auto-generated method stub
+               return false;
+       }
+
+       @Override
+       public boolean save(OutputStream zos) throws OpenXML4JException {
+               // TODO Auto-generated method stub
+               return false;
+       }
+
+}
index 718e78b765bb692a07a622c6e4bc7b1be16775fc..b6c1a8ac873412fd271a10b70b0e3282131d591f 100755 (executable)
@@ -1,28 +1,28 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal.signature;\r
-\r
-/**\r
- * Represents a digital signature origin part.\r
- * \r
- * @author Julien Chable\r
- * @version 0.1\r
- */\r
-public class DigitalSignatureOriginPart {\r
-\r
-}\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.openxml4j.opc.internal.signature;
+
+/**
+ * Represents a digital signature origin part.
+ *
+ * @author Julien Chable
+ * @version 0.1
+ */
+public final class DigitalSignatureOriginPart {
+
+}
index fc03b022ffe7ce1c37512e6b5f61cf222a56560e..a86f56d0af1510762d05b91692f99da042b87010 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.internal.unmarshallers;\r
-\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.zip.ZipEntry;\r
-\r
-import org.dom4j.Attribute;\r
-import org.dom4j.Document;\r
-import org.dom4j.DocumentException;\r
-import org.dom4j.Element;\r
-import org.dom4j.Namespace;\r
-import org.dom4j.QName;\r
-import org.dom4j.io.SAXReader;\r
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.PackageNamespaces;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.apache.poi.openxml4j.opc.PackageProperties;\r
-import org.apache.poi.openxml4j.opc.ZipPackage;\r
-import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;\r
-import org.apache.poi.openxml4j.opc.internal.PartUnmarshaller;\r
-import org.apache.poi.openxml4j.opc.internal.ZipHelper;\r
-\r
-/**\r
- * Package properties unmarshaller.\r
- * \r
- * @author Julien Chable\r
- * @version 1.0\r
- */\r
-public class PackagePropertiesUnmarshaller implements PartUnmarshaller {\r
-\r
-       private final static Namespace namespaceDC = new Namespace("dc",\r
-                       PackageProperties.NAMESPACE_DC);\r
-\r
-       private final static Namespace namespaceCP = new Namespace("cp",\r
-                       PackageNamespaces.CORE_PROPERTIES);\r
-\r
-       private final static Namespace namespaceDcTerms = new Namespace("dcterms",\r
-                       PackageProperties.NAMESPACE_DCTERMS);\r
-\r
-       private final static Namespace namespaceXML = new Namespace("xml",\r
-                       "http://www.w3.org/XML/1998/namespace");\r
-\r
-       private final static Namespace namespaceXSI = new Namespace("xsi",\r
-                       "http://www.w3.org/2001/XMLSchema-instance");\r
-\r
-       protected static final String KEYWORD_CATEGORY = "category";\r
-\r
-       protected static final String KEYWORD_CONTENT_STATUS = "contentStatus";\r
-\r
-       protected static final String KEYWORD_CONTENT_TYPE = "contentType";\r
-\r
-       protected static final String KEYWORD_CREATED = "created";\r
-\r
-       protected static final String KEYWORD_CREATOR = "creator";\r
-\r
-       protected static final String KEYWORD_DESCRIPTION = "description";\r
-\r
-       protected static final String KEYWORD_IDENTIFIER = "identifier";\r
-\r
-       protected static final String KEYWORD_KEYWORDS = "keywords";\r
-\r
-       protected static final String KEYWORD_LANGUAGE = "language";\r
-\r
-       protected static final String KEYWORD_LAST_MODIFIED_BY = "lastModifiedBy";\r
-\r
-       protected static final String KEYWORD_LAST_PRINTED = "lastPrinted";\r
-\r
-       protected static final String KEYWORD_MODIFIED = "modified";\r
-\r
-       protected static final String KEYWORD_REVISION = "revision";\r
-\r
-       protected static final String KEYWORD_SUBJECT = "subject";\r
-\r
-       protected static final String KEYWORD_TITLE = "title";\r
-\r
-       protected static final String KEYWORD_VERSION = "version";\r
-\r
-       // TODO Load element with XMLBeans or dynamic table\r
-       // TODO Check every element/namespace for compliance\r
-       public PackagePart unmarshall(UnmarshallContext context, InputStream in)\r
-                       throws InvalidFormatException, IOException {\r
-               PackagePropertiesPart coreProps = new PackagePropertiesPart(context\r
-                               .getPackage(), context.getPartName());\r
-\r
-               // If the input stream is null then we try to get it from the\r
-               // package.\r
-               if (in == null) {\r
-                       if (context.getZipEntry() != null) {\r
-                               in = ((ZipPackage) context.getPackage()).getZipArchive()\r
-                                               .getInputStream(context.getZipEntry());\r
-                       } else if (context.getPackage() != null) {\r
-                               // Try to retrieve the part inputstream from the URI\r
-                               ZipEntry zipEntry;\r
-                               try {\r
-                                       zipEntry = ZipHelper\r
-                                                       .getCorePropertiesZipEntry((ZipPackage) context\r
-                                                                       .getPackage());\r
-                               } catch (OpenXML4JException e) {\r
-                                       throw new IOException(\r
-                                                       "Error while trying to get the part input stream.");\r
-                               }\r
-                               in = ((ZipPackage) context.getPackage()).getZipArchive()\r
-                                               .getInputStream(zipEntry);\r
-                       } else\r
-                               throw new IOException(\r
-                                               "Error while trying to get the part input stream.");\r
-               }\r
-\r
-               SAXReader xmlReader = new SAXReader();\r
-               Document xmlDoc;\r
-               try {\r
-                       xmlDoc = xmlReader.read(in);\r
-\r
-                       /* Check OPC compliance */\r
-\r
-                       // Rule M4.2, M4.3, M4.4 and M4.5/\r
-                       checkElementForOPCCompliance(xmlDoc.getRootElement());\r
-\r
-                       /* End OPC compliance */\r
-\r
-               } catch (DocumentException e) {\r
-                       throw new IOException(e.getMessage());\r
-               }\r
-\r
-               coreProps.setCategoryProperty(loadCategory(xmlDoc));\r
-               coreProps.setContentStatusProperty(loadContentStatus(xmlDoc));\r
-               coreProps.setContentTypeProperty(loadContentType(xmlDoc));\r
-               coreProps.setCreatedProperty(loadCreated(xmlDoc));\r
-               coreProps.setCreatorProperty(loadCreator(xmlDoc));\r
-               coreProps.setDescriptionProperty(loadDescription(xmlDoc));\r
-               coreProps.setIdentifierProperty(loadIdentifier(xmlDoc));\r
-               coreProps.setKeywordsProperty(loadKeywords(xmlDoc));\r
-               coreProps.setLanguageProperty(loadLanguage(xmlDoc));\r
-               coreProps.setLastModifiedByProperty(loadLastModifiedBy(xmlDoc));\r
-               coreProps.setLastPrintedProperty(loadLastPrinted(xmlDoc));\r
-               coreProps.setModifiedProperty(loadModified(xmlDoc));\r
-               coreProps.setRevisionProperty(loadRevision(xmlDoc));\r
-               coreProps.setSubjectProperty(loadSubject(xmlDoc));\r
-               coreProps.setTitleProperty(loadTitle(xmlDoc));\r
-               coreProps.setVersionProperty(loadVersion(xmlDoc));\r
-\r
-               return coreProps;\r
-       }\r
-\r
-       private String loadCategory(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_CATEGORY, namespaceCP));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadContentStatus(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_CONTENT_STATUS, namespaceCP));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadContentType(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_CONTENT_TYPE, namespaceCP));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadCreated(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_CREATED, namespaceDcTerms));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadCreator(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_CREATOR, namespaceDC));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadDescription(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_DESCRIPTION, namespaceDC));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadIdentifier(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_IDENTIFIER, namespaceDC));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadKeywords(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_KEYWORDS, namespaceCP));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadLanguage(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_LANGUAGE, namespaceDC));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadLastModifiedBy(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_LAST_MODIFIED_BY, namespaceCP));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadLastPrinted(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_LAST_PRINTED, namespaceCP));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadModified(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_MODIFIED, namespaceDcTerms));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadRevision(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_REVISION, namespaceCP));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadSubject(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_SUBJECT, namespaceDC));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadTitle(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_TITLE, namespaceDC));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       private String loadVersion(Document xmlDoc) {\r
-               Element el = xmlDoc.getRootElement().element(\r
-                               new QName(KEYWORD_VERSION, namespaceCP));\r
-               if (el != null)\r
-                       return el.getStringValue();\r
-               else\r
-                       return null;\r
-       }\r
-\r
-       /* OPC Compliance methods */\r
-\r
-       /**\r
-        * Check the element for the following OPC compliance rules:\r
-        * <p>\r
-        * Rule M4.2: A format consumer shall consider the use of the Markup\r
-        * Compatibility namespace to be an error.\r
-        * </p><p>\r
-        * Rule M4.3: Producers shall not create a document element that contains\r
-        * refinements to the Dublin Core elements, except for the two specified in\r
-        * the schema: <dcterms:created> and <dcterms:modified> Consumers shall\r
-        * consider a document element that violates this constraint to be an error.\r
-        * </p><p>\r
-        * Rule M4.4: Producers shall not create a document element that contains\r
-        * the xml:lang attribute. Consumers shall consider a document element that\r
-        * violates this constraint to be an error.\r
-        *  </p><p>\r
-        * Rule M4.5: Producers shall not create a document element that contains\r
-        * the xsi:type attribute, except for a <dcterms:created> or\r
-        * <dcterms:modified> element where the xsi:type attribute shall be present\r
-        * and shall hold the value dcterms:W3CDTF, where dcterms is the namespace\r
-        * prefix of the Dublin Core namespace. Consumers shall consider a document\r
-        * element that violates this constraint to be an error.\r
-     * </p>\r
-        */\r
-       public void checkElementForOPCCompliance(Element el)\r
-                       throws InvalidFormatException {\r
-               // Check the current element\r
-               List declaredNamespaces = el.declaredNamespaces();\r
-               Iterator itNS = declaredNamespaces.iterator();\r
-               while (itNS.hasNext()) {\r
-                       Namespace ns = (Namespace) itNS.next();\r
-\r
-                       // Rule M4.2\r
-                       if (ns.getURI().equals(PackageNamespaces.MARKUP_COMPATIBILITY))\r
-                               throw new InvalidFormatException(\r
-                                               "OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.");\r
-               }\r
-\r
-               // Rule M4.3\r
-               if (el.getNamespace().getURI().equals(\r
-                               PackageProperties.NAMESPACE_DCTERMS)\r
-                               && !(el.getName().equals(KEYWORD_CREATED) || el.getName()\r
-                                               .equals(KEYWORD_MODIFIED)))\r
-                       throw new InvalidFormatException(\r
-                                       "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.");\r
-\r
-               // Rule M4.4\r
-               if (el.attribute(new QName("lang", namespaceXML)) != null)\r
-                       throw new InvalidFormatException(\r
-                                       "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.");\r
-\r
-               // Rule M4.5\r
-               if (el.getNamespace().getURI().equals(\r
-                               PackageProperties.NAMESPACE_DCTERMS)) {\r
-                       // DCTerms namespace only use with 'created' and 'modified' elements\r
-                       String elName = el.getName();\r
-                       if (!(elName.equals(KEYWORD_CREATED) || elName\r
-                                       .equals(KEYWORD_MODIFIED)))\r
-                               throw new InvalidFormatException("Namespace error : " + elName\r
-                                               + " shouldn't have the following naemspace -> "\r
-                                               + PackageProperties.NAMESPACE_DCTERMS);\r
-\r
-                       // Check for the 'xsi:type' attribute\r
-                       Attribute typeAtt = el.attribute(new QName("type", namespaceXSI));\r
-                       if (typeAtt == null)\r
-                               throw new InvalidFormatException("The element '" + elName\r
-                                               + "' must have the '" + namespaceXSI.getPrefix()\r
-                                               + ":type' attribute present !");\r
-\r
-                       // Check for the attribute value => 'dcterms:W3CDTF'\r
-                       if (!typeAtt.getValue().equals("dcterms:W3CDTF"))\r
-                               throw new InvalidFormatException("The element '" + elName\r
-                                               + "' must have the '" + namespaceXSI.getPrefix()\r
-                                               + ":type' attribute with the value 'dcterms:W3CDTF' !");\r
-               }\r
-\r
-               // Check its children\r
-               Iterator itChildren = el.elementIterator();\r
-               while (itChildren.hasNext())\r
-                       checkElementForOPCCompliance((Element) itChildren.next());\r
-       }\r
-}\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.openxml4j.opc.internal.unmarshallers;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Iterator;
+import java.util.List;
+import java.util.zip.ZipEntry;
+
+import org.dom4j.Attribute;
+import org.dom4j.Document;
+import org.dom4j.DocumentException;
+import org.dom4j.Element;
+import org.dom4j.Namespace;
+import org.dom4j.QName;
+import org.dom4j.io.SAXReader;
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.PackageNamespaces;
+import org.apache.poi.openxml4j.opc.PackagePart;
+import org.apache.poi.openxml4j.opc.PackageProperties;
+import org.apache.poi.openxml4j.opc.ZipPackage;
+import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
+import org.apache.poi.openxml4j.opc.internal.PartUnmarshaller;
+import org.apache.poi.openxml4j.opc.internal.ZipHelper;
+
+/**
+ * Package properties unmarshaller.
+ *
+ * @author Julien Chable
+ * @version 1.0
+ */
+public final class PackagePropertiesUnmarshaller implements PartUnmarshaller {
+
+       private final static Namespace namespaceDC = new Namespace("dc",
+                       PackageProperties.NAMESPACE_DC);
+
+       private final static Namespace namespaceCP = new Namespace("cp",
+                       PackageNamespaces.CORE_PROPERTIES);
+
+       private final static Namespace namespaceDcTerms = new Namespace("dcterms",
+                       PackageProperties.NAMESPACE_DCTERMS);
+
+       private final static Namespace namespaceXML = new Namespace("xml",
+                       "http://www.w3.org/XML/1998/namespace");
+
+       private final static Namespace namespaceXSI = new Namespace("xsi",
+                       "http://www.w3.org/2001/XMLSchema-instance");
+
+       protected static final String KEYWORD_CATEGORY = "category";
+
+       protected static final String KEYWORD_CONTENT_STATUS = "contentStatus";
+
+       protected static final String KEYWORD_CONTENT_TYPE = "contentType";
+
+       protected static final String KEYWORD_CREATED = "created";
+
+       protected static final String KEYWORD_CREATOR = "creator";
+
+       protected static final String KEYWORD_DESCRIPTION = "description";
+
+       protected static final String KEYWORD_IDENTIFIER = "identifier";
+
+       protected static final String KEYWORD_KEYWORDS = "keywords";
+
+       protected static final String KEYWORD_LANGUAGE = "language";
+
+       protected static final String KEYWORD_LAST_MODIFIED_BY = "lastModifiedBy";
+
+       protected static final String KEYWORD_LAST_PRINTED = "lastPrinted";
+
+       protected static final String KEYWORD_MODIFIED = "modified";
+
+       protected static final String KEYWORD_REVISION = "revision";
+
+       protected static final String KEYWORD_SUBJECT = "subject";
+
+       protected static final String KEYWORD_TITLE = "title";
+
+       protected static final String KEYWORD_VERSION = "version";
+
+       // TODO Load element with XMLBeans or dynamic table
+       // TODO Check every element/namespace for compliance
+       public PackagePart unmarshall(UnmarshallContext context, InputStream in)
+                       throws InvalidFormatException, IOException {
+               PackagePropertiesPart coreProps = new PackagePropertiesPart(context
+                               .getPackage(), context.getPartName());
+
+               // If the input stream is null then we try to get it from the
+               // package.
+               if (in == null) {
+                       if (context.getZipEntry() != null) {
+                               in = ((ZipPackage) context.getPackage()).getZipArchive()
+                                               .getInputStream(context.getZipEntry());
+                       } else if (context.getPackage() != null) {
+                               // Try to retrieve the part inputstream from the URI
+                               ZipEntry zipEntry;
+                               try {
+                                       zipEntry = ZipHelper
+                                                       .getCorePropertiesZipEntry((ZipPackage) context
+                                                                       .getPackage());
+                               } catch (OpenXML4JException e) {
+                                       throw new IOException(
+                                                       "Error while trying to get the part input stream.");
+                               }
+                               in = ((ZipPackage) context.getPackage()).getZipArchive()
+                                               .getInputStream(zipEntry);
+                       } else
+                               throw new IOException(
+                                               "Error while trying to get the part input stream.");
+               }
+
+               SAXReader xmlReader = new SAXReader();
+               Document xmlDoc;
+               try {
+                       xmlDoc = xmlReader.read(in);
+
+                       /* Check OPC compliance */
+
+                       // Rule M4.2, M4.3, M4.4 and M4.5/
+                       checkElementForOPCCompliance(xmlDoc.getRootElement());
+
+                       /* End OPC compliance */
+
+               } catch (DocumentException e) {
+                       throw new IOException(e.getMessage());
+               }
+
+               coreProps.setCategoryProperty(loadCategory(xmlDoc));
+               coreProps.setContentStatusProperty(loadContentStatus(xmlDoc));
+               coreProps.setContentTypeProperty(loadContentType(xmlDoc));
+               coreProps.setCreatedProperty(loadCreated(xmlDoc));
+               coreProps.setCreatorProperty(loadCreator(xmlDoc));
+               coreProps.setDescriptionProperty(loadDescription(xmlDoc));
+               coreProps.setIdentifierProperty(loadIdentifier(xmlDoc));
+               coreProps.setKeywordsProperty(loadKeywords(xmlDoc));
+               coreProps.setLanguageProperty(loadLanguage(xmlDoc));
+               coreProps.setLastModifiedByProperty(loadLastModifiedBy(xmlDoc));
+               coreProps.setLastPrintedProperty(loadLastPrinted(xmlDoc));
+               coreProps.setModifiedProperty(loadModified(xmlDoc));
+               coreProps.setRevisionProperty(loadRevision(xmlDoc));
+               coreProps.setSubjectProperty(loadSubject(xmlDoc));
+               coreProps.setTitleProperty(loadTitle(xmlDoc));
+               coreProps.setVersionProperty(loadVersion(xmlDoc));
+
+               return coreProps;
+       }
+
+       private String loadCategory(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_CATEGORY, namespaceCP));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadContentStatus(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_CONTENT_STATUS, namespaceCP));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadContentType(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_CONTENT_TYPE, namespaceCP));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadCreated(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_CREATED, namespaceDcTerms));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadCreator(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_CREATOR, namespaceDC));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadDescription(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_DESCRIPTION, namespaceDC));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadIdentifier(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_IDENTIFIER, namespaceDC));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadKeywords(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_KEYWORDS, namespaceCP));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadLanguage(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_LANGUAGE, namespaceDC));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadLastModifiedBy(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_LAST_MODIFIED_BY, namespaceCP));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadLastPrinted(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_LAST_PRINTED, namespaceCP));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadModified(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_MODIFIED, namespaceDcTerms));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadRevision(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_REVISION, namespaceCP));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadSubject(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_SUBJECT, namespaceDC));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadTitle(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_TITLE, namespaceDC));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       private String loadVersion(Document xmlDoc) {
+               Element el = xmlDoc.getRootElement().element(
+                               new QName(KEYWORD_VERSION, namespaceCP));
+               if (el == null) {
+                       return null;
+               }
+               return el.getStringValue();
+       }
+
+       /* OPC Compliance methods */
+
+       /**
+        * Check the element for the following OPC compliance rules:
+        * <p>
+        * Rule M4.2: A format consumer shall consider the use of the Markup
+        * Compatibility namespace to be an error.
+        * </p><p>
+        * Rule M4.3: Producers shall not create a document element that contains
+        * refinements to the Dublin Core elements, except for the two specified in
+        * the schema: <dcterms:created> and <dcterms:modified> Consumers shall
+        * consider a document element that violates this constraint to be an error.
+        * </p><p>
+        * Rule M4.4: Producers shall not create a document element that contains
+        * the xml:lang attribute. Consumers shall consider a document element that
+        * violates this constraint to be an error.
+        *  </p><p>
+        * Rule M4.5: Producers shall not create a document element that contains
+        * the xsi:type attribute, except for a <dcterms:created> or
+        * <dcterms:modified> element where the xsi:type attribute shall be present
+        * and shall hold the value dcterms:W3CDTF, where dcterms is the namespace
+        * prefix of the Dublin Core namespace. Consumers shall consider a document
+        * element that violates this constraint to be an error.
+        * </p>
+        */
+       public void checkElementForOPCCompliance(Element el)
+                       throws InvalidFormatException {
+               // Check the current element
+               @SuppressWarnings("unchecked")
+               List<Namespace> declaredNamespaces = el.declaredNamespaces();
+               Iterator<Namespace> itNS = declaredNamespaces.iterator();
+               while (itNS.hasNext()) {
+                       Namespace ns = itNS.next();
+
+                       // Rule M4.2
+                       if (ns.getURI().equals(PackageNamespaces.MARKUP_COMPATIBILITY))
+                               throw new InvalidFormatException(
+                                               "OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.");
+               }
+
+               // Rule M4.3
+               if (el.getNamespace().getURI().equals(
+                               PackageProperties.NAMESPACE_DCTERMS)
+                               && !(el.getName().equals(KEYWORD_CREATED) || el.getName()
+                                               .equals(KEYWORD_MODIFIED)))
+                       throw new InvalidFormatException(
+                                       "OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.");
+
+               // Rule M4.4
+               if (el.attribute(new QName("lang", namespaceXML)) != null)
+                       throw new InvalidFormatException(
+                                       "OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.");
+
+               // Rule M4.5
+               if (el.getNamespace().getURI().equals(
+                               PackageProperties.NAMESPACE_DCTERMS)) {
+                       // DCTerms namespace only use with 'created' and 'modified' elements
+                       String elName = el.getName();
+                       if (!(elName.equals(KEYWORD_CREATED) || elName
+                                       .equals(KEYWORD_MODIFIED)))
+                               throw new InvalidFormatException("Namespace error : " + elName
+                                               + " shouldn't have the following naemspace -> "
+                                               + PackageProperties.NAMESPACE_DCTERMS);
+
+                       // Check for the 'xsi:type' attribute
+                       Attribute typeAtt = el.attribute(new QName("type", namespaceXSI));
+                       if (typeAtt == null)
+                               throw new InvalidFormatException("The element '" + elName
+                                               + "' must have the '" + namespaceXSI.getPrefix()
+                                               + ":type' attribute present !");
+
+                       // Check for the attribute value => 'dcterms:W3CDTF'
+                       if (!typeAtt.getValue().equals("dcterms:W3CDTF"))
+                               throw new InvalidFormatException("The element '" + elName
+                                               + "' must have the '" + namespaceXSI.getPrefix()
+                                               + ":type' attribute with the value 'dcterms:W3CDTF' !");
+               }
+
+               // Check its children
+               @SuppressWarnings("unchecked")
+               Iterator<Element> itChildren = el.elementIterator();
+               while (itChildren.hasNext())
+                       checkElementForOPCCompliance(itChildren.next());
+       }
+}
index 8922641ce60dafbf8a9629a9601b752e79b87b3b..c7a9b8f7ea15fc3385db64ccacc198fa3b25016e 100755 (executable)
@@ -1,70 +1,70 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.signature;\r
-\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.io.OutputStream;\r
-\r
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;\r
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.apache.poi.openxml4j.opc.internal.ContentType;\r
-\r
-public class PackageDigitalSignature extends PackagePart {\r
-\r
-       public PackageDigitalSignature() throws InvalidFormatException {\r
-               super(null, null, new ContentType(""));\r
-       }\r
-\r
-       @Override\r
-       public void close() {\r
-               // TODO Auto-generated method stub\r
-\r
-       }\r
-\r
-       @Override\r
-       public void flush() {\r
-               // TODO Auto-generated method stub\r
-\r
-       }\r
-\r
-       @Override\r
-       protected InputStream getInputStreamImpl() throws IOException {\r
-               // TODO Auto-generated method stub\r
-               return null;\r
-       }\r
-\r
-       @Override\r
-       protected OutputStream getOutputStreamImpl() {\r
-               // TODO Auto-generated method stub\r
-               return null;\r
-       }\r
-\r
-       @Override\r
-       public boolean load(InputStream ios) throws InvalidFormatException {\r
-               // TODO Auto-generated method stub\r
-               return false;\r
-       }\r
-\r
-       @Override\r
-       public boolean save(OutputStream zos) throws OpenXML4JException {\r
-               // TODO Auto-generated method stub\r
-               return false;\r
-       }\r
-}\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.openxml4j.opc.signature;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.PackagePart;
+import org.apache.poi.openxml4j.opc.internal.ContentType;
+
+public final class PackageDigitalSignature extends PackagePart {
+
+       public PackageDigitalSignature() throws InvalidFormatException {
+               super(null, null, new ContentType(""));
+       }
+
+       @Override
+       public void close() {
+               // TODO Auto-generated method stub
+
+       }
+
+       @Override
+       public void flush() {
+               // TODO Auto-generated method stub
+
+       }
+
+       @Override
+       protected InputStream getInputStreamImpl() throws IOException {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+       @Override
+       protected OutputStream getOutputStreamImpl() {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+       @Override
+       public boolean load(InputStream ios) throws InvalidFormatException {
+               // TODO Auto-generated method stub
+               return false;
+       }
+
+       @Override
+       public boolean save(OutputStream zos) throws OpenXML4JException {
+               // TODO Auto-generated method stub
+               return false;
+       }
+}
index 0e5136d3ac189b40bdfbaae9fa35eaacbfebbc1e..64007f6f001e9163271e8bf1679843cacf758768 100755 (executable)
@@ -1,22 +1,22 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.openxml4j.opc.signature;\r
-\r
-public class PackageDigitalSignatureManager {\r
-\r
-}\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.openxml4j.opc.signature;
+
+public final class PackageDigitalSignatureManager {
+
+}
index 9bcea2e3cef8d5786ac63816d200bdadbe5f1382..8c1a24c8636bb758049a91c8f8c9dcc797b757db 100755 (executable)
@@ -1,71 +1,72 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.openxml4j.util;\r
-\r
-/**\r
- * An immutable object that could be defined as null.\r
- * \r
- * @author Julien Chable\r
- * @version 0.9\r
- */\r
-public final class Nullable<E> {\r
-\r
-       private E value;\r
-\r
-       /**\r
-        * Constructor.\r
-        */\r
-       public Nullable() {\r
-               // Do nothing\r
-       }\r
-\r
-       /**\r
-        * Constructor.\r
-        * \r
-        * @param value\r
-        *            The value to set to this nullable.\r
-        */\r
-       public Nullable(E value) {\r
-               this.value = value;\r
-       }\r
-\r
-       /**\r
-        * Get the store value if any.\r
-        * \r
-        * @return the store value\r
-        */\r
-       public E getValue() {\r
-               return value;\r
-       }\r
-\r
-       /**\r
-        * Get the status of this nullable.\r
-        * \r
-        * @return <b>true</b> if the nullable store a value (empty string is\r
-        *         considered to be a value) else <b>false</>.\r
-        */\r
-       public boolean hasValue() {\r
-               return value != null;\r
-       }\r
-\r
-       /**\r
-        * Set the stored value to <i>null</i>.\r
-        */\r
-       public void nullify() {\r
-               value = null;\r
-       }\r
-}\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.openxml4j.util;
+
+/**
+ * An immutable object that could be defined as null.
+ *
+ * @author Julien Chable
+ * @version 0.9
+ */
+public final class Nullable<E> {
+
+       private E value;
+
+       /**
+        * Constructor.
+        */
+       public Nullable() {
+               // Do nothing
+       }
+
+       /**
+        * Constructor.
+        *
+        * @param value
+        *            The value to set to this nullable.
+        */
+       public Nullable(E value) {
+               this.value = value;
+       }
+
+       /**
+        * Get the store value if any.
+        *
+        * @return the store value
+        */
+       public E getValue() {
+               return value;
+       }
+
+       /**
+        * Get the status of this nullable.
+        *
+        * @return <b>true</b> if the nullable store a value (empty string is
+        *         considered to be a value) else <b>false</>.
+        */
+       public boolean hasValue() {
+               return value != null;
+       }
+
+       /**
+        * Set the stored value to <i>null</i>.
+        */
+       public void nullify() {
+               value = null;
+       }
+}
index 30a800e5314a5b8c7739fdf2cf708755a0097521..af1d55a9607aa3ae02e6a668bd14c0a3e8d92c60 100755 (executable)
@@ -1,90 +1,91 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.dev;\r
-\r
-import org.apache.xmlbeans.XmlObject;\r
-import org.apache.xmlbeans.XmlOptions;\r
-\r
-import javax.xml.parsers.DocumentBuilderFactory;\r
-import javax.xml.parsers.DocumentBuilder;\r
-import java.io.*;\r
-import java.util.zip.ZipFile;\r
-import java.util.zip.ZipEntry;\r
-import java.util.Enumeration;\r
-\r
-/**\r
- * Utility class which dumps the contents of a *.xlsx file into file system.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFDump {\r
-\r
-    public static void main(String[] args) throws Exception {\r
-        for (int i = 0; i < args.length; i++) {\r
-            System.out.println("Dumping " + args[i]);\r
-            ZipFile zip = new ZipFile(args[i]);\r
-            dump(zip);\r
-        }\r
-    }\r
-\r
-    public static void dump(ZipFile zip) throws Exception {\r
-        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r
-        DocumentBuilder builder = factory.newDocumentBuilder();\r
-\r
-        String zipname = zip.getName();\r
-        int sep = zipname.lastIndexOf('.');\r
-        File root = new File(zipname.substring(0, sep));\r
-        root.mkdir();\r
-\r
-        Enumeration en = zip.entries();\r
-        while(en.hasMoreElements()){\r
-            ZipEntry entry = (ZipEntry)en.nextElement();\r
-            String name = entry.getName();\r
-            int idx = name.lastIndexOf('/');\r
-            if(idx != -1){\r
-                File bs = new File(root, name.substring(0, idx));\r
-                bs.mkdirs();\r
-            }\r
-\r
-            File f = new File(root, entry.getName());\r
-            FileOutputStream out = new FileOutputStream(f);\r
-\r
-            if(entry.getName().endsWith(".xml") || entry.getName().endsWith(".vml") || entry.getName().endsWith(".rels")){\r
-                try {\r
-                    XmlObject xml = XmlObject.Factory.parse(zip.getInputStream(entry));\r
-                    XmlOptions options = new XmlOptions();\r
-                    options.setSavePrettyPrint();\r
-                    xml.save(out, options);\r
-                } catch (Exception e){\r
-                    System.err.println("Failed to parse " + entry.getName() + ", dumping raw content");\r
-                    dump(zip.getInputStream(entry), out);\r
-                }\r
-            } else {\r
-                dump(zip.getInputStream(entry), out);\r
-            }\r
-            out.close();\r
-\r
-        }\r
-    }\r
-\r
-    protected static void dump(InputStream is, OutputStream out) throws IOException{\r
-        int pos;\r
-        byte[] chunk = new byte[2048];\r
-        while((pos = is.read(chunk)) > 0) out.write(chunk, 0, pos);\r
-\r
-    }\r
-}\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.dev;
+
+import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.XmlOptions;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.DocumentBuilder;
+import java.io.*;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipEntry;
+import java.util.Enumeration;
+
+/**
+ * Utility class which dumps the contents of a *.xlsx file into file system.
+ *
+ * @author Yegor Kozlov
+ */
+public final class XSSFDump {
+
+    public static void main(String[] args) throws Exception {
+        for (int i = 0; i < args.length; i++) {
+            System.out.println("Dumping " + args[i]);
+            ZipFile zip = new ZipFile(args[i]);
+            dump(zip);
+        }
+    }
+
+    public static void dump(ZipFile zip) throws Exception {
+        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+        DocumentBuilder builder = factory.newDocumentBuilder();
+
+        String zipname = zip.getName();
+        int sep = zipname.lastIndexOf('.');
+        File root = new File(zipname.substring(0, sep));
+        root.mkdir();
+
+        Enumeration en = zip.entries();
+        while(en.hasMoreElements()){
+            ZipEntry entry = (ZipEntry)en.nextElement();
+            String name = entry.getName();
+            int idx = name.lastIndexOf('/');
+            if(idx != -1){
+                File bs = new File(root, name.substring(0, idx));
+                bs.mkdirs();
+            }
+
+            File f = new File(root, entry.getName());
+            FileOutputStream out = new FileOutputStream(f);
+
+            if(entry.getName().endsWith(".xml") || entry.getName().endsWith(".vml") || entry.getName().endsWith(".rels")){
+                try {
+                    XmlObject xml = XmlObject.Factory.parse(zip.getInputStream(entry));
+                    XmlOptions options = new XmlOptions();
+                    options.setSavePrettyPrint();
+                    xml.save(out, options);
+                } catch (Exception e){
+                    System.err.println("Failed to parse " + entry.getName() + ", dumping raw content");
+                    dump(zip.getInputStream(entry), out);
+                }
+            } else {
+                dump(zip.getInputStream(entry), out);
+            }
+            out.close();
+
+        }
+    }
+
+    protected static void dump(InputStream is, OutputStream out) throws IOException{
+        int pos;
+        byte[] chunk = new byte[2048];
+        while((pos = is.read(chunk)) > 0) out.write(chunk, 0, pos);
+
+    }
+}
index 10a4b4755e020fa3b66b2451ed0a4898956337f9..4b2fc3ca53daa01ee239fe3d5c806d8dbfbd87c8 100755 (executable)
@@ -1,42 +1,43 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.dev;\r
-\r
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
-\r
-import java.io.FileOutputStream;\r
-\r
-/**\r
- * Utility which loads a SpreadsheetML file and saves it back.\r
- * This is a handy tool to investigate read-write round trip safety.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFSave {\r
-    public static void main(String[] args) throws Exception {\r
-        for (int i = 0; i < args.length; i++) {\r
-            XSSFWorkbook wb = new XSSFWorkbook(args[i]);\r
-\r
-            int sep = args[i].lastIndexOf('.');\r
-            String outfile = args[i].substring(0, sep) + "-save.xls" + (wb.isMacroEnabled() ? "m" : "x");\r
-            FileOutputStream out = new FileOutputStream(outfile);\r
-            wb.write(out);\r
-            out.close();\r
-        }\r
-    }\r
-\r
-}\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.dev;
+
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+import java.io.FileOutputStream;
+
+/**
+ * Utility which loads a SpreadsheetML file and saves it back.
+ * This is a handy tool to investigate read-write round trip safety.
+ *
+ * @author Yegor Kozlov
+ */
+public final class XSSFSave {
+    public static void main(String[] args) throws Exception {
+        for (int i = 0; i < args.length; i++) {
+            XSSFWorkbook wb = new XSSFWorkbook(args[i]);
+
+            int sep = args[i].lastIndexOf('.');
+            String outfile = args[i].substring(0, sep) + "-save.xls" + (wb.isMacroEnabled() ? "m" : "x");
+            FileOutputStream out = new FileOutputStream(outfile);
+            wb.write(out);
+            out.close();
+        }
+    }
+
+}
index f640f408df12c01f1009797034bb6d033e2a6b1c..a804176fcde277810a0819a0ac7b3dc35c98c06f 100755 (executable)
@@ -1,36 +1,37 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-/**\r
- * An anchor is what specifics the position of a shape within a client object\r
- * or within another containing shape.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public abstract class XSSFAnchor {\r
-    \r
-    public abstract int getDx1();\r
-    public abstract void setDx1( int dx1 );\r
-    public abstract int getDy1();\r
-    public abstract void setDy1( int dy1 );\r
-    public abstract int getDy2();\r
-    public abstract void setDy2( int dy2 );\r
-    public abstract int getDx2();\r
-    public abstract void setDx2( int dx2 );\r
-\r
-}\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.usermodel;
+
+/**
+ * An anchor is what specifics the position of a shape within a client object
+ * or within another containing shape.
+ *
+ * @author Yegor Kozlov
+ */
+public abstract class XSSFAnchor {
+
+    public abstract int getDx1();
+    public abstract void setDx1( int dx1 );
+    public abstract int getDy1();
+    public abstract void setDy1( int dy1 );
+    public abstract int getDy2();
+    public abstract void setDy2( int dy2 );
+    public abstract int getDx2();
+    public abstract void setDx2( int dx2 );
+
+}
index d02ee82d0271a635f180c786798d3c62ddb8552c..5032395394129e8fea084fa57f8532f0903c0ebf 100755 (executable)
@@ -1,81 +1,82 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D;\r
-import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;\r
-import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D;\r
-\r
-/**\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFChildAnchor extends XSSFAnchor {\r
-    private CTTransform2D t2d;\r
-\r
-    public XSSFChildAnchor(int x, int y, int cx, int cy) {\r
-        t2d = CTTransform2D.Factory.newInstance();\r
-        CTPoint2D off = t2d.addNewOff();\r
-        CTPositiveSize2D ext = t2d.addNewExt();\r
-\r
-        off.setX(x);\r
-        off.setY(y);\r
-        ext.setCx(Math.abs(cx - x));\r
-        ext.setCy(Math.abs(cy - y));\r
-        if(x > cx)  t2d.setFlipH(true);\r
-        if(y > cy)  t2d.setFlipV(true);\r
-    }\r
-\r
-    public XSSFChildAnchor(CTTransform2D t2d) {\r
-        this.t2d = t2d;\r
-    }\r
-\r
-    public CTTransform2D getCTTransform2D() {\r
-        return t2d;\r
-    }\r
-\r
-    public int getDx1() {\r
-        return (int)t2d.getOff().getX();\r
-    }\r
-\r
-    public void setDx1(int dx1) {\r
-        t2d.getOff().setX(dx1);\r
-    }\r
-\r
-    public int getDy1() {\r
-        return (int)t2d.getOff().getY();\r
-    }\r
-\r
-    public void setDy1(int dy1) {\r
-        t2d.getOff().setY(dy1);\r
-    }\r
-\r
-    public int getDy2() {\r
-        return (int)(getDy1() + t2d.getExt().getCy());\r
-    }\r
-\r
-    public void setDy2(int dy2) {\r
-        t2d.getExt().setCy(dy2 - getDy1());\r
-    }\r
-\r
-    public int getDx2() {\r
-        return (int)(getDx1() + t2d.getExt().getCx());\r
-    }\r
-\r
-    public void setDx2(int dx2) {\r
-        t2d.getExt().setCx(dx2 - getDx1());\r
-    }\r
-}\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.usermodel;
+
+import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D;
+import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
+import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D;
+
+/**
+ * @author Yegor Kozlov
+ */
+public final class XSSFChildAnchor extends XSSFAnchor {
+    private CTTransform2D t2d;
+
+    public XSSFChildAnchor(int x, int y, int cx, int cy) {
+        t2d = CTTransform2D.Factory.newInstance();
+        CTPoint2D off = t2d.addNewOff();
+        CTPositiveSize2D ext = t2d.addNewExt();
+
+        off.setX(x);
+        off.setY(y);
+        ext.setCx(Math.abs(cx - x));
+        ext.setCy(Math.abs(cy - y));
+        if(x > cx)  t2d.setFlipH(true);
+        if(y > cy)  t2d.setFlipV(true);
+    }
+
+    public XSSFChildAnchor(CTTransform2D t2d) {
+        this.t2d = t2d;
+    }
+
+    public CTTransform2D getCTTransform2D() {
+        return t2d;
+    }
+
+    public int getDx1() {
+        return (int)t2d.getOff().getX();
+    }
+
+    public void setDx1(int dx1) {
+        t2d.getOff().setX(dx1);
+    }
+
+    public int getDy1() {
+        return (int)t2d.getOff().getY();
+    }
+
+    public void setDy1(int dy1) {
+        t2d.getOff().setY(dy1);
+    }
+
+    public int getDy2() {
+        return (int)(getDy1() + t2d.getExt().getCy());
+    }
+
+    public void setDy2(int dy2) {
+        t2d.getExt().setCy(dy2 - getDy1());
+    }
+
+    public int getDx2() {
+        return (int)(getDx1() + t2d.getExt().getCx());
+    }
+
+    public void setDx2(int dx2) {
+        t2d.getExt().setCx(dx2 - getDx1());
+    }
+}
index b23429fa01243fd6aa7e3eec2d10ee6e566c9f39..b6a17fe53ee9474ed3d65fe41a135810e690f75a 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;\r
-import org.apache.poi.ss.usermodel.ClientAnchor;\r
-\r
-/**\r
- * A client anchor is attached to an excel worksheet.  It anchors against\r
- * top-left and bottom-right cells.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFClientAnchor extends XSSFAnchor implements ClientAnchor {\r
-    private int anchorType;\r
-\r
-    /**\r
-     * Starting anchor point\r
-     */\r
-    private CTMarker cell1;\r
-\r
-    /**\r
-     * Ending anchor point\r
-     */\r
-    private CTMarker cell2;\r
-\r
-    /**\r
-     * Creates a new client anchor and defaults all the anchor positions to 0.\r
-     */\r
-    public XSSFClientAnchor() {\r
-        cell1 = CTMarker.Factory.newInstance();\r
-        cell1.setCol(0);\r
-        cell1.setColOff(0);\r
-        cell1.setRow(0);\r
-        cell1.setRowOff(0);\r
-        cell2 = CTMarker.Factory.newInstance();\r
-        cell2.setCol(0);\r
-        cell2.setColOff(0);\r
-        cell2.setRow(0);\r
-        cell2.setRowOff(0);\r
-    }\r
-\r
-    /**\r
-     * Creates a new client anchor and sets the top-left and bottom-right\r
-     * coordinates of the anchor.\r
-     *\r
-     * @param dx1  the x coordinate within the first cell.\r
-     * @param dy1  the y coordinate within the first cell.\r
-     * @param dx2  the x coordinate within the second cell.\r
-     * @param dy2  the y coordinate within the second cell.\r
-     * @param col1 the column (0 based) of the first cell.\r
-     * @param row1 the row (0 based) of the first cell.\r
-     * @param col2 the column (0 based) of the second cell.\r
-     * @param row2 the row (0 based) of the second cell.\r
-     */\r
-    public XSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) {\r
-        this();\r
-        cell1.setCol(col1);\r
-        cell1.setColOff(dx1);\r
-        cell1.setRow(row1);\r
-        cell1.setRowOff(dy1);\r
-        cell2.setCol(col2);\r
-        cell2.setColOff(dx2);\r
-        cell2.setRow(row2);\r
-        cell2.setRowOff(dy2);\r
-    }\r
-\r
-    /**\r
-     * Create XSSFClientAnchor from existing xml beans\r
-     *\r
-     * @param cell1 starting anchor point\r
-     * @param cell2 ending anchor point\r
-     */\r
-    protected XSSFClientAnchor(CTMarker cell1, CTMarker cell2) {\r
-        this.cell1 = cell1;\r
-        this.cell2 = cell2;\r
-    }\r
-\r
-    public short getCol1() {\r
-        return (short)cell1.getCol();\r
-    }\r
-\r
-    public void setCol1(int col1) {\r
-        cell1.setCol(col1);\r
-    }\r
-\r
-    public short getCol2() {\r
-        return (short)cell2.getCol();\r
-    }\r
-\r
-    public void setCol2(int col2) {\r
-        cell2.setCol(col2);\r
-    }\r
-\r
-    public int getRow1() {\r
-        return cell1.getRow();\r
-    }\r
-\r
-    public void setRow1(int row1) {\r
-        cell1.setRow(row1);\r
-    }\r
-\r
-    public int getRow2() {\r
-        return cell2.getRow();\r
-    }\r
-\r
-    public void setRow2(int row2) {\r
-        cell2.setRow(row2);\r
-    }\r
-\r
-    public int getDx1() {\r
-        return (int)cell1.getColOff();\r
-    }\r
-\r
-    public void setDx1(int dx1) {\r
-        cell1.setColOff(dx1);\r
-    }\r
-\r
-    public int getDy1() {\r
-        return (int)cell1.getRowOff();\r
-    }\r
-\r
-    public void setDy1(int dy1) {\r
-        cell1.setRowOff(dy1);\r
-    }\r
-\r
-    public int getDy2() {\r
-        return (int)cell2.getRowOff();\r
-    }\r
-\r
-    public void setDy2(int dy2) {\r
-        cell2.setRowOff(dy2);\r
-    }\r
-\r
-    public int getDx2() {\r
-        return (int)cell2.getColOff();\r
-    }\r
-\r
-    public void setDx2(int dx2) {\r
-        cell2.setColOff(dx2);\r
-    }\r
-\r
-    @Override\r
-    public boolean equals(Object o) {\r
-        if (o == null || !(o instanceof XSSFClientAnchor)) return false;\r
-\r
-        XSSFClientAnchor anchor = (XSSFClientAnchor) o;\r
-        return cell1.toString().equals(anchor.getFrom().toString()) &&\r
-               cell2.toString().equals(anchor.getTo().toString()) ;\r
-\r
-    }\r
-\r
-    @Override\r
-    public String toString(){\r
-        return "from : " + cell1.toString()  + "; to: " + cell2.toString();\r
-    }\r
-\r
-    /**\r
-     * Return starting anchor point\r
-     *\r
-     * @return starting anchor point\r
-     */\r
-    public CTMarker getFrom(){\r
-        return cell1;\r
-    }\r
-\r
-    protected void setFrom(CTMarker from){\r
-        cell1 = from;\r
-    }\r
-\r
-    /**\r
-     * Return ending anchor point\r
-     *\r
-     * @return ending anchor point\r
-     */\r
-    public CTMarker getTo(){\r
-        return cell2;\r
-    }\r
-\r
-    protected void setTo(CTMarker to){\r
-        cell2 = to;\r
-    }\r
-\r
-\r
-    /**\r
-     * Sets the anchor type\r
-     * <p>\r
-     * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.\r
-     */\r
-    public void setAnchorType( int anchorType )\r
-    {\r
-        this.anchorType = anchorType;\r
-    }\r
-\r
-    /**\r
-     * Gets the anchor type\r
-     * <p>\r
-     * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.\r
-     */\r
-    public int getAnchorType()\r
-    {\r
-        return anchorType;\r
-    }\r
-\r
-}\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.usermodel;
+
+import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
+import org.apache.poi.ss.usermodel.ClientAnchor;
+
+/**
+ * A client anchor is attached to an excel worksheet.  It anchors against
+ * top-left and bottom-right cells.
+ *
+ * @author Yegor Kozlov
+ */
+public final class XSSFClientAnchor extends XSSFAnchor implements ClientAnchor {
+    private int anchorType;
+
+    /**
+     * Starting anchor point
+     */
+    private CTMarker cell1;
+
+    /**
+     * Ending anchor point
+     */
+    private CTMarker cell2;
+
+    /**
+     * Creates a new client anchor and defaults all the anchor positions to 0.
+     */
+    public XSSFClientAnchor() {
+        cell1 = CTMarker.Factory.newInstance();
+        cell1.setCol(0);
+        cell1.setColOff(0);
+        cell1.setRow(0);
+        cell1.setRowOff(0);
+        cell2 = CTMarker.Factory.newInstance();
+        cell2.setCol(0);
+        cell2.setColOff(0);
+        cell2.setRow(0);
+        cell2.setRowOff(0);
+    }
+
+    /**
+     * Creates a new client anchor and sets the top-left and bottom-right
+     * coordinates of the anchor.
+     *
+     * @param dx1  the x coordinate within the first cell.
+     * @param dy1  the y coordinate within the first cell.
+     * @param dx2  the x coordinate within the second cell.
+     * @param dy2  the y coordinate within the second cell.
+     * @param col1 the column (0 based) of the first cell.
+     * @param row1 the row (0 based) of the first cell.
+     * @param col2 the column (0 based) of the second cell.
+     * @param row2 the row (0 based) of the second cell.
+     */
+    public XSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) {
+        this();
+        cell1.setCol(col1);
+        cell1.setColOff(dx1);
+        cell1.setRow(row1);
+        cell1.setRowOff(dy1);
+        cell2.setCol(col2);
+        cell2.setColOff(dx2);
+        cell2.setRow(row2);
+        cell2.setRowOff(dy2);
+    }
+
+    /**
+     * Create XSSFClientAnchor from existing xml beans
+     *
+     * @param cell1 starting anchor point
+     * @param cell2 ending anchor point
+     */
+    protected XSSFClientAnchor(CTMarker cell1, CTMarker cell2) {
+        this.cell1 = cell1;
+        this.cell2 = cell2;
+    }
+
+    public short getCol1() {
+        return (short)cell1.getCol();
+    }
+
+    public void setCol1(int col1) {
+        cell1.setCol(col1);
+    }
+
+    public short getCol2() {
+        return (short)cell2.getCol();
+    }
+
+    public void setCol2(int col2) {
+        cell2.setCol(col2);
+    }
+
+    public int getRow1() {
+        return cell1.getRow();
+    }
+
+    public void setRow1(int row1) {
+        cell1.setRow(row1);
+    }
+
+    public int getRow2() {
+        return cell2.getRow();
+    }
+
+    public void setRow2(int row2) {
+        cell2.setRow(row2);
+    }
+
+    public int getDx1() {
+        return (int)cell1.getColOff();
+    }
+
+    public void setDx1(int dx1) {
+        cell1.setColOff(dx1);
+    }
+
+    public int getDy1() {
+        return (int)cell1.getRowOff();
+    }
+
+    public void setDy1(int dy1) {
+        cell1.setRowOff(dy1);
+    }
+
+    public int getDy2() {
+        return (int)cell2.getRowOff();
+    }
+
+    public void setDy2(int dy2) {
+        cell2.setRowOff(dy2);
+    }
+
+    public int getDx2() {
+        return (int)cell2.getColOff();
+    }
+
+    public void setDx2(int dx2) {
+        cell2.setColOff(dx2);
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (o == null || !(o instanceof XSSFClientAnchor)) return false;
+
+        XSSFClientAnchor anchor = (XSSFClientAnchor) o;
+        return cell1.toString().equals(anchor.getFrom().toString()) &&
+               cell2.toString().equals(anchor.getTo().toString()) ;
+
+    }
+
+    @Override
+    public String toString(){
+        return "from : " + cell1.toString()  + "; to: " + cell2.toString();
+    }
+
+    /**
+     * Return starting anchor point
+     *
+     * @return starting anchor point
+     */
+    public CTMarker getFrom(){
+        return cell1;
+    }
+
+    protected void setFrom(CTMarker from){
+        cell1 = from;
+    }
+
+    /**
+     * Return ending anchor point
+     *
+     * @return ending anchor point
+     */
+    public CTMarker getTo(){
+        return cell2;
+    }
+
+    protected void setTo(CTMarker to){
+        cell2 = to;
+    }
+
+
+    /**
+     * Sets the anchor type
+     * <p>
+     * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.
+     */
+    public void setAnchorType( int anchorType )
+    {
+        this.anchorType = anchorType;
+    }
+
+    /**
+     * Gets the anchor type
+     * <p>
+     * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.
+     */
+    public int getAnchorType()
+    {
+        return anchorType;
+    }
+
+}
index 92f0d1d73c1cb00d0300c8c356b3f01bc7ec11ad..f7cf9d5a75d6229a08755ce41975788137728166 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;\r
-import org.openxmlformats.schemas.drawingml.x2006.main.*;\r
-\r
-/**\r
- * A connection shape drawing element. A connection shape is a line, etc.\r
- * that connects two other shapes in this drawing.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFConnector extends XSSFShape {\r
-\r
-    private static CTConnector prototype = null;\r
-\r
-    private CTConnector ctShape;\r
-\r
-    /**\r
-     * Construct a new XSSFConnector object.\r
-     *\r
-     * @param drawing the XSSFDrawing that owns this shape\r
-     * @param ctShape the shape bean that holds all the shape properties\r
-     */\r
-    protected XSSFConnector(XSSFDrawing drawing, CTConnector ctShape) {\r
-        this.drawing = drawing;\r
-        this.ctShape = ctShape;\r
-    }\r
-\r
-    /**\r
-     * Initialize default structure of a new auto-shape\r
-     *\r
-     */\r
-    protected static CTConnector prototype() {\r
-        if(prototype == null) {\r
-            CTConnector shape = CTConnector.Factory.newInstance();\r
-            CTConnectorNonVisual nv = shape.addNewNvCxnSpPr();\r
-            CTNonVisualDrawingProps nvp = nv.addNewCNvPr();\r
-            nvp.setId(1);\r
-            nvp.setName("Shape 1");\r
-            nv.addNewCNvCxnSpPr();\r
-\r
-            CTShapeProperties sp = shape.addNewSpPr();\r
-            CTTransform2D t2d = sp.addNewXfrm();\r
-            CTPositiveSize2D p1 = t2d.addNewExt();\r
-            p1.setCx(0);\r
-            p1.setCy(0);\r
-            CTPoint2D p2 = t2d.addNewOff();\r
-            p2.setX(0);\r
-            p2.setY(0);\r
-\r
-            CTPresetGeometry2D geom = sp.addNewPrstGeom();\r
-            geom.setPrst(STShapeType.LINE);\r
-            geom.addNewAvLst();\r
-\r
-            CTShapeStyle style = shape.addNewStyle();\r
-            CTSchemeColor scheme = style.addNewLnRef().addNewSchemeClr();\r
-            scheme.setVal(STSchemeColorVal.ACCENT_1);\r
-            style.getLnRef().setIdx(1);\r
-\r
-            CTStyleMatrixReference fillref = style.addNewFillRef();\r
-            fillref.setIdx(0);\r
-            fillref.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_1);\r
-\r
-            CTStyleMatrixReference effectRef = style.addNewEffectRef();\r
-            effectRef.setIdx(0);\r
-            effectRef.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_1);\r
-\r
-            CTFontReference fontRef = style.addNewFontRef();\r
-            fontRef.setIdx(STFontCollectionIndex.MINOR);\r
-            fontRef.addNewSchemeClr().setVal(STSchemeColorVal.TX_1);\r
-\r
-            prototype = shape;\r
-        }\r
-        return prototype;\r
-    }\r
-\r
-    public CTConnector getCTConnector(){\r
-        return ctShape;\r
-    }\r
-\r
-    /**\r
-     * Gets the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}.\r
-     *\r
-     * @return the shape type\r
-     * @see org.apache.poi.ss.usermodel.ShapeTypes\r
-     */\r
-    public int getShapeType() {\r
-        return ctShape.getSpPr().getPrstGeom().getPrst().intValue();\r
-    }\r
-\r
-    /**\r
-     * Sets the shape types.\r
-     *\r
-     * @param type the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}.\r
-     * @see org.apache.poi.ss.usermodel.ShapeTypes\r
-     */\r
-    public void setShapeType(int type) {\r
-        ctShape.getSpPr().getPrstGeom().setPrst(STShapeType.Enum.forInt(type));\r
-    }\r
-\r
-    protected CTShapeProperties getShapeProperties(){\r
-        return ctShape.getSpPr();\r
-    }\r
-\r
-}\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.usermodel;
+
+import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;
+import org.openxmlformats.schemas.drawingml.x2006.main.*;
+
+/**
+ * A connection shape drawing element. A connection shape is a line, etc.
+ * that connects two other shapes in this drawing.
+ *
+ * @author Yegor Kozlov
+ */
+public final class XSSFConnector extends XSSFShape {
+
+    private static CTConnector prototype = null;
+
+    private CTConnector ctShape;
+
+    /**
+     * Construct a new XSSFConnector object.
+     *
+     * @param drawing the XSSFDrawing that owns this shape
+     * @param ctShape the shape bean that holds all the shape properties
+     */
+    protected XSSFConnector(XSSFDrawing drawing, CTConnector ctShape) {
+        this.drawing = drawing;
+        this.ctShape = ctShape;
+    }
+
+    /**
+     * Initialize default structure of a new auto-shape
+     *
+     */
+    protected static CTConnector prototype() {
+        if(prototype == null) {
+            CTConnector shape = CTConnector.Factory.newInstance();
+            CTConnectorNonVisual nv = shape.addNewNvCxnSpPr();
+            CTNonVisualDrawingProps nvp = nv.addNewCNvPr();
+            nvp.setId(1);
+            nvp.setName("Shape 1");
+            nv.addNewCNvCxnSpPr();
+
+            CTShapeProperties sp = shape.addNewSpPr();
+            CTTransform2D t2d = sp.addNewXfrm();
+            CTPositiveSize2D p1 = t2d.addNewExt();
+            p1.setCx(0);
+            p1.setCy(0);
+            CTPoint2D p2 = t2d.addNewOff();
+            p2.setX(0);
+            p2.setY(0);
+
+            CTPresetGeometry2D geom = sp.addNewPrstGeom();
+            geom.setPrst(STShapeType.LINE);
+            geom.addNewAvLst();
+
+            CTShapeStyle style = shape.addNewStyle();
+            CTSchemeColor scheme = style.addNewLnRef().addNewSchemeClr();
+            scheme.setVal(STSchemeColorVal.ACCENT_1);
+            style.getLnRef().setIdx(1);
+
+            CTStyleMatrixReference fillref = style.addNewFillRef();
+            fillref.setIdx(0);
+            fillref.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_1);
+
+            CTStyleMatrixReference effectRef = style.addNewEffectRef();
+            effectRef.setIdx(0);
+            effectRef.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_1);
+
+            CTFontReference fontRef = style.addNewFontRef();
+            fontRef.setIdx(STFontCollectionIndex.MINOR);
+            fontRef.addNewSchemeClr().setVal(STSchemeColorVal.TX_1);
+
+            prototype = shape;
+        }
+        return prototype;
+    }
+
+    public CTConnector getCTConnector(){
+        return ctShape;
+    }
+
+    /**
+     * Gets the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}.
+     *
+     * @return the shape type
+     * @see org.apache.poi.ss.usermodel.ShapeTypes
+     */
+    public int getShapeType() {
+        return ctShape.getSpPr().getPrstGeom().getPrst().intValue();
+    }
+
+    /**
+     * Sets the shape types.
+     *
+     * @param type the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}.
+     * @see org.apache.poi.ss.usermodel.ShapeTypes
+     */
+    public void setShapeType(int type) {
+        ctShape.getSpPr().getPrstGeom().setPrst(STShapeType.Enum.forInt(type));
+    }
+
+    protected CTShapeProperties getShapeProperties(){
+        return ctShape.getSpPr();
+    }
+
+}
index 24943ba834a88bddc6802df8b9a6a9970fb9fa6e..ffdc684f5b47d90325db1b30a2774f6353003512 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-import org.apache.poi.POIXMLDocumentPart;\r
-import org.apache.poi.ss.usermodel.Drawing;\r
-import org.apache.poi.ss.usermodel.ClientAnchor;\r
-import org.apache.xmlbeans.XmlException;\r
-import org.apache.xmlbeans.XmlOptions;\r
-import org.apache.poi.openxml4j.opc.*;\r
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;\r
-import org.openxmlformats.schemas.officeDocument.x2006.relationships.STRelationshipId;\r
-\r
-import javax.xml.namespace.QName;\r
-import java.io.IOException;\r
-import java.io.OutputStream;\r
-import java.util.Map;\r
-import java.util.HashMap;\r
-\r
-/**\r
- * Represents a SpreadsheetML drawing\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFDrawing extends POIXMLDocumentPart implements Drawing {\r
-    /**\r
-     * Root element of the SpreadsheetML Drawing part\r
-     */\r
-    private CTDrawing drawing;\r
-    private boolean isNew;\r
-\r
-    /**\r
-     * Create a new SpreadsheetML drawing\r
-     *\r
-     * @see org.apache.poi.xssf.usermodel.XSSFSheet#createDrawingPatriarch()\r
-     */\r
-    protected XSSFDrawing() {\r
-        super();\r
-        drawing = newDrawing();\r
-        isNew = true;\r
-    }\r
-\r
-    /**\r
-     * Construct a SpreadsheetML drawing from a package part\r
-     *\r
-     * @param part the package part holding the drawing data,\r
-     * the content type must be <code>application/vnd.openxmlformats-officedocument.drawing+xml</code>\r
-     * @param rel  the package relationship holding this drawing,\r
-     * the relationship type must be http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing\r
-     */\r
-    protected XSSFDrawing(PackagePart part, PackageRelationship rel) throws IOException, XmlException {\r
-        super(part, rel);\r
-        drawing = CTDrawing.Factory.parse(part.getInputStream());\r
-    }\r
-\r
-    /**\r
-     * Construct a new CTDrawing bean. By default, it's just an empty placeholder for drawing objects\r
-     *\r
-     * @return a new CTDrawing bean\r
-     */\r
-    private static CTDrawing newDrawing(){\r
-        return CTDrawing.Factory.newInstance();\r
-    }\r
-\r
-    /**\r
-     * Return the underlying CTDrawing bean, the root element of the SpreadsheetML Drawing part.\r
-     *\r
-     * @return the underlying CTDrawing bean\r
-     */\r
-    public CTDrawing getCTDrawing(){\r
-        return drawing;\r
-    }\r
-\r
-    @Override\r
-    protected void commit() throws IOException {\r
-        XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);\r
-\r
-        /*\r
-            Saved drawings must have the following namespaces set:\r
-            <xdr:wsDr\r
-                xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"\r
-                xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing">\r
-        */\r
-        if(isNew) xmlOptions.setSaveSyntheticDocumentElement(new QName(CTDrawing.type.getName().getNamespaceURI(), "wsDr", "xdr"));\r
-        Map map = new HashMap();\r
-        map.put("http://schemas.openxmlformats.org/drawingml/2006/main", "a");\r
-        map.put(STRelationshipId.type.getName().getNamespaceURI(), "r");\r
-        xmlOptions.setSaveSuggestedPrefixes(map);\r
-\r
-        PackagePart part = getPackagePart();\r
-        OutputStream out = part.getOutputStream();\r
-        drawing.save(out, xmlOptions);\r
-        out.close();\r
-    }\r
-\r
-    /**\r
-     * Constructs a textbox under the drawing.\r
-     *\r
-     * @param anchor    the client anchor describes how this group is attached\r
-     *                  to the sheet.\r
-     * @return      the newly created textbox.\r
-     */\r
-    public XSSFTextBox createTextbox(XSSFClientAnchor anchor){\r
-        CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);\r
-        CTShape ctShape = ctAnchor.addNewSp();\r
-        ctShape.set(XSSFSimpleShape.prototype());\r
-        XSSFTextBox shape = new XSSFTextBox(this, ctShape);\r
-        shape.anchor = anchor;\r
-        return shape;\r
-\r
-    }\r
-\r
-    /**\r
-     * Creates a picture.\r
-     *\r
-     * @param anchor    the client anchor describes how this picture is attached to the sheet.\r
-     * @param pictureIndex the index of the picture in the workbook collection of pictures,\r
-     *   {@link org.apache.poi.xssf.usermodel.XSSFWorkbook#getAllPictures()} .\r
-     *\r
-     * @return  the newly created picture shape.\r
-     */\r
-    public XSSFPicture createPicture(XSSFClientAnchor anchor, int pictureIndex)\r
-    {\r
-        PackageRelationship rel = addPictureReference(pictureIndex);\r
-\r
-        CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);\r
-        CTPicture ctShape = ctAnchor.addNewPic();\r
-        ctShape.set(XSSFPicture.prototype());\r
-\r
-        XSSFPicture shape = new XSSFPicture(this, ctShape);\r
-        shape.anchor = anchor;\r
-        shape.setPictureReference(rel);\r
-        return shape;\r
-    }\r
-\r
-    public XSSFPicture createPicture(ClientAnchor anchor, int pictureIndex){\r
-        return createPicture((XSSFClientAnchor)anchor, pictureIndex);\r
-    }\r
-\r
-    /**\r
-     * Add the indexed picture to this drawing relations\r
-     *\r
-     * @param pictureIndex the index of the picture in the workbook collection of pictures,\r
-     *   {@link org.apache.poi.xssf.usermodel.XSSFWorkbook#getAllPictures()} .\r
-     */\r
-    protected PackageRelationship addPictureReference(int pictureIndex){\r
-        XSSFWorkbook wb = (XSSFWorkbook)getParent().getParent();\r
-        XSSFPictureData data = wb.getAllPictures().get(pictureIndex);\r
-        PackagePartName ppName = data.getPackagePart().getPartName();\r
-        PackageRelationship rel = getPackagePart().addRelationship(ppName, TargetMode.INTERNAL, XSSFRelation.IMAGES.getRelation());\r
-        addRelation(new XSSFPictureData(data.getPackagePart(), rel));\r
-        return rel;\r
-    }\r
-\r
-    /**\r
-     * Creates a simple shape.  This includes such shapes as lines, rectangles,\r
-     * and ovals.\r
-     *\r
-     * @param anchor    the client anchor describes how this group is attached\r
-     *                  to the sheet.\r
-     * @return  the newly created shape.\r
-     */\r
-    public XSSFSimpleShape createSimpleShape(XSSFClientAnchor anchor)\r
-    {\r
-        CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);\r
-        CTShape ctShape = ctAnchor.addNewSp();\r
-        ctShape.set(XSSFSimpleShape.prototype());\r
-        XSSFSimpleShape shape = new XSSFSimpleShape(this, ctShape);\r
-        shape.anchor = anchor;\r
-        return shape;\r
-    }\r
-\r
-    /**\r
-     * Creates a simple shape.  This includes such shapes as lines, rectangles,\r
-     * and ovals.\r
-     *\r
-     * @param anchor    the client anchor describes how this group is attached\r
-     *                  to the sheet.\r
-     * @return  the newly created shape.\r
-     */\r
-    public XSSFConnector createConnector(XSSFClientAnchor anchor)\r
-    {\r
-        CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);\r
-        CTConnector ctShape = ctAnchor.addNewCxnSp();\r
-        ctShape.set(XSSFConnector.prototype());\r
-\r
-        XSSFConnector shape = new XSSFConnector(this, ctShape);\r
-        shape.anchor = anchor;\r
-        return shape;\r
-    }\r
-\r
-    /**\r
-     * Creates a simple shape.  This includes such shapes as lines, rectangles,\r
-     * and ovals.\r
-     *\r
-     * @param anchor    the client anchor describes how this group is attached\r
-     *                  to the sheet.\r
-     * @return  the newly created shape.\r
-     */\r
-    public XSSFShapeGroup createGroup(XSSFClientAnchor anchor)\r
-    {\r
-        CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);\r
-        CTGroupShape ctGroup = ctAnchor.addNewGrpSp();\r
-        ctGroup.set(XSSFShapeGroup.prototype());\r
-\r
-        XSSFShapeGroup shape = new XSSFShapeGroup(this, ctGroup);\r
-        shape.anchor = anchor;\r
-        return shape;\r
-    }\r
-\r
-    /**\r
-     * Create and initialize a CTTwoCellAnchor that anchors a shape against top-left and bottom-right cells.\r
-     *\r
-     * @return a new CTTwoCellAnchor\r
-     */\r
-    private CTTwoCellAnchor createTwoCellAnchor(XSSFClientAnchor anchor) {\r
-        CTTwoCellAnchor ctAnchor = drawing.addNewTwoCellAnchor();\r
-        ctAnchor.setFrom(anchor.getFrom());\r
-        ctAnchor.setTo(anchor.getTo());\r
-        ctAnchor.addNewClientData();\r
-        anchor.setTo(ctAnchor.getTo());\r
-        anchor.setFrom(ctAnchor.getFrom());\r
-        STEditAs.Enum aditAs;\r
-        switch(anchor.getAnchorType()) {\r
-            case ClientAnchor.DONT_MOVE_AND_RESIZE: aditAs = STEditAs.ABSOLUTE; break;\r
-            case ClientAnchor.MOVE_AND_RESIZE: aditAs = STEditAs.TWO_CELL; break;\r
-            case ClientAnchor.MOVE_DONT_RESIZE: aditAs = STEditAs.ONE_CELL; break;\r
-            default: aditAs = STEditAs.ONE_CELL;\r
-        }\r
-        ctAnchor.setEditAs(aditAs);\r
-        return ctAnchor;\r
-    }\r
-}\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.usermodel;
+
+import org.apache.poi.POIXMLDocumentPart;
+import org.apache.poi.ss.usermodel.Drawing;
+import org.apache.poi.ss.usermodel.ClientAnchor;
+import org.apache.xmlbeans.XmlException;
+import org.apache.xmlbeans.XmlOptions;
+import org.apache.poi.openxml4j.opc.*;
+import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;
+import org.openxmlformats.schemas.officeDocument.x2006.relationships.STRelationshipId;
+
+import javax.xml.namespace.QName;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Map;
+import java.util.HashMap;
+
+/**
+ * Represents a SpreadsheetML drawing
+ *
+ * @author Yegor Kozlov
+ */
+public final class XSSFDrawing extends POIXMLDocumentPart implements Drawing {
+    /**
+     * Root element of the SpreadsheetML Drawing part
+     */
+    private CTDrawing drawing;
+    private boolean isNew;
+
+    /**
+     * Create a new SpreadsheetML drawing
+     *
+     * @see org.apache.poi.xssf.usermodel.XSSFSheet#createDrawingPatriarch()
+     */
+    protected XSSFDrawing() {
+        super();
+        drawing = newDrawing();
+        isNew = true;
+    }
+
+    /**
+     * Construct a SpreadsheetML drawing from a package part
+     *
+     * @param part the package part holding the drawing data,
+     * the content type must be <code>application/vnd.openxmlformats-officedocument.drawing+xml</code>
+     * @param rel  the package relationship holding this drawing,
+     * the relationship type must be http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing
+     */
+    protected XSSFDrawing(PackagePart part, PackageRelationship rel) throws IOException, XmlException {
+        super(part, rel);
+        drawing = CTDrawing.Factory.parse(part.getInputStream());
+    }
+
+    /**
+     * Construct a new CTDrawing bean. By default, it's just an empty placeholder for drawing objects
+     *
+     * @return a new CTDrawing bean
+     */
+    private static CTDrawing newDrawing(){
+        return CTDrawing.Factory.newInstance();
+    }
+
+    /**
+     * Return the underlying CTDrawing bean, the root element of the SpreadsheetML Drawing part.
+     *
+     * @return the underlying CTDrawing bean
+     */
+    public CTDrawing getCTDrawing(){
+        return drawing;
+    }
+
+    @Override
+    protected void commit() throws IOException {
+        XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
+
+        /*
+            Saved drawings must have the following namespaces set:
+            <xdr:wsDr
+                xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
+                xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing">
+        */
+        if(isNew) xmlOptions.setSaveSyntheticDocumentElement(new QName(CTDrawing.type.getName().getNamespaceURI(), "wsDr", "xdr"));
+        Map map = new HashMap();
+        map.put("http://schemas.openxmlformats.org/drawingml/2006/main", "a");
+        map.put(STRelationshipId.type.getName().getNamespaceURI(), "r");
+        xmlOptions.setSaveSuggestedPrefixes(map);
+
+        PackagePart part = getPackagePart();
+        OutputStream out = part.getOutputStream();
+        drawing.save(out, xmlOptions);
+        out.close();
+    }
+
+    /**
+     * Constructs a textbox under the drawing.
+     *
+     * @param anchor    the client anchor describes how this group is attached
+     *                  to the sheet.
+     * @return      the newly created textbox.
+     */
+    public XSSFTextBox createTextbox(XSSFClientAnchor anchor){
+        CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
+        CTShape ctShape = ctAnchor.addNewSp();
+        ctShape.set(XSSFSimpleShape.prototype());
+        XSSFTextBox shape = new XSSFTextBox(this, ctShape);
+        shape.anchor = anchor;
+        return shape;
+
+    }
+
+    /**
+     * Creates a picture.
+     *
+     * @param anchor    the client anchor describes how this picture is attached to the sheet.
+     * @param pictureIndex the index of the picture in the workbook collection of pictures,
+     *   {@link org.apache.poi.xssf.usermodel.XSSFWorkbook#getAllPictures()} .
+     *
+     * @return  the newly created picture shape.
+     */
+    public XSSFPicture createPicture(XSSFClientAnchor anchor, int pictureIndex)
+    {
+        PackageRelationship rel = addPictureReference(pictureIndex);
+
+        CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
+        CTPicture ctShape = ctAnchor.addNewPic();
+        ctShape.set(XSSFPicture.prototype());
+
+        XSSFPicture shape = new XSSFPicture(this, ctShape);
+        shape.anchor = anchor;
+        shape.setPictureReference(rel);
+        return shape;
+    }
+
+    public XSSFPicture createPicture(ClientAnchor anchor, int pictureIndex){
+        return createPicture((XSSFClientAnchor)anchor, pictureIndex);
+    }
+
+    /**
+     * Add the indexed picture to this drawing relations
+     *
+     * @param pictureIndex the index of the picture in the workbook collection of pictures,
+     *   {@link org.apache.poi.xssf.usermodel.XSSFWorkbook#getAllPictures()} .
+     */
+    protected PackageRelationship addPictureReference(int pictureIndex){
+        XSSFWorkbook wb = (XSSFWorkbook)getParent().getParent();
+        XSSFPictureData data = wb.getAllPictures().get(pictureIndex);
+        PackagePartName ppName = data.getPackagePart().getPartName();
+        PackageRelationship rel = getPackagePart().addRelationship(ppName, TargetMode.INTERNAL, XSSFRelation.IMAGES.getRelation());
+        addRelation(new XSSFPictureData(data.getPackagePart(), rel));
+        return rel;
+    }
+
+    /**
+     * Creates a simple shape.  This includes such shapes as lines, rectangles,
+     * and ovals.
+     *
+     * @param anchor    the client anchor describes how this group is attached
+     *                  to the sheet.
+     * @return  the newly created shape.
+     */
+    public XSSFSimpleShape createSimpleShape(XSSFClientAnchor anchor)
+    {
+        CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
+        CTShape ctShape = ctAnchor.addNewSp();
+        ctShape.set(XSSFSimpleShape.prototype());
+        XSSFSimpleShape shape = new XSSFSimpleShape(this, ctShape);
+        shape.anchor = anchor;
+        return shape;
+    }
+
+    /**
+     * Creates a simple shape.  This includes such shapes as lines, rectangles,
+     * and ovals.
+     *
+     * @param anchor    the client anchor describes how this group is attached
+     *                  to the sheet.
+     * @return  the newly created shape.
+     */
+    public XSSFConnector createConnector(XSSFClientAnchor anchor)
+    {
+        CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
+        CTConnector ctShape = ctAnchor.addNewCxnSp();
+        ctShape.set(XSSFConnector.prototype());
+
+        XSSFConnector shape = new XSSFConnector(this, ctShape);
+        shape.anchor = anchor;
+        return shape;
+    }
+
+    /**
+     * Creates a simple shape.  This includes such shapes as lines, rectangles,
+     * and ovals.
+     *
+     * @param anchor    the client anchor describes how this group is attached
+     *                  to the sheet.
+     * @return  the newly created shape.
+     */
+    public XSSFShapeGroup createGroup(XSSFClientAnchor anchor)
+    {
+        CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor);
+        CTGroupShape ctGroup = ctAnchor.addNewGrpSp();
+        ctGroup.set(XSSFShapeGroup.prototype());
+
+        XSSFShapeGroup shape = new XSSFShapeGroup(this, ctGroup);
+        shape.anchor = anchor;
+        return shape;
+    }
+
+    /**
+     * Create and initialize a CTTwoCellAnchor that anchors a shape against top-left and bottom-right cells.
+     *
+     * @return a new CTTwoCellAnchor
+     */
+    private CTTwoCellAnchor createTwoCellAnchor(XSSFClientAnchor anchor) {
+        CTTwoCellAnchor ctAnchor = drawing.addNewTwoCellAnchor();
+        ctAnchor.setFrom(anchor.getFrom());
+        ctAnchor.setTo(anchor.getTo());
+        ctAnchor.addNewClientData();
+        anchor.setTo(ctAnchor.getTo());
+        anchor.setFrom(ctAnchor.getFrom());
+        STEditAs.Enum aditAs;
+        switch(anchor.getAnchorType()) {
+            case ClientAnchor.DONT_MOVE_AND_RESIZE: aditAs = STEditAs.ABSOLUTE; break;
+            case ClientAnchor.MOVE_AND_RESIZE: aditAs = STEditAs.TWO_CELL; break;
+            case ClientAnchor.MOVE_DONT_RESIZE: aditAs = STEditAs.ONE_CELL; break;
+            default: aditAs = STEditAs.ONE_CELL;
+        }
+        ctAnchor.setEditAs(aditAs);
+        return ctAnchor;
+    }
+}
index ef2bdf89b3feada626938f14d4c9a9b34badc53c..5264281f00bca8179da15128245f40b09e1962ee 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-import org.apache.poi.hssf.record.formula.NamePtg;\r
-import org.apache.poi.hssf.record.formula.NameXPtg;\r
-import org.apache.poi.hssf.record.formula.Ptg;\r
-import org.apache.poi.ss.formula.*;\r
-import org.apache.poi.ss.SpreadsheetVersion;\r
-import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;\r
-\r
-/**\r
- * Internal POI use only\r
- * \r
- * @author Josh Micich\r
- */\r
-public final class XSSFEvaluationWorkbook implements FormulaRenderingWorkbook, EvaluationWorkbook, FormulaParsingWorkbook {\r
-\r
-       private final XSSFWorkbook _uBook;\r
-       \r
-       public static XSSFEvaluationWorkbook create(XSSFWorkbook book) {\r
-               if (book == null) {\r
-                       return null;\r
-               }\r
-               return new XSSFEvaluationWorkbook(book);\r
-       }\r
-\r
-       private XSSFEvaluationWorkbook(XSSFWorkbook book) {\r
-               _uBook = book;\r
-       }\r
-\r
-       private int convertFromExternalSheetIndex(int externSheetIndex) {\r
-               return externSheetIndex;\r
-       }\r
-       /**\r
-        * @return the sheet index of the sheet with the given external index.\r
-        */\r
-       public int convertFromExternSheetIndex(int externSheetIndex) {\r
-               return externSheetIndex;\r
-       }\r
-       /**\r
-        * @return  the external sheet index of the sheet with the given internal\r
-        * index. Used by some of the more obscure formula and named range things. \r
-        * Fairly easy on XSSF (we think...) since the internal and external \r
-        * indicies are the same\r
-        */\r
-       private int convertToExternalSheetIndex(int sheetIndex) {\r
-               return sheetIndex;\r
-       }\r
-\r
-       public int getExternalSheetIndex(String sheetName) {\r
-               int sheetIndex = _uBook.getSheetIndex(sheetName);\r
-               return convertToExternalSheetIndex(sheetIndex);\r
-       }\r
-\r
-    public EvaluationName getName(String name, int sheetIndex) {\r
-        for(int i=0; i < _uBook.getNumberOfNames(); i++) {\r
-            XSSFName nm = _uBook.getNameAt(i);\r
-            String nameText = nm.getNameName();\r
-            if (name.equalsIgnoreCase(nameText) && nm.getSheetIndex() == sheetIndex) {\r
-                return new Name(_uBook.getNameAt(i), i, this);\r
-            }\r
-        }\r
-        return sheetIndex == -1 ? null : getName(name, -1);\r
-    }\r
-\r
-       public int getSheetIndex(EvaluationSheet evalSheet) {\r
-               XSSFSheet sheet = ((XSSFEvaluationSheet)evalSheet).getXSSFSheet();\r
-               return _uBook.getSheetIndex(sheet);\r
-       }\r
-\r
-       public String getSheetName(int sheetIndex) {\r
-               return _uBook.getSheetName(sheetIndex);\r
-       }\r
-\r
-       public NameXPtg getNameXPtg(String name) {\r
-               // may require to return null to make tests pass\r
-               throw new RuntimeException("Not implemented yet");\r
-       }\r
-\r
-       public EvaluationSheet getSheet(int sheetIndex) {\r
-               return new XSSFEvaluationSheet(_uBook.getSheetAt(sheetIndex));\r
-       }\r
-\r
-       public ExternalSheet getExternalSheet(int externSheetIndex) {\r
-               // TODO Auto-generated method stub\r
-               return null;\r
-       }\r
-       public int getExternalSheetIndex(String workbookName, String sheetName) {\r
-               throw new RuntimeException("not implemented yet");\r
-       }\r
-       public int getSheetIndex(String sheetName) {\r
-               return _uBook.getSheetIndex(sheetName);\r
-       }\r
-\r
-    /**\r
-     * TODO - figure out what the hell this methods does in\r
-     *  HSSF...\r
-     */\r
-       public String resolveNameXText(NameXPtg n) {\r
-               throw new RuntimeException("method not implemented yet");\r
-       }\r
-\r
-       public String getSheetNameByExternSheet(int externSheetIndex) {\r
-               int sheetIndex = convertFromExternalSheetIndex(externSheetIndex);\r
-               return _uBook.getSheetName(sheetIndex);\r
-       }\r
-\r
-       public String getNameText(NamePtg namePtg) {\r
-               return _uBook.getNameAt(namePtg.getIndex()).getNameName();\r
-       }\r
-       public EvaluationName getName(NamePtg namePtg) {\r
-               int ix = namePtg.getIndex();\r
-               return new Name(_uBook.getNameAt(ix), ix, this);\r
-       }\r
-       public Ptg[] getFormulaTokens(EvaluationCell evalCell) {\r
-               XSSFCell cell = ((XSSFEvaluationCell)evalCell).getXSSFCell();\r
-               XSSFEvaluationWorkbook frBook = XSSFEvaluationWorkbook.create(_uBook);\r
-               return FormulaParser.parse(cell.getCellFormula(), frBook, FormulaType.CELL, _uBook.getSheetIndex(cell.getSheet()));\r
-       }\r
-\r
-       private static final class Name implements EvaluationName {\r
-\r
-               private final XSSFName _nameRecord;\r
-               private final int _index;\r
-               private final FormulaParsingWorkbook _fpBook;\r
-\r
-               public Name(XSSFName name, int index, FormulaParsingWorkbook fpBook) {\r
-                       _nameRecord = name;\r
-                       _index = index;\r
-                       _fpBook = fpBook;\r
-               }\r
-\r
-               public Ptg[] getNameDefinition() {\r
-                       \r
-                       return FormulaParser.parse(_nameRecord.getRefersToFormula(), _fpBook, FormulaType.NAMEDRANGE, _nameRecord.getSheetIndex());\r
-               }\r
-\r
-               public String getNameText() {\r
-                       return _nameRecord.getNameName();\r
-               }\r
-\r
-               public boolean hasFormula() {\r
-                       // TODO - no idea if this is right\r
-                       CTDefinedName ctn = _nameRecord.getCTName();\r
-                       String strVal = ctn.getStringValue();\r
-                       return !ctn.getFunction() && strVal != null && strVal.length() > 0;\r
-               }\r
-\r
-               public boolean isFunctionName() {\r
-                       return _nameRecord.isFunctionName();\r
-               }\r
-\r
-               public boolean isRange() {\r
-                       return hasFormula(); // TODO - is this right?\r
-               }\r
-               public NamePtg createPtg() {\r
-                       return new NamePtg(_index);\r
-               }\r
-       }\r
-    \r
-    public SpreadsheetVersion getSpreadsheetVersion(){\r
-        return SpreadsheetVersion.EXCEL2007;\r
-    }\r
-}\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.usermodel;
+
+import org.apache.poi.hssf.record.formula.NamePtg;
+import org.apache.poi.hssf.record.formula.NameXPtg;
+import org.apache.poi.hssf.record.formula.Ptg;
+import org.apache.poi.ss.formula.*;
+import org.apache.poi.ss.SpreadsheetVersion;
+import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;
+
+/**
+ * Internal POI use only
+ *
+ * @author Josh Micich
+ */
+public final class XSSFEvaluationWorkbook implements FormulaRenderingWorkbook, EvaluationWorkbook, FormulaParsingWorkbook {
+
+       private final XSSFWorkbook _uBook;
+
+       public static XSSFEvaluationWorkbook create(XSSFWorkbook book) {
+               if (book == null) {
+                       return null;
+               }
+               return new XSSFEvaluationWorkbook(book);
+       }
+
+       private XSSFEvaluationWorkbook(XSSFWorkbook book) {
+               _uBook = book;
+       }
+
+       private int convertFromExternalSheetIndex(int externSheetIndex) {
+               return externSheetIndex;
+       }
+       /**
+        * @return the sheet index of the sheet with the given external index.
+        */
+       public int convertFromExternSheetIndex(int externSheetIndex) {
+               return externSheetIndex;
+       }
+       /**
+        * @return  the external sheet index of the sheet with the given internal
+        * index. Used by some of the more obscure formula and named range things.
+        * Fairly easy on XSSF (we think...) since the internal and external
+        * indicies are the same
+        */
+       private int convertToExternalSheetIndex(int sheetIndex) {
+               return sheetIndex;
+       }
+
+       public int getExternalSheetIndex(String sheetName) {
+               int sheetIndex = _uBook.getSheetIndex(sheetName);
+               return convertToExternalSheetIndex(sheetIndex);
+       }
+
+       public EvaluationName getName(String name, int sheetIndex) {
+               for (int i = 0; i < _uBook.getNumberOfNames(); i++) {
+                       XSSFName nm = _uBook.getNameAt(i);
+                       String nameText = nm.getNameName();
+                       if (name.equalsIgnoreCase(nameText) && nm.getSheetIndex() == sheetIndex) {
+                               return new Name(_uBook.getNameAt(i), i, this);
+                       }
+               }
+               return sheetIndex == -1 ? null : getName(name, -1);
+       }
+
+       public int getSheetIndex(EvaluationSheet evalSheet) {
+               XSSFSheet sheet = ((XSSFEvaluationSheet)evalSheet).getXSSFSheet();
+               return _uBook.getSheetIndex(sheet);
+       }
+
+       public String getSheetName(int sheetIndex) {
+               return _uBook.getSheetName(sheetIndex);
+       }
+
+       public NameXPtg getNameXPtg(String name) {
+               // may require to return null to make tests pass
+               throw new RuntimeException("Not implemented yet");
+       }
+
+       public EvaluationSheet getSheet(int sheetIndex) {
+               return new XSSFEvaluationSheet(_uBook.getSheetAt(sheetIndex));
+       }
+
+       public ExternalSheet getExternalSheet(int externSheetIndex) {
+               // TODO Auto-generated method stub
+               return null;
+       }
+       public int getExternalSheetIndex(String workbookName, String sheetName) {
+               throw new RuntimeException("not implemented yet");
+       }
+       public int getSheetIndex(String sheetName) {
+               return _uBook.getSheetIndex(sheetName);
+       }
+
+       /**
+        * TODO - figure out what the hell this methods does in
+        *  HSSF...
+        */
+       public String resolveNameXText(NameXPtg n) {
+               throw new RuntimeException("method not implemented yet");
+       }
+
+       public String getSheetNameByExternSheet(int externSheetIndex) {
+               int sheetIndex = convertFromExternalSheetIndex(externSheetIndex);
+               return _uBook.getSheetName(sheetIndex);
+       }
+
+       public String getNameText(NamePtg namePtg) {
+               return _uBook.getNameAt(namePtg.getIndex()).getNameName();
+       }
+       public EvaluationName getName(NamePtg namePtg) {
+               int ix = namePtg.getIndex();
+               return new Name(_uBook.getNameAt(ix), ix, this);
+       }
+       public Ptg[] getFormulaTokens(EvaluationCell evalCell) {
+               XSSFCell cell = ((XSSFEvaluationCell)evalCell).getXSSFCell();
+               XSSFEvaluationWorkbook frBook = XSSFEvaluationWorkbook.create(_uBook);
+               return FormulaParser.parse(cell.getCellFormula(), frBook, FormulaType.CELL, _uBook.getSheetIndex(cell.getSheet()));
+       }
+
+       private static final class Name implements EvaluationName {
+
+               private final XSSFName _nameRecord;
+               private final int _index;
+               private final FormulaParsingWorkbook _fpBook;
+
+               public Name(XSSFName name, int index, FormulaParsingWorkbook fpBook) {
+                       _nameRecord = name;
+                       _index = index;
+                       _fpBook = fpBook;
+               }
+
+               public Ptg[] getNameDefinition() {
+
+                       return FormulaParser.parse(_nameRecord.getRefersToFormula(), _fpBook, FormulaType.NAMEDRANGE, _nameRecord.getSheetIndex());
+               }
+
+               public String getNameText() {
+                       return _nameRecord.getNameName();
+               }
+
+               public boolean hasFormula() {
+                       // TODO - no idea if this is right
+                       CTDefinedName ctn = _nameRecord.getCTName();
+                       String strVal = ctn.getStringValue();
+                       return !ctn.getFunction() && strVal != null && strVal.length() > 0;
+               }
+
+               public boolean isFunctionName() {
+                       return _nameRecord.isFunctionName();
+               }
+
+               public boolean isRange() {
+                       return hasFormula(); // TODO - is this right?
+               }
+               public NamePtg createPtg() {
+                       return new NamePtg(_index);
+               }
+       }
+
+       public SpreadsheetVersion getSpreadsheetVersion(){
+               return SpreadsheetVersion.EXCEL2007;
+       }
+}
index 4736ecbc4a448be03b31c0b7329f0c115b5f044c..ab0ef2b443b9c693f8619c43be246073e50cd126 100755 (executable)
@@ -1,74 +1,75 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-import org.apache.poi.POIXMLDocumentPart;\r
-import org.apache.poi.POIXMLFactory;\r
-import org.apache.poi.POIXMLException;\r
-import org.apache.poi.POIXMLRelation;\r
-import org.apache.poi.util.POILogger;\r
-import org.apache.poi.util.POILogFactory;\r
-import org.apache.poi.openxml4j.opc.PackageRelationship;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-\r
-import java.lang.reflect.Constructor;\r
-\r
-/**\r
- * Instantiates sub-classes of POIXMLDocumentPart depending on their relationship type\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFFactory extends POIXMLFactory  {\r
-    private static POILogger logger = POILogFactory.getLogger(XSSFFactory.class);\r
-\r
-    private XSSFFactory(){\r
-\r
-    }\r
-\r
-    private static final XSSFFactory inst = new XSSFFactory();\r
-\r
-    public static XSSFFactory getInstance(){\r
-        return inst;\r
-    }\r
-\r
-    public POIXMLDocumentPart createDocumentPart(PackageRelationship rel, PackagePart part){\r
-        POIXMLRelation descriptor = XSSFRelation.getInstance(rel.getRelationshipType());\r
-        if(descriptor == null || descriptor.getRelationClass() == null){\r
-            logger.log(POILogger.DEBUG, "using default POIXMLDocumentPart for " + rel.getRelationshipType());\r
-            return new POIXMLDocumentPart(part, rel);\r
-        }\r
-\r
-        try {\r
-            Class cls = descriptor.getRelationClass();\r
-            Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(PackagePart.class, PackageRelationship.class);\r
-            return constructor.newInstance(part, rel);\r
-        } catch (Exception e){\r
-            throw new POIXMLException(e);\r
-        }\r
-    }\r
-\r
-    public POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor){\r
-        try {\r
-            Class cls = descriptor.getRelationClass();\r
-            Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor();\r
-            return constructor.newInstance();\r
-        } catch (Exception e){\r
-            throw new POIXMLException(e);\r
-        }\r
-    }\r
-\r
-}\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.usermodel;
+
+import org.apache.poi.POIXMLDocumentPart;
+import org.apache.poi.POIXMLFactory;
+import org.apache.poi.POIXMLException;
+import org.apache.poi.POIXMLRelation;
+import org.apache.poi.util.POILogger;
+import org.apache.poi.util.POILogFactory;
+import org.apache.poi.openxml4j.opc.PackageRelationship;
+import org.apache.poi.openxml4j.opc.PackagePart;
+
+import java.lang.reflect.Constructor;
+
+/**
+ * Instantiates sub-classes of POIXMLDocumentPart depending on their relationship type
+ *
+ * @author Yegor Kozlov
+ */
+public final class XSSFFactory extends POIXMLFactory  {
+    private static POILogger logger = POILogFactory.getLogger(XSSFFactory.class);
+
+    private XSSFFactory(){
+
+    }
+
+    private static final XSSFFactory inst = new XSSFFactory();
+
+    public static XSSFFactory getInstance(){
+        return inst;
+    }
+
+    public POIXMLDocumentPart createDocumentPart(PackageRelationship rel, PackagePart part){
+        POIXMLRelation descriptor = XSSFRelation.getInstance(rel.getRelationshipType());
+        if(descriptor == null || descriptor.getRelationClass() == null){
+            logger.log(POILogger.DEBUG, "using default POIXMLDocumentPart for " + rel.getRelationshipType());
+            return new POIXMLDocumentPart(part, rel);
+        }
+
+        try {
+            Class cls = descriptor.getRelationClass();
+            Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(PackagePart.class, PackageRelationship.class);
+            return constructor.newInstance(part, rel);
+        } catch (Exception e){
+            throw new POIXMLException(e);
+        }
+    }
+
+    public POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor){
+        try {
+            Class cls = descriptor.getRelationClass();
+            Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor();
+            return constructor.newInstance();
+        } catch (Exception e){
+            throw new POIXMLException(e);
+        }
+    }
+
+}
index e58b58377b19507712d4ecf83a6398ebc3926cf4..ef548e7b97ac0cbe6f3a054d979e3fb3a5acac83 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;\r
-import org.openxmlformats.schemas.drawingml.x2006.main.*;\r
-import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;\r
-import org.apache.poi.ss.usermodel.Workbook;\r
-import org.apache.poi.ss.usermodel.Picture;\r
-import org.apache.poi.util.POILogger;\r
-import org.apache.poi.util.POILogFactory;\r
-import org.apache.poi.POIXMLDocumentPart;\r
-import org.apache.poi.openxml4j.opc.PackageRelationship;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.w3c.dom.NodeList;\r
-import org.w3c.dom.Element;\r
-import javax.imageio.ImageIO;\r
-import javax.imageio.ImageReader;\r
-import javax.imageio.stream.ImageInputStream;\r
-import java.awt.*;\r
-import java.awt.image.BufferedImage;\r
-import java.io.IOException;\r
-import java.util.Iterator;\r
-\r
-/**\r
- * Represents a picture shape in a SpreadsheetML drawing.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFPicture extends XSSFShape implements Picture {\r
-    private static final POILogger logger = POILogFactory.getLogger(XSSFPicture.class);\r
-\r
-    /**\r
-     * Column width measured as the number of characters of the maximum digit width of the\r
-     * numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin\r
-     * padding (two on each side), plus 1 pixel padding for the gridlines.\r
-     *\r
-     * This value is the same for default font in Office 2007 (Calibry) and Office 2003 and earlier (Arial)\r
-     */\r
-    private static float DEFAULT_COLUMN_WIDTH = 9.140625f;\r
-\r
-    /**\r
-     * A default instance of CTShape used for creating new shapes.\r
-     */\r
-    private static CTPicture prototype = null;\r
-\r
-    /**\r
-     * This object specifies a picture object and all its properties\r
-     */\r
-    private CTPicture ctPicture;\r
-\r
-    /**\r
-     * Construct a new XSSFPicture object. This constructor is called from\r
-     *  {@link XSSFDrawing#createPicture(XSSFClientAnchor, int)}\r
-     *\r
-     * @param drawing the XSSFDrawing that owns this picture\r
-     */\r
-    protected XSSFPicture(XSSFDrawing drawing, CTPicture ctPicture){\r
-        this.drawing = drawing;\r
-        this.ctPicture = ctPicture;\r
-    }\r
-\r
-    /**\r
-     * Returns a prototype that is used to construct new shapes\r
-     *\r
-     * @return a prototype that is used to construct new shapes\r
-     */\r
-    protected static CTPicture prototype(){\r
-        if(prototype == null) {\r
-            CTPicture pic = CTPicture.Factory.newInstance();\r
-            CTPictureNonVisual nvpr = pic.addNewNvPicPr();\r
-            CTNonVisualDrawingProps nvProps = nvpr.addNewCNvPr();\r
-            nvProps.setId(1);\r
-            nvProps.setName("Picture 1");\r
-            nvProps.setDescr("Picture");\r
-            CTNonVisualPictureProperties nvPicProps = nvpr.addNewCNvPicPr();\r
-            nvPicProps.addNewPicLocks().setNoChangeAspect(true);\r
-\r
-            CTBlipFillProperties blip = pic.addNewBlipFill();\r
-            blip.addNewBlip().setEmbed("");\r
-            blip.addNewStretch().addNewFillRect();\r
-\r
-            CTShapeProperties sppr = pic.addNewSpPr();\r
-            CTTransform2D t2d = sppr.addNewXfrm();\r
-            CTPositiveSize2D ext = t2d.addNewExt();\r
-            //should be original picture width and height expressed in EMUs\r
-            ext.setCx(0);\r
-            ext.setCy(0);\r
-\r
-            CTPoint2D off = t2d.addNewOff();\r
-            off.setX(0);\r
-            off.setY(0);\r
-\r
-            CTPresetGeometry2D prstGeom = sppr.addNewPrstGeom();\r
-            prstGeom.setPrst(STShapeType.RECT);\r
-            prstGeom.addNewAvLst();\r
-\r
-            prototype = pic;\r
-        }\r
-        return prototype;\r
-    }\r
-\r
-    /**\r
-     * Link this shape with the picture data\r
-     *\r
-     * @param rel relationship referring the picture data\r
-     */\r
-    protected void setPictureReference(PackageRelationship rel){\r
-        ctPicture.getBlipFill().getBlip().setEmbed(rel.getId());\r
-    }\r
-\r
-    /**\r
-     * Return the underlying CTPicture bean that holds all properties for this picture\r
-     *\r
-     * @return the underlying CTPicture bean\r
-     */\r
-    public CTPicture getCTPicture(){\r
-        return ctPicture;\r
-    }\r
-\r
-    /**\r
-     * Reset the image to the original size.\r
-     */\r
-    public void resize(){\r
-        resize(1.0);\r
-    }\r
-\r
-    /**\r
-     * Reset the image to the original size.\r
-     *\r
-     * @param scale the amount by which image dimensions are multiplied relative to the original size.\r
-     * <code>resize(1.0)</code> sets the original size, <code>resize(0.5)</code> resize to 50% of the original,\r
-     * <code>resize(2.0)</code> resizes to 200% of the original.\r
-     */\r
-    public void resize(double scale){\r
-        XSSFClientAnchor anchor = (XSSFClientAnchor)getAnchor();\r
-\r
-        XSSFClientAnchor pref = getPreferredSize(scale);\r
-\r
-        int row2 = anchor.getRow1() + (pref.getRow2() - pref.getRow1());\r
-        int col2 = anchor.getCol1() + (pref.getCol2() - pref.getCol1());\r
-\r
-        anchor.setCol2(col2);\r
-        anchor.setDx1(0);\r
-        anchor.setDx2(pref.getDx2());\r
-\r
-        anchor.setRow2(row2);\r
-        anchor.setDy1(0);\r
-        anchor.setDy2(pref.getDy2());\r
-    }\r
-\r
-    /**\r
-     * Calculate the preferred size for this picture.\r
-     *\r
-     * @return XSSFClientAnchor with the preferred size for this image\r
-     */\r
-    public XSSFClientAnchor getPreferredSize(){\r
-        return getPreferredSize(1);\r
-    }\r
-\r
-    /**\r
-     * Calculate the preferred size for this picture.\r
-     *\r
-     * @param scale the amount by which image dimensions are multiplied relative to the original size.\r
-     * @return XSSFClientAnchor with the preferred size for this image\r
-     */\r
-    public XSSFClientAnchor getPreferredSize(double scale){\r
-        XSSFClientAnchor anchor = (XSSFClientAnchor)getAnchor();\r
-\r
-        XSSFPictureData data = getPictureData();\r
-        Dimension size = getImageDimension(data.getPackagePart(), data.getPictureType());\r
-        double scaledWidth = size.getWidth() * scale;\r
-        double scaledHeight = size.getHeight() * scale;\r
-\r
-        float w = 0;\r
-        int col2 = anchor.getCol1();\r
-        int dx2 = 0;\r
-        if(anchor.getDx1() > 0){\r
-            w += getColumnWidthInPixels(col2) - anchor.getDx1();\r
-            col2++;\r
-        }\r
-\r
-        for (;;) {\r
-            w += getColumnWidthInPixels(col2);\r
-            if(w > scaledWidth) break;\r
-            col2++;\r
-        }\r
-\r
-        if(w > scaledWidth) {\r
-            double cw = getColumnWidthInPixels(col2 + 1);\r
-            double delta = w - scaledWidth;\r
-            dx2 = (int)(EMU_PER_PIXEL*(cw-delta));\r
-        }\r
-        anchor.setCol2(col2);\r
-        anchor.setDx2(dx2);\r
-\r
-        double h = 0;\r
-        int row2 = anchor.getRow1();\r
-        int dy2 = 0;\r
-\r
-        if(anchor.getDy1() > 0){\r
-            h += getRowHeightInPixels(row2) - anchor.getDy1();\r
-            row2++;\r
-        }\r
-\r
-        for (;;) {\r
-            h += getRowHeightInPixels(row2);\r
-            if(h > scaledHeight) break;\r
-            row2++;\r
-        }\r
-\r
-        if(h > scaledHeight) {\r
-            double ch = getRowHeightInPixels(row2 + 1);\r
-            double delta = h - scaledHeight;\r
-            dy2 = (int)(EMU_PER_PIXEL*(ch-delta));\r
-        }\r
-        anchor.setRow2(row2);\r
-        anchor.setDy2(dy2);\r
-\r
-        CTPositiveSize2D size2d =  ctPicture.getSpPr().getXfrm().getExt();\r
-        size2d.setCx((long)(scaledWidth*EMU_PER_PIXEL));\r
-        size2d.setCy((long)(scaledHeight*EMU_PER_PIXEL));\r
-\r
-        return anchor;\r
-    }\r
-\r
-    private float getColumnWidthInPixels(int columnIndex){\r
-        XSSFSheet sheet = (XSSFSheet)getDrawing().getParent();\r
-\r
-        CTCol col = sheet.getColumnHelper().getColumn(columnIndex, false);\r
-        double numChars = col == null || !col.isSetWidth() ? DEFAULT_COLUMN_WIDTH : col.getWidth();\r
-\r
-        return (float)numChars*XSSFWorkbook.DEFAULT_CHARACTER_WIDTH;\r
-    }\r
-\r
-    private float getRowHeightInPixels(int rowIndex){\r
-        XSSFSheet sheet = (XSSFSheet)getDrawing().getParent();\r
-\r
-        XSSFRow row = sheet.getRow(rowIndex);\r
-        float height = row != null ?  row.getHeightInPoints() : sheet.getDefaultRowHeightInPoints();\r
-        return height*PIXEL_DPI/POINT_DPI;\r
-    }\r
-\r
-    /**\r
-     * Return the dimension of this image\r
-     *\r
-     * @param part the package part holding raw picture data\r
-     * @param type type of the picture: {@link Workbook#PICTURE_TYPE_JPEG},\r
-     * {@link Workbook#PICTURE_TYPE_PNG} or {@link Workbook#PICTURE_TYPE_DIB}\r
-     *\r
-     * @return image dimension in pixels\r
-     */\r
-    protected static Dimension getImageDimension(PackagePart part, int type){\r
-        Dimension size = new Dimension();\r
-\r
-        switch (type){\r
-            //we can calculate the preferred size only for JPEG, PNG and BMP\r
-            //other formats like WMF, EMF and PICT are not supported in Java\r
-            case Workbook.PICTURE_TYPE_JPEG:\r
-            case Workbook.PICTURE_TYPE_PNG:\r
-            case Workbook.PICTURE_TYPE_DIB:\r
-                try {\r
-                    //read the image using javax.imageio.*\r
-                    ImageInputStream iis = ImageIO.createImageInputStream( part.getInputStream() );\r
-                    Iterator i = ImageIO.getImageReaders( iis );\r
-                    ImageReader r = (ImageReader) i.next();\r
-                    r.setInput( iis );\r
-                    BufferedImage img = r.read(0);\r
-\r
-                    int[] dpi = getResolution(r);\r
-\r
-                    //if DPI is zero then assume standard 96 DPI\r
-                    //since cannot divide by zero\r
-                    if (dpi[0] == 0) dpi[0] = PIXEL_DPI;\r
-                    if (dpi[1] == 0) dpi[1] = PIXEL_DPI;\r
-\r
-                    size.width = img.getWidth()*PIXEL_DPI/dpi[0];\r
-                    size.height = img.getHeight()*PIXEL_DPI/dpi[1];\r
-\r
-                } catch (IOException e){\r
-                    //silently return if ImageIO failed to read the image\r
-                    logger.log(POILogger.WARN, e);\r
-                }\r
-\r
-                break;\r
-            default:\r
-                logger.log(POILogger.WARN, "Only JPEG, PNG and DIB pictures can be automatically sized");\r
-        }\r
-        return size;\r
-    }\r
-\r
-    /**\r
-     * The metadata of PNG and JPEG can contain the width of a pixel in millimeters.\r
-     * Return the the "effective" dpi calculated as <code>25.4/HorizontalPixelSize</code>\r
-     * and <code>25.4/VerticalPixelSize</code>.  Where 25.4 is the number of mm in inch.\r
-     *\r
-     * @return array of two elements: <code>{horisontalPdi, verticalDpi}</code>.\r
-     * {96, 96} is the default.\r
-     */\r
-    protected static int[] getResolution(ImageReader r) throws IOException {\r
-        int hdpi = PIXEL_DPI, vdpi = PIXEL_DPI;\r
-        double mm2inch = 25.4;\r
-\r
-        NodeList lst;\r
-        Element node = (Element)r.getImageMetadata(0).getAsTree("javax_imageio_1.0");\r
-        lst = node.getElementsByTagName("HorizontalPixelSize");\r
-        if(lst != null && lst.getLength() == 1) hdpi = (int)(mm2inch/Float.parseFloat(((Element)lst.item(0)).getAttribute("value")));\r
-\r
-        lst = node.getElementsByTagName("VerticalPixelSize");\r
-        if(lst != null && lst.getLength() == 1) vdpi = (int)(mm2inch/Float.parseFloat(((Element)lst.item(0)).getAttribute("value")));\r
-\r
-        return new int[]{hdpi, vdpi};\r
-    }\r
-\r
-    /**\r
-     * Return picture data for this shape\r
-     *\r
-     * @return picture data for this shape\r
-     */\r
-    public XSSFPictureData getPictureData() {\r
-        String blipId = ctPicture.getBlipFill().getBlip().getEmbed();\r
-        for (POIXMLDocumentPart part : getDrawing().getRelations()) {\r
-            if(part.getPackageRelationship().getId().equals(blipId)){\r
-                return (XSSFPictureData)part;\r
-            }\r
-        }\r
-        logger.log(POILogger.WARN, "Picture data was not found for blipId=" + blipId);\r
-        return null;\r
-    }\r
-\r
-    protected CTShapeProperties getShapeProperties(){\r
-        return ctPicture.getSpPr();\r
-    }\r
-\r
-}\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.usermodel;
+
+import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;
+import org.openxmlformats.schemas.drawingml.x2006.main.*;
+import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.ss.usermodel.Picture;
+import org.apache.poi.util.POILogger;
+import org.apache.poi.util.POILogFactory;
+import org.apache.poi.POIXMLDocumentPart;
+import org.apache.poi.openxml4j.opc.PackageRelationship;
+import org.apache.poi.openxml4j.opc.PackagePart;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Element;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
+import javax.imageio.stream.ImageInputStream;
+import java.awt.*;
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.util.Iterator;
+
+/**
+ * Represents a picture shape in a SpreadsheetML drawing.
+ *
+ * @author Yegor Kozlov
+ */
+public final class XSSFPicture extends XSSFShape implements Picture {
+    private static final POILogger logger = POILogFactory.getLogger(XSSFPicture.class);
+
+    /**
+     * Column width measured as the number of characters of the maximum digit width of the
+     * numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin
+     * padding (two on each side), plus 1 pixel padding for the gridlines.
+     *
+     * This value is the same for default font in Office 2007 (Calibry) and Office 2003 and earlier (Arial)
+     */
+    private static float DEFAULT_COLUMN_WIDTH = 9.140625f;
+
+    /**
+     * A default instance of CTShape used for creating new shapes.
+     */
+    private static CTPicture prototype = null;
+
+    /**
+     * This object specifies a picture object and all its properties
+     */
+    private CTPicture ctPicture;
+
+    /**
+     * Construct a new XSSFPicture object. This constructor is called from
+     *  {@link XSSFDrawing#createPicture(XSSFClientAnchor, int)}
+     *
+     * @param drawing the XSSFDrawing that owns this picture
+     */
+    protected XSSFPicture(XSSFDrawing drawing, CTPicture ctPicture){
+        this.drawing = drawing;
+        this.ctPicture = ctPicture;
+    }
+
+    /**
+     * Returns a prototype that is used to construct new shapes
+     *
+     * @return a prototype that is used to construct new shapes
+     */
+    protected static CTPicture prototype(){
+        if(prototype == null) {
+            CTPicture pic = CTPicture.Factory.newInstance();
+            CTPictureNonVisual nvpr = pic.addNewNvPicPr();
+            CTNonVisualDrawingProps nvProps = nvpr.addNewCNvPr();
+            nvProps.setId(1);
+            nvProps.setName("Picture 1");
+            nvProps.setDescr("Picture");
+            CTNonVisualPictureProperties nvPicProps = nvpr.addNewCNvPicPr();
+            nvPicProps.addNewPicLocks().setNoChangeAspect(true);
+
+            CTBlipFillProperties blip = pic.addNewBlipFill();
+            blip.addNewBlip().setEmbed("");
+            blip.addNewStretch().addNewFillRect();
+
+            CTShapeProperties sppr = pic.addNewSpPr();
+            CTTransform2D t2d = sppr.addNewXfrm();
+            CTPositiveSize2D ext = t2d.addNewExt();
+            //should be original picture width and height expressed in EMUs
+            ext.setCx(0);
+            ext.setCy(0);
+
+            CTPoint2D off = t2d.addNewOff();
+            off.setX(0);
+            off.setY(0);
+
+            CTPresetGeometry2D prstGeom = sppr.addNewPrstGeom();
+            prstGeom.setPrst(STShapeType.RECT);
+            prstGeom.addNewAvLst();
+
+            prototype = pic;
+        }
+        return prototype;
+    }
+
+    /**
+     * Link this shape with the picture data
+     *
+     * @param rel relationship referring the picture data
+     */
+    protected void setPictureReference(PackageRelationship rel){
+        ctPicture.getBlipFill().getBlip().setEmbed(rel.getId());
+    }
+
+    /**
+     * Return the underlying CTPicture bean that holds all properties for this picture
+     *
+     * @return the underlying CTPicture bean
+     */
+    public CTPicture getCTPicture(){
+        return ctPicture;
+    }
+
+    /**
+     * Reset the image to the original size.
+     */
+    public void resize(){
+        resize(1.0);
+    }
+
+    /**
+     * Reset the image to the original size.
+     *
+     * @param scale the amount by which image dimensions are multiplied relative to the original size.
+     * <code>resize(1.0)</code> sets the original size, <code>resize(0.5)</code> resize to 50% of the original,
+     * <code>resize(2.0)</code> resizes to 200% of the original.
+     */
+    public void resize(double scale){
+        XSSFClientAnchor anchor = (XSSFClientAnchor)getAnchor();
+
+        XSSFClientAnchor pref = getPreferredSize(scale);
+
+        int row2 = anchor.getRow1() + (pref.getRow2() - pref.getRow1());
+        int col2 = anchor.getCol1() + (pref.getCol2() - pref.getCol1());
+
+        anchor.setCol2(col2);
+        anchor.setDx1(0);
+        anchor.setDx2(pref.getDx2());
+
+        anchor.setRow2(row2);
+        anchor.setDy1(0);
+        anchor.setDy2(pref.getDy2());
+    }
+
+    /**
+     * Calculate the preferred size for this picture.
+     *
+     * @return XSSFClientAnchor with the preferred size for this image
+     */
+    public XSSFClientAnchor getPreferredSize(){
+        return getPreferredSize(1);
+    }
+
+    /**
+     * Calculate the preferred size for this picture.
+     *
+     * @param scale the amount by which image dimensions are multiplied relative to the original size.
+     * @return XSSFClientAnchor with the preferred size for this image
+     */
+    public XSSFClientAnchor getPreferredSize(double scale){
+        XSSFClientAnchor anchor = (XSSFClientAnchor)getAnchor();
+
+        XSSFPictureData data = getPictureData();
+        Dimension size = getImageDimension(data.getPackagePart(), data.getPictureType());
+        double scaledWidth = size.getWidth() * scale;
+        double scaledHeight = size.getHeight() * scale;
+
+        float w = 0;
+        int col2 = anchor.getCol1();
+        int dx2 = 0;
+        if(anchor.getDx1() > 0){
+            w += getColumnWidthInPixels(col2) - anchor.getDx1();
+            col2++;
+        }
+
+        for (;;) {
+            w += getColumnWidthInPixels(col2);
+            if(w > scaledWidth) break;
+            col2++;
+        }
+
+        if(w > scaledWidth) {
+            double cw = getColumnWidthInPixels(col2 + 1);
+            double delta = w - scaledWidth;
+            dx2 = (int)(EMU_PER_PIXEL*(cw-delta));
+        }
+        anchor.setCol2(col2);
+        anchor.setDx2(dx2);
+
+        double h = 0;
+        int row2 = anchor.getRow1();
+        int dy2 = 0;
+
+        if(anchor.getDy1() > 0){
+            h += getRowHeightInPixels(row2) - anchor.getDy1();
+            row2++;
+        }
+
+        for (;;) {
+            h += getRowHeightInPixels(row2);
+            if(h > scaledHeight) break;
+            row2++;
+        }
+
+        if(h > scaledHeight) {
+            double ch = getRowHeightInPixels(row2 + 1);
+            double delta = h - scaledHeight;
+            dy2 = (int)(EMU_PER_PIXEL*(ch-delta));
+        }
+        anchor.setRow2(row2);
+        anchor.setDy2(dy2);
+
+        CTPositiveSize2D size2d =  ctPicture.getSpPr().getXfrm().getExt();
+        size2d.setCx((long)(scaledWidth*EMU_PER_PIXEL));
+        size2d.setCy((long)(scaledHeight*EMU_PER_PIXEL));
+
+        return anchor;
+    }
+
+    private float getColumnWidthInPixels(int columnIndex){
+        XSSFSheet sheet = (XSSFSheet)getDrawing().getParent();
+
+        CTCol col = sheet.getColumnHelper().getColumn(columnIndex, false);
+        double numChars = col == null || !col.isSetWidth() ? DEFAULT_COLUMN_WIDTH : col.getWidth();
+
+        return (float)numChars*XSSFWorkbook.DEFAULT_CHARACTER_WIDTH;
+    }
+
+    private float getRowHeightInPixels(int rowIndex){
+        XSSFSheet sheet = (XSSFSheet)getDrawing().getParent();
+
+        XSSFRow row = sheet.getRow(rowIndex);
+        float height = row != null ?  row.getHeightInPoints() : sheet.getDefaultRowHeightInPoints();
+        return height*PIXEL_DPI/POINT_DPI;
+    }
+
+    /**
+     * Return the dimension of this image
+     *
+     * @param part the package part holding raw picture data
+     * @param type type of the picture: {@link Workbook#PICTURE_TYPE_JPEG},
+     * {@link Workbook#PICTURE_TYPE_PNG} or {@link Workbook#PICTURE_TYPE_DIB}
+     *
+     * @return image dimension in pixels
+     */
+    protected static Dimension getImageDimension(PackagePart part, int type){
+        Dimension size = new Dimension();
+
+        switch (type){
+            //we can calculate the preferred size only for JPEG, PNG and BMP
+            //other formats like WMF, EMF and PICT are not supported in Java
+            case Workbook.PICTURE_TYPE_JPEG:
+            case Workbook.PICTURE_TYPE_PNG:
+            case Workbook.PICTURE_TYPE_DIB:
+                try {
+                    //read the image using javax.imageio.*
+                    ImageInputStream iis = ImageIO.createImageInputStream( part.getInputStream() );
+                    Iterator i = ImageIO.getImageReaders( iis );
+                    ImageReader r = (ImageReader) i.next();
+                    r.setInput( iis );
+                    BufferedImage img = r.read(0);
+
+                    int[] dpi = getResolution(r);
+
+                    //if DPI is zero then assume standard 96 DPI
+                    //since cannot divide by zero
+                    if (dpi[0] == 0) dpi[0] = PIXEL_DPI;
+                    if (dpi[1] == 0) dpi[1] = PIXEL_DPI;
+
+                    size.width = img.getWidth()*PIXEL_DPI/dpi[0];
+                    size.height = img.getHeight()*PIXEL_DPI/dpi[1];
+
+                } catch (IOException e){
+                    //silently return if ImageIO failed to read the image
+                    logger.log(POILogger.WARN, e);
+                }
+
+                break;
+            default:
+                logger.log(POILogger.WARN, "Only JPEG, PNG and DIB pictures can be automatically sized");
+        }
+        return size;
+    }
+
+    /**
+     * The metadata of PNG and JPEG can contain the width of a pixel in millimeters.
+     * Return the the "effective" dpi calculated as <code>25.4/HorizontalPixelSize</code>
+     * and <code>25.4/VerticalPixelSize</code>.  Where 25.4 is the number of mm in inch.
+     *
+     * @return array of two elements: <code>{horisontalPdi, verticalDpi}</code>.
+     * {96, 96} is the default.
+     */
+    protected static int[] getResolution(ImageReader r) throws IOException {
+        int hdpi = PIXEL_DPI, vdpi = PIXEL_DPI;
+        double mm2inch = 25.4;
+
+        NodeList lst;
+        Element node = (Element)r.getImageMetadata(0).getAsTree("javax_imageio_1.0");
+        lst = node.getElementsByTagName("HorizontalPixelSize");
+        if(lst != null && lst.getLength() == 1) hdpi = (int)(mm2inch/Float.parseFloat(((Element)lst.item(0)).getAttribute("value")));
+
+        lst = node.getElementsByTagName("VerticalPixelSize");
+        if(lst != null && lst.getLength() == 1) vdpi = (int)(mm2inch/Float.parseFloat(((Element)lst.item(0)).getAttribute("value")));
+
+        return new int[]{hdpi, vdpi};
+    }
+
+    /**
+     * Return picture data for this shape
+     *
+     * @return picture data for this shape
+     */
+    public XSSFPictureData getPictureData() {
+        String blipId = ctPicture.getBlipFill().getBlip().getEmbed();
+        for (POIXMLDocumentPart part : getDrawing().getRelations()) {
+            if(part.getPackageRelationship().getId().equals(blipId)){
+                return (XSSFPictureData)part;
+            }
+        }
+        logger.log(POILogger.WARN, "Picture data was not found for blipId=" + blipId);
+        return null;
+    }
+
+    protected CTShapeProperties getShapeProperties(){
+        return ctPicture.getSpPr();
+    }
+
+}
index cd6c2208dfc725a229524ccb27f1985d4b241f90..4734a26fa5b0e41135d09d15500a9f78a8dd5b06 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-import org.openxmlformats.schemas.drawingml.x2006.main.*;\r
-\r
-/**\r
- * Represents a shape in a SpreadsheetML drawing.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public abstract class XSSFShape {\r
-    public static final int EMU_PER_PIXEL = 9525;\r
-    public static final int EMU_PER_POINT = 12700;\r
-\r
-    public static final int POINT_DPI = 72;\r
-    public static final int PIXEL_DPI = 96;\r
-\r
-    /**\r
-     * Parent drawing\r
-     */\r
-    protected XSSFDrawing drawing;\r
-\r
-    /**\r
-     * The parent shape, always not-null for shapes in groups\r
-     */\r
-    protected XSSFShapeGroup parent;\r
-\r
-    /**\r
-     * anchor that is used by this shape\r
-     */\r
-    protected XSSFAnchor anchor;\r
-\r
-    /**\r
-     * Return the drawing that owns this shape\r
-     *\r
-     * @return the parent drawing that owns this shape\r
-     */\r
-    public XSSFDrawing getDrawing(){\r
-        return drawing;\r
-    }\r
-\r
-    /**\r
-     * Gets the parent shape.\r
-     */\r
-    public XSSFShapeGroup getParent()\r
-    {\r
-        return parent;\r
-    }\r
-\r
-    /**\r
-     * @return  the anchor that is used by this shape.\r
-     */\r
-    public XSSFAnchor getAnchor()\r
-    {\r
-        return anchor;\r
-    }\r
-\r
-    /**\r
-     * Returns xml bean with shape properties. \r
-     *\r
-     * @return xml bean with shape properties.\r
-     */\r
-    protected abstract CTShapeProperties getShapeProperties();\r
-\r
-    /**\r
-     * Whether this shape is not filled with a color\r
-     *\r
-     * @return true if this shape is not filled with a color.\r
-     */\r
-    public boolean isNoFill() {\r
-        return getShapeProperties().isSetNoFill();\r
-    }\r
-\r
-    /**\r
-     * Sets whether this shape is filled or transparent.\r
-     *\r
-     * @param noFill if true then no fill will be applied to the shape element.\r
-     */\r
-    public void setNoFill(boolean noFill) {\r
-        CTShapeProperties props = getShapeProperties();\r
-        //unset solid and pattern fills if they are set\r
-        if (props.isSetPattFill()) props.unsetPattFill();\r
-        if (props.isSetSolidFill()) props.unsetSolidFill();\r
-\r
-        props.setNoFill(CTNoFillProperties.Factory.newInstance());\r
-    }\r
-\r
-    /**\r
-     * Sets the color used to fill this shape using the solid fill pattern.\r
-     */\r
-    public void setFillColor(int red, int green, int blue) {\r
-        CTShapeProperties props = getShapeProperties();\r
-        CTSolidColorFillProperties fill = props.isSetSolidFill() ? props.getSolidFill() : props.addNewSolidFill();\r
-        CTSRgbColor rgb = CTSRgbColor.Factory.newInstance();\r
-        rgb.setVal(new byte[]{(byte)red, (byte)green, (byte)blue});\r
-        fill.setSrgbClr(rgb);\r
-    }\r
-\r
-    /**\r
-     * The color applied to the lines of this shape.\r
-     */\r
-    public void setLineStyleColor( int red, int green, int blue ) {\r
-        CTShapeProperties props = getShapeProperties();\r
-        CTLineProperties ln = props.isSetLn() ? props.getLn() : props.addNewLn();\r
-        CTSolidColorFillProperties fill = ln.isSetSolidFill() ? ln.getSolidFill() : ln.addNewSolidFill();\r
-        CTSRgbColor rgb = CTSRgbColor.Factory.newInstance();\r
-        rgb.setVal(new byte[]{(byte)red, (byte)green, (byte)blue});\r
-        fill.setSrgbClr(rgb);\r
-    }\r
-\r
-    /**\r
-     * Specifies the width to be used for the underline stroke.\r
-     *\r
-     * @param lineWidth width in points\r
-     */\r
-    public void setLineWidth( double lineWidth ) {\r
-        CTShapeProperties props = getShapeProperties();\r
-        CTLineProperties ln = props.isSetLn() ? props.getLn() : props.addNewLn();\r
-        ln.setW((int)(lineWidth*EMU_PER_POINT));\r
-    }\r
-\r
-    /**\r
-     * Sets the line style.\r
-     *\r
-     * @param lineStyle\r
-     */\r
-    public void setLineStyle( int lineStyle ) {\r
-        CTShapeProperties props = getShapeProperties();\r
-        CTLineProperties ln = props.isSetLn() ? props.getLn() : props.addNewLn();\r
-        CTPresetLineDashProperties dashStyle = CTPresetLineDashProperties.Factory.newInstance();\r
-        dashStyle.setVal(STPresetLineDashVal.Enum.forInt(lineStyle+1));\r
-        ln.setPrstDash(dashStyle);\r
-    }\r
-\r
-}\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.usermodel;
+
+import org.openxmlformats.schemas.drawingml.x2006.main.*;
+
+/**
+ * Represents a shape in a SpreadsheetML drawing.
+ *
+ * @author Yegor Kozlov
+ */
+public abstract class XSSFShape {
+    public static final int EMU_PER_PIXEL = 9525;
+    public static final int EMU_PER_POINT = 12700;
+
+    public static final int POINT_DPI = 72;
+    public static final int PIXEL_DPI = 96;
+
+    /**
+     * Parent drawing
+     */
+    protected XSSFDrawing drawing;
+
+    /**
+     * The parent shape, always not-null for shapes in groups
+     */
+    protected XSSFShapeGroup parent;
+
+    /**
+     * anchor that is used by this shape
+     */
+    protected XSSFAnchor anchor;
+
+    /**
+     * Return the drawing that owns this shape
+     *
+     * @return the parent drawing that owns this shape
+     */
+    public XSSFDrawing getDrawing(){
+        return drawing;
+    }
+
+    /**
+     * Gets the parent shape.
+     */
+    public XSSFShapeGroup getParent()
+    {
+        return parent;
+    }
+
+    /**
+     * @return  the anchor that is used by this shape.
+     */
+    public XSSFAnchor getAnchor()
+    {
+        return anchor;
+    }
+
+    /**
+     * Returns xml bean with shape properties.
+     *
+     * @return xml bean with shape properties.
+     */
+    protected abstract CTShapeProperties getShapeProperties();
+
+    /**
+     * Whether this shape is not filled with a color
+     *
+     * @return true if this shape is not filled with a color.
+     */
+    public boolean isNoFill() {
+        return getShapeProperties().isSetNoFill();
+    }
+
+    /**
+     * Sets whether this shape is filled or transparent.
+     *
+     * @param noFill if true then no fill will be applied to the shape element.
+     */
+    public void setNoFill(boolean noFill) {
+        CTShapeProperties props = getShapeProperties();
+        //unset solid and pattern fills if they are set
+        if (props.isSetPattFill()) props.unsetPattFill();
+        if (props.isSetSolidFill()) props.unsetSolidFill();
+
+        props.setNoFill(CTNoFillProperties.Factory.newInstance());
+    }
+
+    /**
+     * Sets the color used to fill this shape using the solid fill pattern.
+     */
+    public void setFillColor(int red, int green, int blue) {
+        CTShapeProperties props = getShapeProperties();
+        CTSolidColorFillProperties fill = props.isSetSolidFill() ? props.getSolidFill() : props.addNewSolidFill();
+        CTSRgbColor rgb = CTSRgbColor.Factory.newInstance();
+        rgb.setVal(new byte[]{(byte)red, (byte)green, (byte)blue});
+        fill.setSrgbClr(rgb);
+    }
+
+    /**
+     * The color applied to the lines of this shape.
+     */
+    public void setLineStyleColor( int red, int green, int blue ) {
+        CTShapeProperties props = getShapeProperties();
+        CTLineProperties ln = props.isSetLn() ? props.getLn() : props.addNewLn();
+        CTSolidColorFillProperties fill = ln.isSetSolidFill() ? ln.getSolidFill() : ln.addNewSolidFill();
+        CTSRgbColor rgb = CTSRgbColor.Factory.newInstance();
+        rgb.setVal(new byte[]{(byte)red, (byte)green, (byte)blue});
+        fill.setSrgbClr(rgb);
+    }
+
+    /**
+     * Specifies the width to be used for the underline stroke.
+     *
+     * @param lineWidth width in points
+     */
+    public void setLineWidth( double lineWidth ) {
+        CTShapeProperties props = getShapeProperties();
+        CTLineProperties ln = props.isSetLn() ? props.getLn() : props.addNewLn();
+        ln.setW((int)(lineWidth*EMU_PER_POINT));
+    }
+
+    /**
+     * Sets the line style.
+     *
+     * @param lineStyle
+     */
+    public void setLineStyle( int lineStyle ) {
+        CTShapeProperties props = getShapeProperties();
+        CTLineProperties ln = props.isSetLn() ? props.getLn() : props.addNewLn();
+        CTPresetLineDashProperties dashStyle = CTPresetLineDashProperties.Factory.newInstance();
+        dashStyle.setVal(STPresetLineDashVal.Enum.forInt(lineStyle+1));
+        ln.setPrstDash(dashStyle);
+    }
+
+}
index ac6b1268baaec339b98e30326147183f7e69d72a..de2c22cdc2e3ea70a8fd08ab8cb403ac9113f145 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;\r
-import org.openxmlformats.schemas.drawingml.x2006.main.*;\r
-import org.apache.poi.openxml4j.opc.PackageRelationship;\r
-\r
-/**\r
- * This object specifies a group shape that represents many shapes grouped together. This shape is to be treated\r
- * just as if it were a regular shape but instead of being described by a single geometry it is made up of all the\r
- * shape geometries encompassed within it. Within a group shape each of the shapes that make up the group are\r
- * specified just as they normally would.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFShapeGroup extends XSSFShape {\r
-    private static CTGroupShape prototype = null;\r
-\r
-    private CTGroupShape ctGroup;\r
-\r
-    /**\r
-     * Construct a new XSSFSimpleShape object.\r
-     *\r
-     * @param drawing the XSSFDrawing that owns this shape\r
-     * @param ctGroup the XML bean that stores this group content\r
-     */\r
-    protected XSSFShapeGroup(XSSFDrawing drawing, CTGroupShape ctGroup) {\r
-        this.drawing = drawing;\r
-        this.ctGroup = ctGroup;\r
-    }\r
-\r
-    /**\r
-     * Initialize default structure of a new shape group\r
-     */\r
-    protected static CTGroupShape prototype() {\r
-        if (prototype == null) {\r
-            CTGroupShape shape = CTGroupShape.Factory.newInstance();\r
-\r
-            CTGroupShapeNonVisual nv = shape.addNewNvGrpSpPr();\r
-            CTNonVisualDrawingProps nvpr = nv.addNewCNvPr();\r
-            nvpr.setId(0);\r
-            nvpr.setName("Group 0");\r
-            nv.addNewCNvGrpSpPr();\r
-            CTGroupShapeProperties sp = shape.addNewGrpSpPr();\r
-            CTGroupTransform2D t2d = sp.addNewXfrm();\r
-            CTPositiveSize2D p1 = t2d.addNewExt();\r
-            p1.setCx(0);\r
-            p1.setCy(0);\r
-            CTPoint2D p2 = t2d.addNewOff();\r
-            p2.setX(0);\r
-            p2.setY(0);\r
-            CTPositiveSize2D p3 = t2d.addNewChExt();\r
-            p3.setCx(0);\r
-            p3.setCy(0);\r
-            CTPoint2D p4 = t2d.addNewChOff();\r
-            p4.setX(0);\r
-            p4.setY(0);\r
-\r
-            prototype = shape;\r
-        }\r
-        return prototype;\r
-    }\r
-\r
-    /**\r
-     * Constructs a textbox.\r
-     *\r
-     * @param anchor the child anchor describes how this shape is attached\r
-     *               to the group.\r
-     * @return      the newly created textbox.\r
-     */\r
-    public XSSFTextBox createTextbox(XSSFChildAnchor anchor){\r
-        CTShape ctShape = ctGroup.addNewSp();\r
-        ctShape.set(XSSFSimpleShape.prototype());\r
-\r
-        XSSFTextBox shape = new XSSFTextBox(getDrawing(), ctShape);\r
-        shape.parent = this;\r
-        shape.anchor = anchor;\r
-        shape.getCTShape().getSpPr().setXfrm(anchor.getCTTransform2D());\r
-        return shape;\r
-\r
-    }\r
-    /**\r
-     * Creates a simple shape.  This includes such shapes as lines, rectangles,\r
-     * and ovals.\r
-     *\r
-     * @param anchor the child anchor describes how this shape is attached\r
-     *               to the group.\r
-     * @return the newly created shape.\r
-     */\r
-    public XSSFSimpleShape createSimpleShape(XSSFChildAnchor anchor) {\r
-        CTShape ctShape = ctGroup.addNewSp();\r
-        ctShape.set(XSSFSimpleShape.prototype());\r
-\r
-        XSSFSimpleShape shape = new XSSFSimpleShape(getDrawing(), ctShape);\r
-        shape.parent = this;\r
-        shape.anchor = anchor;\r
-        shape.getCTShape().getSpPr().setXfrm(anchor.getCTTransform2D());\r
-        return shape;\r
-    }\r
-\r
-    /**\r
-     * Creates a simple shape.  This includes such shapes as lines, rectangles,\r
-     * and ovals.\r
-     *\r
-     * @param anchor the child anchor describes how this shape is attached\r
-     *               to the group.\r
-     * @return the newly created shape.\r
-     */\r
-    public XSSFConnector createConnector(XSSFChildAnchor anchor) {\r
-        CTConnector ctShape = ctGroup.addNewCxnSp();\r
-        ctShape.set(XSSFConnector.prototype());\r
-\r
-        XSSFConnector shape = new XSSFConnector(getDrawing(), ctShape);\r
-        shape.parent = this;\r
-        shape.anchor = anchor;\r
-        shape.getCTConnector().getSpPr().setXfrm(anchor.getCTTransform2D());\r
-        return shape;\r
-    }\r
-\r
-    /**\r
-     * Creates a picture.\r
-     *\r
-     * @param anchor       the client anchor describes how this picture is attached to the sheet.\r
-     * @param pictureIndex the index of the picture in the workbook collection of pictures,\r
-     *                     {@link XSSFWorkbook#getAllPictures()} .\r
-     * @return the newly created picture shape.\r
-     */\r
-    public XSSFPicture createPicture(XSSFClientAnchor anchor, int pictureIndex) {\r
-        PackageRelationship rel = getDrawing().addPictureReference(pictureIndex);\r
-\r
-        CTPicture ctShape = ctGroup.addNewPic();\r
-        ctShape.set(XSSFPicture.prototype());\r
-\r
-        XSSFPicture shape = new XSSFPicture(getDrawing(), ctShape);\r
-        shape.parent = this;\r
-        shape.anchor = anchor;\r
-        shape.setPictureReference(rel);\r
-        return shape;\r
-    }\r
-\r
-    public CTGroupShape getCTGroupShape() {\r
-        return ctGroup;\r
-    }\r
-\r
-    /**\r
-     * Sets the coordinate space of this group.  All children are constrained\r
-     * to these coordinates.\r
-     */\r
-    public void setCoordinates(int x1, int y1, int x2, int y2) {\r
-        CTGroupTransform2D t2d = ctGroup.getGrpSpPr().getXfrm();\r
-        CTPoint2D off = t2d.getOff();\r
-        off.setX(x1);\r
-        off.setY(y1);\r
-        CTPositiveSize2D ext = t2d.getExt();\r
-        ext.setCx(x2);\r
-        ext.setCy(y2);\r
-\r
-        CTPoint2D chOff = t2d.getChOff();\r
-        chOff.setX(x1);\r
-        chOff.setY(y1);\r
-        CTPositiveSize2D chExt = t2d.getChExt();\r
-        chExt.setCx(x2);\r
-        chExt.setCy(y2);\r
-    }\r
-\r
-    protected CTShapeProperties getShapeProperties() {\r
-        throw new IllegalStateException("Not supported for shape group");\r
-    }\r
-\r
-}\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.usermodel;
+
+import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;
+import org.openxmlformats.schemas.drawingml.x2006.main.*;
+import org.apache.poi.openxml4j.opc.PackageRelationship;
+
+/**
+ * This object specifies a group shape that represents many shapes grouped together. This shape is to be treated
+ * just as if it were a regular shape but instead of being described by a single geometry it is made up of all the
+ * shape geometries encompassed within it. Within a group shape each of the shapes that make up the group are
+ * specified just as they normally would.
+ *
+ * @author Yegor Kozlov
+ */
+public final class XSSFShapeGroup extends XSSFShape {
+    private static CTGroupShape prototype = null;
+
+    private CTGroupShape ctGroup;
+
+    /**
+     * Construct a new XSSFSimpleShape object.
+     *
+     * @param drawing the XSSFDrawing that owns this shape
+     * @param ctGroup the XML bean that stores this group content
+     */
+    protected XSSFShapeGroup(XSSFDrawing drawing, CTGroupShape ctGroup) {
+        this.drawing = drawing;
+        this.ctGroup = ctGroup;
+    }
+
+    /**
+     * Initialize default structure of a new shape group
+     */
+    protected static CTGroupShape prototype() {
+        if (prototype == null) {
+            CTGroupShape shape = CTGroupShape.Factory.newInstance();
+
+            CTGroupShapeNonVisual nv = shape.addNewNvGrpSpPr();
+            CTNonVisualDrawingProps nvpr = nv.addNewCNvPr();
+            nvpr.setId(0);
+            nvpr.setName("Group 0");
+            nv.addNewCNvGrpSpPr();
+            CTGroupShapeProperties sp = shape.addNewGrpSpPr();
+            CTGroupTransform2D t2d = sp.addNewXfrm();
+            CTPositiveSize2D p1 = t2d.addNewExt();
+            p1.setCx(0);
+            p1.setCy(0);
+            CTPoint2D p2 = t2d.addNewOff();
+            p2.setX(0);
+            p2.setY(0);
+            CTPositiveSize2D p3 = t2d.addNewChExt();
+            p3.setCx(0);
+            p3.setCy(0);
+            CTPoint2D p4 = t2d.addNewChOff();
+            p4.setX(0);
+            p4.setY(0);
+
+            prototype = shape;
+        }
+        return prototype;
+    }
+
+    /**
+     * Constructs a textbox.
+     *
+     * @param anchor the child anchor describes how this shape is attached
+     *               to the group.
+     * @return      the newly created textbox.
+     */
+    public XSSFTextBox createTextbox(XSSFChildAnchor anchor){
+        CTShape ctShape = ctGroup.addNewSp();
+        ctShape.set(XSSFSimpleShape.prototype());
+
+        XSSFTextBox shape = new XSSFTextBox(getDrawing(), ctShape);
+        shape.parent = this;
+        shape.anchor = anchor;
+        shape.getCTShape().getSpPr().setXfrm(anchor.getCTTransform2D());
+        return shape;
+
+    }
+    /**
+     * Creates a simple shape.  This includes such shapes as lines, rectangles,
+     * and ovals.
+     *
+     * @param anchor the child anchor describes how this shape is attached
+     *               to the group.
+     * @return the newly created shape.
+     */
+    public XSSFSimpleShape createSimpleShape(XSSFChildAnchor anchor) {
+        CTShape ctShape = ctGroup.addNewSp();
+        ctShape.set(XSSFSimpleShape.prototype());
+
+        XSSFSimpleShape shape = new XSSFSimpleShape(getDrawing(), ctShape);
+        shape.parent = this;
+        shape.anchor = anchor;
+        shape.getCTShape().getSpPr().setXfrm(anchor.getCTTransform2D());
+        return shape;
+    }
+
+    /**
+     * Creates a simple shape.  This includes such shapes as lines, rectangles,
+     * and ovals.
+     *
+     * @param anchor the child anchor describes how this shape is attached
+     *               to the group.
+     * @return the newly created shape.
+     */
+    public XSSFConnector createConnector(XSSFChildAnchor anchor) {
+        CTConnector ctShape = ctGroup.addNewCxnSp();
+        ctShape.set(XSSFConnector.prototype());
+
+        XSSFConnector shape = new XSSFConnector(getDrawing(), ctShape);
+        shape.parent = this;
+        shape.anchor = anchor;
+        shape.getCTConnector().getSpPr().setXfrm(anchor.getCTTransform2D());
+        return shape;
+    }
+
+    /**
+     * Creates a picture.
+     *
+     * @param anchor       the client anchor describes how this picture is attached to the sheet.
+     * @param pictureIndex the index of the picture in the workbook collection of pictures,
+     *                     {@link XSSFWorkbook#getAllPictures()} .
+     * @return the newly created picture shape.
+     */
+    public XSSFPicture createPicture(XSSFClientAnchor anchor, int pictureIndex) {
+        PackageRelationship rel = getDrawing().addPictureReference(pictureIndex);
+
+        CTPicture ctShape = ctGroup.addNewPic();
+        ctShape.set(XSSFPicture.prototype());
+
+        XSSFPicture shape = new XSSFPicture(getDrawing(), ctShape);
+        shape.parent = this;
+        shape.anchor = anchor;
+        shape.setPictureReference(rel);
+        return shape;
+    }
+
+    public CTGroupShape getCTGroupShape() {
+        return ctGroup;
+    }
+
+    /**
+     * Sets the coordinate space of this group.  All children are constrained
+     * to these coordinates.
+     */
+    public void setCoordinates(int x1, int y1, int x2, int y2) {
+        CTGroupTransform2D t2d = ctGroup.getGrpSpPr().getXfrm();
+        CTPoint2D off = t2d.getOff();
+        off.setX(x1);
+        off.setY(y1);
+        CTPositiveSize2D ext = t2d.getExt();
+        ext.setCx(x2);
+        ext.setCy(y2);
+
+        CTPoint2D chOff = t2d.getChOff();
+        chOff.setX(x1);
+        chOff.setY(y1);
+        CTPositiveSize2D chExt = t2d.getChExt();
+        chExt.setCx(x2);
+        chExt.setCy(y2);
+    }
+
+    protected CTShapeProperties getShapeProperties() {
+        throw new IllegalStateException("Not supported for shape group");
+    }
+
+}
index d5dd19c1ba612497a41fbe8b1734ee2507c8f772..3667c8cbb73c70e8aeafdde2e1429651b8ac1f08 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShape;\r
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShapeNonVisual;\r
-import org.openxmlformats.schemas.drawingml.x2006.main.*;\r
-import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;\r
-\r
-/**\r
- * Represents a shape with a predefined geometry in a SpreadsheetML drawing.\r
- * Possible shape types are defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFSimpleShape extends XSSFShape {\r
-    /**\r
-     * A default instance of CTShape used for creating new shapes.\r
-     */\r
-    private static CTShape prototype = null;\r
-\r
-    /**\r
-     *  Xml bean that stores properties of this shape\r
-     */\r
-    private CTShape ctShape;\r
-\r
-    protected XSSFSimpleShape(XSSFDrawing drawing, CTShape ctShape) {\r
-        this.drawing = drawing;\r
-        this.ctShape = ctShape;\r
-    }\r
-\r
-    /**\r
-     * Prototype with the default structure of a new auto-shape.\r
-     */\r
-    protected static CTShape prototype() {\r
-        if(prototype == null) {\r
-            CTShape shape = CTShape.Factory.newInstance();\r
-\r
-            CTShapeNonVisual nv = shape.addNewNvSpPr();\r
-            CTNonVisualDrawingProps nvp = nv.addNewCNvPr();\r
-            nvp.setId(1);\r
-            nvp.setName("Shape 1");\r
-            nv.addNewCNvSpPr();\r
-\r
-            CTShapeProperties sp = shape.addNewSpPr();\r
-            CTTransform2D t2d = sp.addNewXfrm();\r
-            CTPositiveSize2D p1 = t2d.addNewExt();\r
-            p1.setCx(0);\r
-            p1.setCy(0);\r
-            CTPoint2D p2 = t2d.addNewOff();\r
-            p2.setX(0);\r
-            p2.setY(0);\r
-\r
-            CTPresetGeometry2D geom = sp.addNewPrstGeom();\r
-            geom.setPrst(STShapeType.RECT);\r
-            geom.addNewAvLst();\r
-\r
-            CTShapeStyle style = shape.addNewStyle();\r
-            CTSchemeColor scheme = style.addNewLnRef().addNewSchemeClr();\r
-            scheme.setVal(STSchemeColorVal.ACCENT_1);\r
-            scheme.addNewShade().setVal(50000);\r
-            style.getLnRef().setIdx(2);\r
-\r
-            CTStyleMatrixReference fillref = style.addNewFillRef();\r
-            fillref.setIdx(1);\r
-            fillref.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_1);\r
-\r
-            CTStyleMatrixReference effectRef = style.addNewEffectRef();\r
-            effectRef.setIdx(0);\r
-            effectRef.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_1);\r
-\r
-            CTFontReference fontRef = style.addNewFontRef();\r
-            fontRef.setIdx(STFontCollectionIndex.MINOR);\r
-            fontRef.addNewSchemeClr().setVal(STSchemeColorVal.LT_1);\r
-\r
-            CTTextBody body = shape.addNewTxBody();\r
-            CTTextBodyProperties bodypr = body.addNewBodyPr();\r
-            bodypr.setAnchor(STTextAnchoringType.CTR);\r
-            bodypr.setRtlCol(false);\r
-            CTTextParagraph p = body.addNewP();\r
-            p.addNewPPr().setAlgn(STTextAlignType.CTR);\r
-            CTTextCharacterProperties endPr = p.addNewEndParaRPr();\r
-            endPr.setLang("en-US");\r
-            endPr.setSz(1100);\r
-\r
-            body.addNewLstStyle();\r
-\r
-            prototype = shape;\r
-        }\r
-        return prototype;\r
-    }\r
-\r
-    public CTShape getCTShape(){\r
-        return ctShape;\r
-    }\r
-\r
-    /**\r
-     * Gets the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}.\r
-     *\r
-     * @return the shape type\r
-     * @see org.apache.poi.ss.usermodel.ShapeTypes\r
-     */\r
-    public int getShapeType() {\r
-        return ctShape.getSpPr().getPrstGeom().getPrst().intValue();\r
-    }\r
-\r
-    /**\r
-     * Sets the shape types.\r
-     *\r
-     * @param type the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}.\r
-     * @see org.apache.poi.ss.usermodel.ShapeTypes\r
-     */\r
-    public void setShapeType(int type) {\r
-        ctShape.getSpPr().getPrstGeom().setPrst(STShapeType.Enum.forInt(type));\r
-    }\r
-\r
-    protected CTShapeProperties getShapeProperties(){\r
-        return ctShape.getSpPr();\r
-    }\r
-\r
-    public void setText(XSSFRichTextString str){\r
-\r
-        XSSFWorkbook wb = (XSSFWorkbook)getDrawing().getParent().getParent();\r
-        str.setStylesTableReference(wb.getStylesSource());\r
-\r
-        CTTextParagraph p = CTTextParagraph.Factory.newInstance();\r
-        if(str.numFormattingRuns() == 0){\r
-            CTRegularTextRun r = p.addNewR();\r
-            CTTextCharacterProperties rPr = r.addNewRPr();\r
-            rPr.setLang("en-US");\r
-            rPr.setSz(1100);\r
-            r.setT(str.getString());\r
-\r
-        } else {\r
-            for (int i = 0; i < str.getCTRst().sizeOfRArray(); i++) {\r
-                CTRElt lt = str.getCTRst().getRArray(i);\r
-                CTRPrElt ltPr = lt.getRPr();\r
-\r
-                CTRegularTextRun r = p.addNewR();\r
-                CTTextCharacterProperties rPr = r.addNewRPr();\r
-                rPr.setLang("en-US");\r
-\r
-                applyAttributes(ltPr, rPr);\r
-\r
-                r.setT(lt.getT());\r
-            }\r
-        }\r
-        ctShape.getTxBody().setPArray(new CTTextParagraph[]{p});\r
-\r
-    }\r
-\r
-    /**\r
-     *\r
-     * CTRPrElt --> CTFont adapter\r
-     */\r
-    private static void applyAttributes(CTRPrElt pr, CTTextCharacterProperties rPr){\r
-\r
-        if(pr.sizeOfBArray() > 0) rPr.setB(pr.getBArray(0).getVal());\r
-        //if(pr.sizeOfUArray() > 0) rPr.setU(pr.getUArray(0).getVal());\r
-        if(pr.sizeOfIArray() > 0) rPr.setI(pr.getIArray(0).getVal());\r
-\r
-        CTTextFont rFont = rPr.addNewLatin();\r
-        rFont.setTypeface(pr.sizeOfRFontArray() > 0 ? pr.getRFontArray(0).getVal() : "Arial");\r
-    }\r
-}\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.usermodel;
+
+import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShape;
+import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShapeNonVisual;
+import org.openxmlformats.schemas.drawingml.x2006.main.*;
+import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
+
+/**
+ * Represents a shape with a predefined geometry in a SpreadsheetML drawing.
+ * Possible shape types are defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}
+ *
+ * @author Yegor Kozlov
+ */
+public class XSSFSimpleShape extends XSSFShape { // TODO - instantiable superclass
+    /**
+     * A default instance of CTShape used for creating new shapes.
+     */
+    private static CTShape prototype = null;
+
+    /**
+     *  Xml bean that stores properties of this shape
+     */
+    private CTShape ctShape;
+
+    protected XSSFSimpleShape(XSSFDrawing drawing, CTShape ctShape) {
+        this.drawing = drawing;
+        this.ctShape = ctShape;
+    }
+
+    /**
+     * Prototype with the default structure of a new auto-shape.
+     */
+    protected static CTShape prototype() {
+        if(prototype == null) {
+            CTShape shape = CTShape.Factory.newInstance();
+
+            CTShapeNonVisual nv = shape.addNewNvSpPr();
+            CTNonVisualDrawingProps nvp = nv.addNewCNvPr();
+            nvp.setId(1);
+            nvp.setName("Shape 1");
+            nv.addNewCNvSpPr();
+
+            CTShapeProperties sp = shape.addNewSpPr();
+            CTTransform2D t2d = sp.addNewXfrm();
+            CTPositiveSize2D p1 = t2d.addNewExt();
+            p1.setCx(0);
+            p1.setCy(0);
+            CTPoint2D p2 = t2d.addNewOff();
+            p2.setX(0);
+            p2.setY(0);
+
+            CTPresetGeometry2D geom = sp.addNewPrstGeom();
+            geom.setPrst(STShapeType.RECT);
+            geom.addNewAvLst();
+
+            CTShapeStyle style = shape.addNewStyle();
+            CTSchemeColor scheme = style.addNewLnRef().addNewSchemeClr();
+            scheme.setVal(STSchemeColorVal.ACCENT_1);
+            scheme.addNewShade().setVal(50000);
+            style.getLnRef().setIdx(2);
+
+            CTStyleMatrixReference fillref = style.addNewFillRef();
+            fillref.setIdx(1);
+            fillref.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_1);
+
+            CTStyleMatrixReference effectRef = style.addNewEffectRef();
+            effectRef.setIdx(0);
+            effectRef.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_1);
+
+            CTFontReference fontRef = style.addNewFontRef();
+            fontRef.setIdx(STFontCollectionIndex.MINOR);
+            fontRef.addNewSchemeClr().setVal(STSchemeColorVal.LT_1);
+
+            CTTextBody body = shape.addNewTxBody();
+            CTTextBodyProperties bodypr = body.addNewBodyPr();
+            bodypr.setAnchor(STTextAnchoringType.CTR);
+            bodypr.setRtlCol(false);
+            CTTextParagraph p = body.addNewP();
+            p.addNewPPr().setAlgn(STTextAlignType.CTR);
+            CTTextCharacterProperties endPr = p.addNewEndParaRPr();
+            endPr.setLang("en-US");
+            endPr.setSz(1100);
+
+            body.addNewLstStyle();
+
+            prototype = shape;
+        }
+        return prototype;
+    }
+
+    public CTShape getCTShape(){
+        return ctShape;
+    }
+
+    /**
+     * Gets the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}.
+     *
+     * @return the shape type
+     * @see org.apache.poi.ss.usermodel.ShapeTypes
+     */
+    public int getShapeType() {
+        return ctShape.getSpPr().getPrstGeom().getPrst().intValue();
+    }
+
+    /**
+     * Sets the shape types.
+     *
+     * @param type the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}.
+     * @see org.apache.poi.ss.usermodel.ShapeTypes
+     */
+    public void setShapeType(int type) {
+        ctShape.getSpPr().getPrstGeom().setPrst(STShapeType.Enum.forInt(type));
+    }
+
+    protected CTShapeProperties getShapeProperties(){
+        return ctShape.getSpPr();
+    }
+
+    public void setText(XSSFRichTextString str){
+
+        XSSFWorkbook wb = (XSSFWorkbook)getDrawing().getParent().getParent();
+        str.setStylesTableReference(wb.getStylesSource());
+
+        CTTextParagraph p = CTTextParagraph.Factory.newInstance();
+        if(str.numFormattingRuns() == 0){
+            CTRegularTextRun r = p.addNewR();
+            CTTextCharacterProperties rPr = r.addNewRPr();
+            rPr.setLang("en-US");
+            rPr.setSz(1100);
+            r.setT(str.getString());
+
+        } else {
+            for (int i = 0; i < str.getCTRst().sizeOfRArray(); i++) {
+                CTRElt lt = str.getCTRst().getRArray(i);
+                CTRPrElt ltPr = lt.getRPr();
+
+                CTRegularTextRun r = p.addNewR();
+                CTTextCharacterProperties rPr = r.addNewRPr();
+                rPr.setLang("en-US");
+
+                applyAttributes(ltPr, rPr);
+
+                r.setT(lt.getT());
+            }
+        }
+        ctShape.getTxBody().setPArray(new CTTextParagraph[]{p});
+
+    }
+
+    /**
+     *
+     * CTRPrElt --> CTFont adapter
+     */
+    private static void applyAttributes(CTRPrElt pr, CTTextCharacterProperties rPr){
+
+        if(pr.sizeOfBArray() > 0) rPr.setB(pr.getBArray(0).getVal());
+        //if(pr.sizeOfUArray() > 0) rPr.setU(pr.getUArray(0).getVal());
+        if(pr.sizeOfIArray() > 0) rPr.setI(pr.getIArray(0).getVal());
+
+        CTTextFont rFont = rPr.addNewLatin();
+        rFont.setTypeface(pr.sizeOfRFontArray() > 0 ? pr.getRFontArray(0).getVal() : "Arial");
+    }
+}
index a708a759fdfcc252fb440d31b966ae09f96ebdc3..027f83bf2e6b08c2a0e89f8fbe51a13272dbce26 100755 (executable)
@@ -1,32 +1,32 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel;\r
-\r
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;\r
-\r
-/**\r
- * Represents a text box in a SpreadsheetML drawing.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFTextBox extends XSSFSimpleShape {\r
-\r
-    protected XSSFTextBox(XSSFDrawing drawing, CTShape ctShape) {\r
-        super(drawing, ctShape);\r
-    }\r
-\r
-}\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.usermodel;
+
+import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;
+
+/**
+ * Represents a text box in a SpreadsheetML drawing.
+ *
+ * @author Yegor Kozlov
+ */
+public final class XSSFTextBox extends XSSFSimpleShape {
+
+    protected XSSFTextBox(XSSFDrawing drawing, CTShape ctShape) {
+        super(drawing, ctShape);
+    }
+}
index 26fdad839cce5297d556f5c71c79a6b5f4384e63..9facfe8f28c3dfb295ba2e9ea8b35def9a07dd56 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xssf.usermodel.helpers;\r
-\r
-import org.apache.poi.xssf.usermodel.*;\r
-import org.apache.poi.ss.util.CellRangeAddress;\r
-import org.apache.poi.ss.formula.FormulaParser;\r
-import org.apache.poi.ss.formula.FormulaType;\r
-import org.apache.poi.ss.formula.FormulaRenderer;\r
-import org.apache.poi.ss.usermodel.Row;\r
-import org.apache.poi.ss.usermodel.Cell;\r
-import org.apache.poi.hssf.record.formula.FormulaShifter;\r
-import org.apache.poi.hssf.record.formula.Ptg;\r
-import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;\r
-import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula;\r
-\r
-import java.util.List;\r
-import java.util.ArrayList;\r
-\r
-/**\r
- * @author Yegor Kozlov\r
- */\r
-public class XSSFRowShifter {\r
-    private final XSSFSheet sheet;\r
-\r
-    public XSSFRowShifter(XSSFSheet sh) {\r
-        sheet = sh;\r
-    }\r
-\r
-    /**\r
-     * Shift merged regions\r
-     *\r
-     * @param startRow the row to start shifting\r
-     * @param endRow   the row to end shifting\r
-     * @param n        the number of rows to shift\r
-     * @return an array of affected cell regions\r
-     */\r
-    public List<CellRangeAddress> shiftMerged(int startRow, int endRow, int n) {\r
-        List<CellRangeAddress> shiftedRegions = new ArrayList<CellRangeAddress>();\r
-        //move merged regions completely if they fall within the new region boundaries when they are shifted\r
-        for (int i = 0; i < sheet.getNumMergedRegions(); i++) {\r
-            CellRangeAddress merged = sheet.getMergedRegion(i);\r
-\r
-            boolean inStart = (merged.getFirstRow() >= startRow || merged.getLastRow() >= startRow);\r
-            boolean inEnd = (merged.getFirstRow() <= endRow || merged.getLastRow() <= endRow);\r
-\r
-            //don't check if it's not within the shifted area\r
-            if (!inStart || !inEnd) {\r
-                continue;\r
-            }\r
-\r
-            //only shift if the region outside the shifted rows is not merged too\r
-            if (!containsCell(merged, startRow - 1, 0) && !containsCell(merged, endRow + 1, 0)) {\r
-                merged.setFirstRow(merged.getFirstRow() + n);\r
-                merged.setLastRow(merged.getLastRow() + n);\r
-                //have to remove/add it back\r
-                shiftedRegions.add(merged);\r
-                sheet.removeMergedRegion(i);\r
-                i = i - 1; // we have to back up now since we removed one\r
-            }\r
-        }\r
-\r
-        //read so it doesn't get shifted again\r
-        for (CellRangeAddress region : shiftedRegions) {\r
-            sheet.addMergedRegion(region);\r
-        }\r
-        return shiftedRegions;\r
-    }\r
-\r
-    /**\r
-     * Check if the  row and column are in the specified cell range\r
-     *\r
-     * @param cr    the cell range to check in\r
-     * @param rowIx the row to check\r
-     * @param colIx the column to check\r
-     * @return true if the range contains the cell [rowIx,colIx]\r
-     */\r
-    private static boolean containsCell(CellRangeAddress cr, int rowIx, int colIx) {\r
-        if (cr.getFirstRow() <= rowIx && cr.getLastRow() >= rowIx\r
-                && cr.getFirstColumn() <= colIx && cr.getLastColumn() >= colIx) {\r
-            return true;\r
-        }\r
-        return false;\r
-    }\r
-\r
-    /**\r
-     * Updated named ranges\r
-     */\r
-    public void updateNamedRanges(FormulaShifter shifter) {\r
-        XSSFWorkbook wb = sheet.getWorkbook();\r
-        XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);\r
-        for (int i = 0; i < wb.getNumberOfNames(); i++) {\r
-            XSSFName name = wb.getNameAt(i);\r
-            String formula = name.getRefersToFormula();\r
-            int sheetIndex = name.getSheetIndex();\r
-\r
-            Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.NAMEDRANGE, sheetIndex);\r
-            if (shifter.adjustFormula(ptgs, sheetIndex)) {\r
-                String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs);\r
-                name.setRefersToFormula(shiftedFmla);\r
-            }\r
-\r
-        }\r
-    }\r
-\r
-    /**\r
-     * Update formulas.\r
-     */\r
-    public void updateFormulas(FormulaShifter shifter) {\r
-        //update formulas on the parent sheet\r
-        updateSheetFormulas(sheet, shifter);\r
-\r
-        //update formulas on other sheets\r
-        XSSFWorkbook wb = sheet.getWorkbook();\r
-        for (XSSFSheet sh : wb) {\r
-            if (sheet == sh) continue;\r
-            updateSheetFormulas(sh, shifter);\r
-        }\r
-    }\r
-\r
-    private void updateSheetFormulas(XSSFSheet sh, FormulaShifter shifter) {\r
-        for (Row r : sh) {\r
-            XSSFRow row = (XSSFRow) r;\r
-            updateRowFormulas(row, shifter);\r
-        }\r
-    }\r
-\r
-    private void updateRowFormulas(XSSFRow row, FormulaShifter shifter) {\r
-        for (Cell c : row) {\r
-            XSSFCell cell = (XSSFCell) c;\r
-\r
-            CTCell ctCell = cell.getCTCell();\r
-            if (ctCell.isSetF()) {\r
-                CTCellFormula f = ctCell.getF();\r
-                String formula = f.getStringValue();\r
-                if (formula.length() > 0) {\r
-                    String shiftedFormula = shiftFormula(row, formula, shifter);\r
-                    if (shiftedFormula != null) {\r
-                        f.setStringValue(shiftedFormula);\r
-                    }\r
-                }\r
-\r
-                if (f.isSetRef()) { //Range of cells which the formula applies to.\r
-                    String ref = f.getRef();\r
-                    String shiftedRef = shiftFormula(row, ref, shifter);\r
-                    if (shiftedRef != null) f.setRef(shiftedRef);\r
-                }\r
-            }\r
-\r
-        }\r
-    }\r
-\r
-    /**\r
-     * Shift a formula using the supplied FormulaShifter\r
-     *\r
-     * @param row     the row of the cell this formula belongs to. Used to get a reference to the parent workbook.\r
-     * @param formula the formula to shift\r
-     * @param shifter the FormulaShifter object that operates on the parsed formula tokens\r
-     * @return the shifted formula if the formula was changed,\r
-     *         <code>null</code> if the formula wasn't modified\r
-     */\r
-    private static String shiftFormula(XSSFRow row, String formula, FormulaShifter shifter) {\r
-        XSSFSheet sheet = row.getSheet();\r
-        XSSFWorkbook wb = sheet.getWorkbook();\r
-        int sheetIndex = wb.getSheetIndex(sheet);\r
-        XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);\r
-        Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.CELL, sheetIndex);\r
-        String shiftedFmla = null;\r
-        if (shifter.adjustFormula(ptgs, sheetIndex)) {\r
-            shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs);\r
-        }\r
-        return shiftedFmla;\r
-    }\r
-\r
-}\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.usermodel.helpers;
+
+import org.apache.poi.xssf.usermodel.*;
+import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.ss.formula.FormulaParser;
+import org.apache.poi.ss.formula.FormulaType;
+import org.apache.poi.ss.formula.FormulaRenderer;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.hssf.record.formula.FormulaShifter;
+import org.apache.poi.hssf.record.formula.Ptg;
+import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
+import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula;
+
+import java.util.List;
+import java.util.ArrayList;
+
+/**
+ * @author Yegor Kozlov
+ */
+public final class XSSFRowShifter {
+    private final XSSFSheet sheet;
+
+    public XSSFRowShifter(XSSFSheet sh) {
+        sheet = sh;
+    }
+
+    /**
+     * Shift merged regions
+     *
+     * @param startRow the row to start shifting
+     * @param endRow   the row to end shifting
+     * @param n        the number of rows to shift
+     * @return an array of affected cell regions
+     */
+    public List<CellRangeAddress> shiftMerged(int startRow, int endRow, int n) {
+        List<CellRangeAddress> shiftedRegions = new ArrayList<CellRangeAddress>();
+        //move merged regions completely if they fall within the new region boundaries when they are shifted
+        for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
+            CellRangeAddress merged = sheet.getMergedRegion(i);
+
+            boolean inStart = (merged.getFirstRow() >= startRow || merged.getLastRow() >= startRow);
+            boolean inEnd = (merged.getFirstRow() <= endRow || merged.getLastRow() <= endRow);
+
+            //don't check if it's not within the shifted area
+            if (!inStart || !inEnd) {
+                continue;
+            }
+
+            //only shift if the region outside the shifted rows is not merged too
+            if (!containsCell(merged, startRow - 1, 0) && !containsCell(merged, endRow + 1, 0)) {
+                merged.setFirstRow(merged.getFirstRow() + n);
+                merged.setLastRow(merged.getLastRow() + n);
+                //have to remove/add it back
+                shiftedRegions.add(merged);
+                sheet.removeMergedRegion(i);
+                i = i - 1; // we have to back up now since we removed one
+            }
+        }
+
+        //read so it doesn't get shifted again
+        for (CellRangeAddress region : shiftedRegions) {
+            sheet.addMergedRegion(region);
+        }
+        return shiftedRegions;
+    }
+
+    /**
+     * Check if the  row and column are in the specified cell range
+     *
+     * @param cr    the cell range to check in
+     * @param rowIx the row to check
+     * @param colIx the column to check
+     * @return true if the range contains the cell [rowIx,colIx]
+     */
+    private static boolean containsCell(CellRangeAddress cr, int rowIx, int colIx) {
+        if (cr.getFirstRow() <= rowIx && cr.getLastRow() >= rowIx
+                && cr.getFirstColumn() <= colIx && cr.getLastColumn() >= colIx) {
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Updated named ranges
+     */
+    public void updateNamedRanges(FormulaShifter shifter) {
+        XSSFWorkbook wb = sheet.getWorkbook();
+        XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
+        for (int i = 0; i < wb.getNumberOfNames(); i++) {
+            XSSFName name = wb.getNameAt(i);
+            String formula = name.getRefersToFormula();
+            int sheetIndex = name.getSheetIndex();
+
+            Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.NAMEDRANGE, sheetIndex);
+            if (shifter.adjustFormula(ptgs, sheetIndex)) {
+                String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs);
+                name.setRefersToFormula(shiftedFmla);
+            }
+
+        }
+    }
+
+    /**
+     * Update formulas.
+     */
+    public void updateFormulas(FormulaShifter shifter) {
+        //update formulas on the parent sheet
+        updateSheetFormulas(sheet, shifter);
+
+        //update formulas on other sheets
+        XSSFWorkbook wb = sheet.getWorkbook();
+        for (XSSFSheet sh : wb) {
+            if (sheet == sh) continue;
+            updateSheetFormulas(sh, shifter);
+        }
+    }
+
+    private void updateSheetFormulas(XSSFSheet sh, FormulaShifter shifter) {
+        for (Row r : sh) {
+            XSSFRow row = (XSSFRow) r;
+            updateRowFormulas(row, shifter);
+        }
+    }
+
+    private void updateRowFormulas(XSSFRow row, FormulaShifter shifter) {
+        for (Cell c : row) {
+            XSSFCell cell = (XSSFCell) c;
+
+            CTCell ctCell = cell.getCTCell();
+            if (ctCell.isSetF()) {
+                CTCellFormula f = ctCell.getF();
+                String formula = f.getStringValue();
+                if (formula.length() > 0) {
+                    String shiftedFormula = shiftFormula(row, formula, shifter);
+                    if (shiftedFormula != null) {
+                        f.setStringValue(shiftedFormula);
+                    }
+                }
+
+                if (f.isSetRef()) { //Range of cells which the formula applies to.
+                    String ref = f.getRef();
+                    String shiftedRef = shiftFormula(row, ref, shifter);
+                    if (shiftedRef != null) f.setRef(shiftedRef);
+                }
+            }
+
+        }
+    }
+
+    /**
+     * Shift a formula using the supplied FormulaShifter
+     *
+     * @param row     the row of the cell this formula belongs to. Used to get a reference to the parent workbook.
+     * @param formula the formula to shift
+     * @param shifter the FormulaShifter object that operates on the parsed formula tokens
+     * @return the shifted formula if the formula was changed,
+     *         <code>null</code> if the formula wasn't modified
+     */
+    private static String shiftFormula(XSSFRow row, String formula, FormulaShifter shifter) {
+        XSSFSheet sheet = row.getSheet();
+        XSSFWorkbook wb = sheet.getWorkbook();
+        int sheetIndex = wb.getSheetIndex(sheet);
+        XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
+        Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.CELL, sheetIndex);
+        String shiftedFmla = null;
+        if (shifter.adjustFormula(ptgs, sheetIndex)) {
+            shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs);
+        }
+        return shiftedFmla;
+    }
+
+}
index fd0b63565414122b8e305d95b13a7b37d151dc22..3b2a90baec46c2162f228fbd1fb210dd4f4832d6 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xwpf.usermodel;\r
-\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-\r
-/**\r
- * Specifies all types of borders which can be specified for WordprocessingML\r
- * objects which have a border. Borders can be separated into two types:\r
- * <ul> \r
- * <li> Line borders: which specify a pattern to be used when drawing a line around the\r
- * specified object.\r
- * </li> \r
- * <li> Art borders: which specify a repeated image to be used\r
- * when drawing a border around the specified object. Line borders may be\r
- * specified on any object which allows a border, however, art borders may only\r
- * be used as a border at the page level - the borders under the pgBorders\r
- * element\r
- *</li>\r
- * </ul>\r
- * @author Gisella Bronzetti\r
- */\r
-public enum Borders {\r
-\r
-    NIL(1),\r
-\r
-    NONE(2),\r
-\r
-    /**\r
-     * Specifies a line border consisting of a single line around the parent\r
-     * object.\r
-     */\r
-    SINGLE(3),\r
-\r
-    THICK(4),\r
-\r
-    DOUBLE(5),\r
-\r
-    DOTTED(6),\r
-\r
-    DASHED(7),\r
-\r
-    DOT_DASH(8),\r
-\r
-    DOT_DOT_DASH(9),\r
-\r
-    TRIPLE(10),\r
-\r
-    THIN_THICK_SMALL_GAP(11),\r
-\r
-    THICK_THIN_SMALL_GAP(12),\r
-\r
-    THIN_THICK_THIN_SMALL_GAP(13),\r
-\r
-    THIN_THICK_MEDIUM_GAP(14),\r
-\r
-    THICK_THIN_MEDIUM_GAP(15),\r
-\r
-    THIN_THICK_THIN_MEDIUM_GAP(16),\r
-\r
-    THIN_THICK_LARGE_GAP(17),\r
-\r
-    THICK_THIN_LARGE_GAP(18),\r
-\r
-    THIN_THICK_THIN_LARGE_GAP(19),\r
-\r
-    WAVE(20),\r
-\r
-    DOUBLE_WAVE(21),\r
-\r
-    DASH_SMALL_GAP(22),\r
-\r
-    DASH_DOT_STROKED(23),\r
-\r
-    THREE_D_EMBOSS(24),\r
-\r
-    THREE_D_ENGRAVE(25),\r
-\r
-    OUTSET(26),\r
-\r
-    INSET(27),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of an apple\r
-     */\r
-    APPLES(28),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a shell pattern\r
-     */\r
-    ARCHED_SCALLOPS(29),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a baby pacifier\r
-     */\r
-    BABY_PACIFIER(30),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a baby rattle\r
-     */\r
-    BABY_RATTLE(31),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a set of\r
-     * balloons\r
-     */\r
-    BALLOONS_3_COLORS(32),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a hot air\r
-     * balloon\r
-     */\r
-    BALLOONS_HOT_AIR(33),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a black and\r
-     * white background.\r
-     */\r
-    BASIC_BLACK_DASHES(34),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a black dot on\r
-     * a white background.\r
-     */\r
-    BASIC_BLACK_DOTS(35),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a black and\r
-     * white background\r
-     */\r
-    BASIC_BLACK_SQUARES(36),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a black and\r
-     * white background.\r
-     */\r
-    BASIC_THIN_LINES(37),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a black and\r
-     * white background.\r
-     */\r
-    BASIC_WHITE_DASHES(38),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a white dot on\r
-     * a black background.\r
-     */\r
-    BASIC_WHITE_DOTS(39),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a black and\r
-     * white background.\r
-     */\r
-    BASIC_WHITE_SQUARES(40),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a black and\r
-     * white background.\r
-     */\r
-    BASIC_WIDE_INLINE(41),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a black and\r
-     * white background\r
-     */\r
-    BASIC_WIDE_MIDLINE(42),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a black and\r
-     * white background\r
-     */\r
-    BASIC_WIDE_OUTLINE(43),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of bats\r
-     */\r
-    BATS(44),\r
-\r
-    /**\r
-     * Specifies an art border consisting of repeating images of birds\r
-     */\r
-    BIRDS(45),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of birds flying\r
-     */\r
-    BIRDS_FLIGHT(46),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a cabin\r
-     */\r
-    CABINS(47),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a piece of cake\r
-     */\r
-    CAKE_SLICE(48),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of candy corn\r
-     */\r
-    CANDY_CORN(49),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a knot work\r
-     * pattern\r
-     */\r
-    CELTIC_KNOTWORK(50),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a banner.\r
-     * <p>\r
-     * If the border is on the left or right, no border is displayed.\r
-     * </p>\r
-     */\r
-    CERTIFICATE_BANNER(51),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a chain link\r
-     * pattern.\r
-     */\r
-    CHAIN_LINK(52),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a champagne\r
-     * bottle\r
-     */\r
-    CHAMPAGNE_BOTTLE(53),\r
-\r
-    /**\r
-     * Specifies an art border consisting of repeating images of a compass\r
-     */\r
-    CHECKED_BAR_BLACK(54),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeating image of a colored\r
-     * pattern.\r
-     */\r
-    CHECKED_BAR_COLOR(55),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a checkerboard\r
-     */\r
-    CHECKERED(56),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a Christmas\r
-     * tree\r
-     */\r
-    CHRISTMAS_TREE(57),\r
-\r
-    /**\r
-     * Specifies an art border consisting of repeating images of lines and\r
-     * circles\r
-     */\r
-    CIRCLES_LINES(58),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a rectangular\r
-     * pattern\r
-     */\r
-    CIRCLES_RECTANGLES(59),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a wave\r
-     */\r
-    CLASSICAL_WAVE(60),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a clock\r
-     */\r
-    CLOCKS(61),\r
-\r
-    /**\r
-     * Specifies an art border consisting of repeating images of a compass\r
-     */\r
-    COMPASS(62),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of confetti\r
-     */\r
-    CONFETTI(63),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of confetti\r
-     */\r
-    CONFETTI_GRAYS(64),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of confetti\r
-     */\r
-    CONFETTI_OUTLINE(65),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of confetti\r
-     * streamers\r
-     */\r
-    CONFETTI_STREAMERS(66),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of confetti\r
-     */\r
-    CONFETTI_WHITE(67),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image\r
-     */\r
-    CORNER_TRIANGLES(68),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a dashed line\r
-     */\r
-    COUPON_CUTOUT_DASHES(69),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a dotted line\r
-     */\r
-    COUPON_CUTOUT_DOTS(70),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a maze-like\r
-     * pattern\r
-     */\r
-    CRAZY_MAZE(71),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a butterfly\r
-     */\r
-    CREATURES_BUTTERFLY(72),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a fish\r
-     */\r
-    CREATURES_FISH(73),\r
-\r
-    /**\r
-     * Specifies an art border consisting of repeating images of insects.\r
-     */\r
-    CREATURES_INSECTS(74),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of a ladybug\r
-     */\r
-    CREATURES_LADY_BUG(75),\r
-\r
-    /**\r
-     * Specifies an art border consisting of repeating images of a cross-stitch\r
-     * pattern\r
-     */\r
-    CROSS_STITCH(76),\r
-\r
-    /**\r
-     * Specifies an art border consisting of a repeated image of Cupid\r
-     */\r
-    CUP(77),\r
-\r
-    DECO_ARCH(78),\r
-\r
-    DECO_ARCH_COLOR(79),\r
-\r
-    DECO_BLOCKS(80),\r
-\r
-    DIAMONDS_GRAY(81),\r
-\r
-    DOUBLE_D(82),\r
-\r
-    DOUBLE_DIAMONDS(83),\r
-\r
-    EARTH_1(84),\r
-\r
-    EARTH_2(85),\r
-\r
-    ECLIPSING_SQUARES_1(86),\r
-\r
-    ECLIPSING_SQUARES_2(87),\r
-\r
-    EGGS_BLACK(88),\r
-\r
-    FANS(89),\r
-\r
-    FILM(90),\r
-\r
-    FIRECRACKERS(91),\r
-\r
-    FLOWERS_BLOCK_PRINT(92),\r
-\r
-    FLOWERS_DAISIES(93),\r
-\r
-    FLOWERS_MODERN_1(94),\r
-\r
-    FLOWERS_MODERN_2(95),\r
-\r
-    FLOWERS_PANSY(96),\r
-\r
-    FLOWERS_RED_ROSE(97),\r
-\r
-    FLOWERS_ROSES(98),\r
-\r
-    FLOWERS_TEACUP(99),\r
-\r
-    FLOWERS_TINY(100),\r
-\r
-    GEMS(101),\r
-\r
-    GINGERBREAD_MAN(102),\r
-\r
-    GRADIENT(103),\r
-\r
-    HANDMADE_1(104),\r
-\r
-    HANDMADE_2(105),\r
-\r
-    HEART_BALLOON(106),\r
-\r
-    HEART_GRAY(107),\r
-\r
-    HEARTS(108),\r
-\r
-    HEEBIE_JEEBIES(109),\r
-\r
-    HOLLY(110),\r
-\r
-    HOUSE_FUNKY(111),\r
-\r
-    HYPNOTIC(112),\r
-\r
-    ICE_CREAM_CONES(113),\r
-\r
-    LIGHT_BULB(114),\r
-\r
-    LIGHTNING_1(115),\r
-\r
-    LIGHTNING_2(116),\r
-\r
-    MAP_PINS(117),\r
-\r
-    MAPLE_LEAF(118),\r
-\r
-    MAPLE_MUFFINS(119),\r
-\r
-    MARQUEE(120),\r
-\r
-    MARQUEE_TOOTHED(121),\r
-\r
-    MOONS(122),\r
-\r
-    MOSAIC(123),\r
-\r
-    MUSIC_NOTES(124),\r
-\r
-    NORTHWEST(125),\r
-\r
-    OVALS(126),\r
-\r
-    PACKAGES(127),\r
-\r
-    PALMS_BLACK(128),\r
-\r
-    PALMS_COLOR(129),\r
-\r
-    PAPER_CLIPS(130),\r
-\r
-    PAPYRUS(131),\r
-\r
-    PARTY_FAVOR(132),\r
-\r
-    PARTY_GLASS(133),\r
-\r
-    PENCILS(134),\r
-\r
-    PEOPLE(135),\r
-\r
-    PEOPLE_WAVING(136),\r
-\r
-    PEOPLE_HATS(137),\r
-\r
-    POINSETTIAS(138),\r
-\r
-    POSTAGE_STAMP(139),\r
-\r
-    PUMPKIN_1(140),\r
-\r
-    PUSH_PIN_NOTE_2(141),\r
-\r
-    PUSH_PIN_NOTE_1(142),\r
-\r
-    PYRAMIDS(143),\r
-\r
-    PYRAMIDS_ABOVE(144),\r
-\r
-    QUADRANTS(145),\r
-\r
-    RINGS(146),\r
-\r
-    SAFARI(147),\r
-\r
-    SAWTOOTH(148),\r
-\r
-    SAWTOOTH_GRAY(149),\r
-\r
-    SCARED_CAT(150),\r
-\r
-    SEATTLE(151),\r
-\r
-    SHADOWED_SQUARES(152),\r
-\r
-    SHARKS_TEETH(153),\r
-\r
-    SHOREBIRD_TRACKS(154),\r
-\r
-    SKYROCKET(155),\r
-\r
-    SNOWFLAKE_FANCY(156),\r
-\r
-    SNOWFLAKES(157),\r
-\r
-    SOMBRERO(158),\r
-\r
-    SOUTHWEST(159),\r
-\r
-    STARS(160),\r
-\r
-    STARS_TOP(161),\r
-\r
-    STARS_3_D(162),\r
-\r
-    STARS_BLACK(163),\r
-\r
-    STARS_SHADOWED(164),\r
-\r
-    SUN(165),\r
-\r
-    SWIRLIGIG(166),\r
-\r
-    TORN_PAPER(167),\r
-\r
-    TORN_PAPER_BLACK(168),\r
-\r
-    TREES(169),\r
-\r
-    TRIANGLE_PARTY(170),\r
-\r
-    TRIANGLES(171),\r
-\r
-    TRIBAL_1(172),\r
-\r
-    TRIBAL_2(173),\r
-\r
-    TRIBAL_3(174),\r
-\r
-    TRIBAL_4(175),\r
-\r
-    TRIBAL_5(176),\r
-\r
-    TRIBAL_6(177),\r
-\r
-    TWISTED_LINES_1(178),\r
-\r
-    TWISTED_LINES_2(179),\r
-\r
-    VINE(180),\r
-\r
-    WAVELINE(181),\r
-\r
-    WEAVING_ANGLES(182),\r
-\r
-    WEAVING_BRAID(183),\r
-\r
-    WEAVING_RIBBON(184),\r
-\r
-    WEAVING_STRIPS(185),\r
-\r
-    WHITE_FLOWERS(186),\r
-\r
-    WOODWORK(187),\r
-\r
-    X_ILLUSIONS(188),\r
-\r
-    ZANY_TRIANGLES(189),\r
-\r
-    ZIG_ZAG(190),\r
-\r
-    ZIG_ZAG_STITCH(191);\r
-\r
-    private final int value;\r
-\r
-    private Borders(int val) {\r
-       value = val;\r
-    }\r
-\r
-    public int getValue() {\r
-       return value;\r
-    }\r
-\r
-    private static Map<Integer, Borders> imap = new HashMap<Integer, Borders>();\r
-    static {\r
-       for (Borders p : values()) {\r
-           imap.put(p.getValue(), p);\r
-       }\r
-    }\r
-\r
-    public static Borders valueOf(int type) {\r
-       Borders pBorder = imap.get(type);\r
-       if (pBorder == null)\r
-           throw new IllegalArgumentException("Unknown paragraph border: "\r
-                   + type);\r
-       return pBorder;\r
-    }\r
-\r
-}\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.xwpf.usermodel;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Specifies all types of borders which can be specified for WordprocessingML
+ * objects which have a border. Borders can be separated into two types:
+ * <ul>
+ * <li> Line borders: which specify a pattern to be used when drawing a line around the
+ * specified object.
+ * </li>
+ * <li> Art borders: which specify a repeated image to be used
+ * when drawing a border around the specified object. Line borders may be
+ * specified on any object which allows a border, however, art borders may only
+ * be used as a border at the page level - the borders under the pgBorders
+ * element
+ *</li>
+ * </ul>
+ * @author Gisella Bronzetti
+ */
+public enum Borders {
+
+    NIL(1),
+
+    NONE(2),
+
+    /**
+     * Specifies a line border consisting of a single line around the parent
+     * object.
+     */
+    SINGLE(3),
+
+    THICK(4),
+
+    DOUBLE(5),
+
+    DOTTED(6),
+
+    DASHED(7),
+
+    DOT_DASH(8),
+
+    DOT_DOT_DASH(9),
+
+    TRIPLE(10),
+
+    THIN_THICK_SMALL_GAP(11),
+
+    THICK_THIN_SMALL_GAP(12),
+
+    THIN_THICK_THIN_SMALL_GAP(13),
+
+    THIN_THICK_MEDIUM_GAP(14),
+
+    THICK_THIN_MEDIUM_GAP(15),
+
+    THIN_THICK_THIN_MEDIUM_GAP(16),
+
+    THIN_THICK_LARGE_GAP(17),
+
+    THICK_THIN_LARGE_GAP(18),
+
+    THIN_THICK_THIN_LARGE_GAP(19),
+
+    WAVE(20),
+
+    DOUBLE_WAVE(21),
+
+    DASH_SMALL_GAP(22),
+
+    DASH_DOT_STROKED(23),
+
+    THREE_D_EMBOSS(24),
+
+    THREE_D_ENGRAVE(25),
+
+    OUTSET(26),
+
+    INSET(27),
+
+    /**
+     * Specifies an art border consisting of a repeated image of an apple
+     */
+    APPLES(28),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a shell pattern
+     */
+    ARCHED_SCALLOPS(29),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a baby pacifier
+     */
+    BABY_PACIFIER(30),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a baby rattle
+     */
+    BABY_RATTLE(31),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a set of
+     * balloons
+     */
+    BALLOONS_3_COLORS(32),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a hot air
+     * balloon
+     */
+    BALLOONS_HOT_AIR(33),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a black and
+     * white background.
+     */
+    BASIC_BLACK_DASHES(34),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a black dot on
+     * a white background.
+     */
+    BASIC_BLACK_DOTS(35),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a black and
+     * white background
+     */
+    BASIC_BLACK_SQUARES(36),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a black and
+     * white background.
+     */
+    BASIC_THIN_LINES(37),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a black and
+     * white background.
+     */
+    BASIC_WHITE_DASHES(38),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a white dot on
+     * a black background.
+     */
+    BASIC_WHITE_DOTS(39),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a black and
+     * white background.
+     */
+    BASIC_WHITE_SQUARES(40),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a black and
+     * white background.
+     */
+    BASIC_WIDE_INLINE(41),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a black and
+     * white background
+     */
+    BASIC_WIDE_MIDLINE(42),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a black and
+     * white background
+     */
+    BASIC_WIDE_OUTLINE(43),
+
+    /**
+     * Specifies an art border consisting of a repeated image of bats
+     */
+    BATS(44),
+
+    /**
+     * Specifies an art border consisting of repeating images of birds
+     */
+    BIRDS(45),
+
+    /**
+     * Specifies an art border consisting of a repeated image of birds flying
+     */
+    BIRDS_FLIGHT(46),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a cabin
+     */
+    CABINS(47),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a piece of cake
+     */
+    CAKE_SLICE(48),
+
+    /**
+     * Specifies an art border consisting of a repeated image of candy corn
+     */
+    CANDY_CORN(49),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a knot work
+     * pattern
+     */
+    CELTIC_KNOTWORK(50),
+
+    /**
+     * Specifies an art border consisting of a banner.
+     * <p>
+     * If the border is on the left or right, no border is displayed.
+     * </p>
+     */
+    CERTIFICATE_BANNER(51),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a chain link
+     * pattern.
+     */
+    CHAIN_LINK(52),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a champagne
+     * bottle
+     */
+    CHAMPAGNE_BOTTLE(53),
+
+    /**
+     * Specifies an art border consisting of repeating images of a compass
+     */
+    CHECKED_BAR_BLACK(54),
+
+    /**
+     * Specifies an art border consisting of a repeating image of a colored
+     * pattern.
+     */
+    CHECKED_BAR_COLOR(55),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a checkerboard
+     */
+    CHECKERED(56),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a Christmas
+     * tree
+     */
+    CHRISTMAS_TREE(57),
+
+    /**
+     * Specifies an art border consisting of repeating images of lines and
+     * circles
+     */
+    CIRCLES_LINES(58),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a rectangular
+     * pattern
+     */
+    CIRCLES_RECTANGLES(59),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a wave
+     */
+    CLASSICAL_WAVE(60),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a clock
+     */
+    CLOCKS(61),
+
+    /**
+     * Specifies an art border consisting of repeating images of a compass
+     */
+    COMPASS(62),
+
+    /**
+     * Specifies an art border consisting of a repeated image of confetti
+     */
+    CONFETTI(63),
+
+    /**
+     * Specifies an art border consisting of a repeated image of confetti
+     */
+    CONFETTI_GRAYS(64),
+
+    /**
+     * Specifies an art border consisting of a repeated image of confetti
+     */
+    CONFETTI_OUTLINE(65),
+
+    /**
+     * Specifies an art border consisting of a repeated image of confetti
+     * streamers
+     */
+    CONFETTI_STREAMERS(66),
+
+    /**
+     * Specifies an art border consisting of a repeated image of confetti
+     */
+    CONFETTI_WHITE(67),
+
+    /**
+     * Specifies an art border consisting of a repeated image
+     */
+    CORNER_TRIANGLES(68),
+
+    /**
+     * Specifies an art border consisting of a dashed line
+     */
+    COUPON_CUTOUT_DASHES(69),
+
+    /**
+     * Specifies an art border consisting of a dotted line
+     */
+    COUPON_CUTOUT_DOTS(70),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a maze-like
+     * pattern
+     */
+    CRAZY_MAZE(71),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a butterfly
+     */
+    CREATURES_BUTTERFLY(72),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a fish
+     */
+    CREATURES_FISH(73),
+
+    /**
+     * Specifies an art border consisting of repeating images of insects.
+     */
+    CREATURES_INSECTS(74),
+
+    /**
+     * Specifies an art border consisting of a repeated image of a ladybug
+     */
+    CREATURES_LADY_BUG(75),
+
+    /**
+     * Specifies an art border consisting of repeating images of a cross-stitch
+     * pattern
+     */
+    CROSS_STITCH(76),
+
+    /**
+     * Specifies an art border consisting of a repeated image of Cupid
+     */
+    CUP(77),
+
+    DECO_ARCH(78),
+
+    DECO_ARCH_COLOR(79),
+
+    DECO_BLOCKS(80),
+
+    DIAMONDS_GRAY(81),
+
+    DOUBLE_D(82),
+
+    DOUBLE_DIAMONDS(83),
+
+    EARTH_1(84),
+
+    EARTH_2(85),
+
+    ECLIPSING_SQUARES_1(86),
+
+    ECLIPSING_SQUARES_2(87),
+
+    EGGS_BLACK(88),
+
+    FANS(89),
+
+    FILM(90),
+
+    FIRECRACKERS(91),
+
+    FLOWERS_BLOCK_PRINT(92),
+
+    FLOWERS_DAISIES(93),
+
+    FLOWERS_MODERN_1(94),
+
+    FLOWERS_MODERN_2(95),
+
+    FLOWERS_PANSY(96),
+
+    FLOWERS_RED_ROSE(97),
+
+    FLOWERS_ROSES(98),
+
+    FLOWERS_TEACUP(99),
+
+    FLOWERS_TINY(100),
+
+    GEMS(101),
+
+    GINGERBREAD_MAN(102),
+
+    GRADIENT(103),
+
+    HANDMADE_1(104),
+
+    HANDMADE_2(105),
+
+    HEART_BALLOON(106),
+
+    HEART_GRAY(107),
+
+    HEARTS(108),
+
+    HEEBIE_JEEBIES(109),
+
+    HOLLY(110),
+
+    HOUSE_FUNKY(111),
+
+    HYPNOTIC(112),
+
+    ICE_CREAM_CONES(113),
+
+    LIGHT_BULB(114),
+
+    LIGHTNING_1(115),
+
+    LIGHTNING_2(116),
+
+    MAP_PINS(117),
+
+    MAPLE_LEAF(118),
+
+    MAPLE_MUFFINS(119),
+
+    MARQUEE(120),
+
+    MARQUEE_TOOTHED(121),
+
+    MOONS(122),
+
+    MOSAIC(123),
+
+    MUSIC_NOTES(124),
+
+    NORTHWEST(125),
+
+    OVALS(126),
+
+    PACKAGES(127),
+
+    PALMS_BLACK(128),
+
+    PALMS_COLOR(129),
+
+    PAPER_CLIPS(130),
+
+    PAPYRUS(131),
+
+    PARTY_FAVOR(132),
+
+    PARTY_GLASS(133),
+
+    PENCILS(134),
+
+    PEOPLE(135),
+
+    PEOPLE_WAVING(136),
+
+    PEOPLE_HATS(137),
+
+    POINSETTIAS(138),
+
+    POSTAGE_STAMP(139),
+
+    PUMPKIN_1(140),
+
+    PUSH_PIN_NOTE_2(141),
+
+    PUSH_PIN_NOTE_1(142),
+
+    PYRAMIDS(143),
+
+    PYRAMIDS_ABOVE(144),
+
+    QUADRANTS(145),
+
+    RINGS(146),
+
+    SAFARI(147),
+
+    SAWTOOTH(148),
+
+    SAWTOOTH_GRAY(149),
+
+    SCARED_CAT(150),
+
+    SEATTLE(151),
+
+    SHADOWED_SQUARES(152),
+
+    SHARKS_TEETH(153),
+
+    SHOREBIRD_TRACKS(154),
+
+    SKYROCKET(155),
+
+    SNOWFLAKE_FANCY(156),
+
+    SNOWFLAKES(157),
+
+    SOMBRERO(158),
+
+    SOUTHWEST(159),
+
+    STARS(160),
+
+    STARS_TOP(161),
+
+    STARS_3_D(162),
+
+    STARS_BLACK(163),
+
+    STARS_SHADOWED(164),
+
+    SUN(165),
+
+    SWIRLIGIG(166),
+
+    TORN_PAPER(167),
+
+    TORN_PAPER_BLACK(168),
+
+    TREES(169),
+
+    TRIANGLE_PARTY(170),
+
+    TRIANGLES(171),
+
+    TRIBAL_1(172),
+
+    TRIBAL_2(173),
+
+    TRIBAL_3(174),
+
+    TRIBAL_4(175),
+
+    TRIBAL_5(176),
+
+    TRIBAL_6(177),
+
+    TWISTED_LINES_1(178),
+
+    TWISTED_LINES_2(179),
+
+    VINE(180),
+
+    WAVELINE(181),
+
+    WEAVING_ANGLES(182),
+
+    WEAVING_BRAID(183),
+
+    WEAVING_RIBBON(184),
+
+    WEAVING_STRIPS(185),
+
+    WHITE_FLOWERS(186),
+
+    WOODWORK(187),
+
+    X_ILLUSIONS(188),
+
+    ZANY_TRIANGLES(189),
+
+    ZIG_ZAG(190),
+
+    ZIG_ZAG_STITCH(191);
+
+    private final int value;
+
+    private Borders(int val) {
+        value = val;
+    }
+
+    public int getValue() {
+        return value;
+    }
+
+    private static Map<Integer, Borders> imap = new HashMap<Integer, Borders>();
+    static {
+        for (Borders p : values()) {
+            imap.put(new Integer(p.getValue()), p);
+        }
+    }
+
+    public static Borders valueOf(int type) {
+        Borders pBorder = imap.get(new Integer(type));
+        if (pBorder == null) {
+            throw new IllegalArgumentException("Unknown paragraph border: " + type);
+        }
+        return pBorder;
+    }
+}
index 6c8aad1c7fbb510f608f90d9eeb6a1cd8f153ee1..503aeca8e3103a22bcf70f911cf355e7e0fa0a6c 100755 (executable)
@@ -1,65 +1,66 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xwpf.usermodel;\r
-\r
-import java.util.Map;\r
-import java.util.HashMap;\r
-\r
-/**\r
- * Specifies all types of alignment which are available to be applied to objects in a\r
- * WordprocessingML document\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public enum ParagraphAlignment {\r
-    //YK: TODO document each alignment option\r
-\r
-    LEFT(1),\r
-    CENTER(2),\r
-    RIGHT(3),\r
-    BOTH(4),\r
-    MEDIUM_KASHIDA(5),\r
-    DISTRIBUTE(6),\r
-    NUM_TAB(7),\r
-    HIGH_KASHIDA(8),\r
-    LOW_KASHIDA(9),\r
-    THAI_DISTRIBUTE(10);\r
-\r
-    private final int value;\r
-\r
-    private ParagraphAlignment(int val){\r
-        value = val;\r
-    }\r
-\r
-    public int getValue(){\r
-        return value;\r
-    }\r
-\r
-    private static Map<Integer, ParagraphAlignment> imap = new HashMap<Integer, ParagraphAlignment>();\r
-    static{\r
-        for (ParagraphAlignment p : values()) {\r
-            imap.put(p.getValue(), p);\r
-        }\r
-    }\r
-\r
-    public static ParagraphAlignment valueOf(int type){\r
-        ParagraphAlignment err = imap.get(type);\r
-        if(err == null) throw new IllegalArgumentException("Unknown paragraph alignment: " + type);\r
-        return err;\r
-    }\r
-\r
-}\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.xwpf.usermodel;
+
+import java.util.Map;
+import java.util.HashMap;
+
+/**
+ * Specifies all types of alignment which are available to be applied to objects in a
+ * WordprocessingML document
+ *
+ * @author Yegor Kozlov
+ */
+public enum ParagraphAlignment {
+    //YK: TODO document each alignment option
+
+    LEFT(1),
+    CENTER(2),
+    RIGHT(3),
+    BOTH(4),
+    MEDIUM_KASHIDA(5),
+    DISTRIBUTE(6),
+    NUM_TAB(7),
+    HIGH_KASHIDA(8),
+    LOW_KASHIDA(9),
+    THAI_DISTRIBUTE(10);
+
+    private final int value;
+
+    private ParagraphAlignment(int val){
+        value = val;
+    }
+
+    public int getValue(){
+        return value;
+    }
+
+    private static Map<Integer, ParagraphAlignment> imap = new HashMap<Integer, ParagraphAlignment>();
+    static{
+        for (ParagraphAlignment p : values()) {
+            imap.put(p.getValue(), p);
+        }
+    }
+
+    public static ParagraphAlignment valueOf(int type){
+        ParagraphAlignment err = imap.get(type);
+        if(err == null) throw new IllegalArgumentException("Unknown paragraph alignment: " + type);
+        return err;
+    }
+
+}
index 04bf13d113f55b44af992b208b5cd7ef5c789d48..02b18d9a2e027970ba783041cbf716c309a831b8 100755 (executable)
@@ -1,73 +1,74 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xwpf.usermodel;\r
-\r
-import org.apache.poi.POIXMLFactory;\r
-import org.apache.poi.POIXMLDocumentPart;\r
-import org.apache.poi.POIXMLException;\r
-import org.apache.poi.POIXMLRelation;\r
-import org.apache.poi.util.POILogger;\r
-import org.apache.poi.util.POILogFactory;\r
-import org.apache.poi.openxml4j.opc.PackageRelationship;\r
-import org.apache.poi.openxml4j.opc.PackagePart;\r
-\r
-import java.lang.reflect.Constructor;\r
-\r
-/**\r
- * @author Yegor Kozlov\r
- */\r
-public class XWPFFactory extends POIXMLFactory  {\r
-\r
-    private static POILogger logger = POILogFactory.getLogger(XWPFFactory.class);\r
-\r
-    private XWPFFactory(){\r
-\r
-    }\r
-\r
-    private static final XWPFFactory inst = new XWPFFactory();\r
-\r
-    public static XWPFFactory getInstance(){\r
-        return inst;\r
-    }\r
-\r
-    public POIXMLDocumentPart createDocumentPart(PackageRelationship rel, PackagePart part){\r
-        POIXMLRelation descriptor = XWPFRelation.getInstance(rel.getRelationshipType());\r
-        if(descriptor == null || descriptor.getRelationClass() == null){\r
-            logger.log(POILogger.DEBUG, "using default POIXMLDocumentPart for " + rel.getRelationshipType());\r
-            return new POIXMLDocumentPart(part, rel);\r
-        }\r
-\r
-        try {\r
-            Class cls = descriptor.getRelationClass();\r
-            Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(PackagePart.class, PackageRelationship.class);\r
-            return constructor.newInstance(part, rel);\r
-        } catch (Exception e){\r
-            throw new POIXMLException(e);\r
-        }\r
-    }\r
-\r
-    public POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor){\r
-        try {\r
-            Class cls = descriptor.getRelationClass();\r
-            Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor();\r
-            return constructor.newInstance();\r
-        } catch (Exception e){\r
-            throw new POIXMLException(e);\r
-        }\r
-    }\r
-\r
-}\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.xwpf.usermodel;
+
+import org.apache.poi.POIXMLFactory;
+import org.apache.poi.POIXMLDocumentPart;
+import org.apache.poi.POIXMLException;
+import org.apache.poi.POIXMLRelation;
+import org.apache.poi.util.POILogger;
+import org.apache.poi.util.POILogFactory;
+import org.apache.poi.openxml4j.opc.PackageRelationship;
+import org.apache.poi.openxml4j.opc.PackagePart;
+
+import java.lang.reflect.Constructor;
+
+/**
+ * @author Yegor Kozlov
+ */
+public final class XWPFFactory extends POIXMLFactory  {
+
+    private static POILogger logger = POILogFactory.getLogger(XWPFFactory.class);
+
+    private XWPFFactory(){
+
+    }
+
+    private static final XWPFFactory inst = new XWPFFactory();
+
+    public static XWPFFactory getInstance(){
+        return inst;
+    }
+
+    public POIXMLDocumentPart createDocumentPart(PackageRelationship rel, PackagePart part){
+        POIXMLRelation descriptor = XWPFRelation.getInstance(rel.getRelationshipType());
+        if(descriptor == null || descriptor.getRelationClass() == null){
+            logger.log(POILogger.DEBUG, "using default POIXMLDocumentPart for " + rel.getRelationshipType());
+            return new POIXMLDocumentPart(part, rel);
+        }
+
+        try {
+            Class cls = descriptor.getRelationClass();
+            Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(PackagePart.class, PackageRelationship.class);
+            return constructor.newInstance(part, rel);
+        } catch (Exception e){
+            throw new POIXMLException(e);
+        }
+    }
+
+    public POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor){
+        try {
+            Class cls = descriptor.getRelationClass();
+            Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor();
+            return constructor.newInstance();
+        } catch (Exception e){
+            throw new POIXMLException(e);
+        }
+    }
+
+}
index b58db4a75fcdad58dbf1fc74763aa615017e861e..5532ee299fc9ce47ac506fd543d08118b9a9a59f 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.xwpf.usermodel;\r
-\r
-import org.apache.poi.POIXMLRelation;\r
-import org.apache.poi.POIXMLDocumentPart;\r
-\r
-import java.util.Map;\r
-import java.util.HashMap;\r
-\r
-/**\r
- * @author Yegor Kozlov\r
- */\r
-public class XWPFRelation extends POIXMLRelation {\r
-\r
-    /**\r
-     * A map to lookup POIXMLRelation by its relation type\r
-     */\r
-    protected static Map<String, XWPFRelation> _table = new HashMap<String, XWPFRelation>();\r
-\r
-\r
-    public static final XWPFRelation DOCUMENT = new XWPFRelation(\r
-            "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",\r
-            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",\r
-            "/word/document.xml",\r
-            null\r
-    );\r
-    public static final XWPFRelation FONT_TABLE = new XWPFRelation(\r
-            "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml",\r
-            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",\r
-            "/word/fontTable.xml",\r
-            null\r
-    );\r
-    public static final XWPFRelation SETTINGS = new XWPFRelation(\r
-            "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml",\r
-            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",\r
-            "/word/settings.xml",\r
-            null\r
-    );\r
-    public static final XWPFRelation STYLES = new XWPFRelation(\r
-            "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml",\r
-            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",\r
-            "/word/styles.xml",\r
-            null\r
-    );\r
-    public static final XWPFRelation WEB_SETTINGS = new XWPFRelation(\r
-            "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml",\r
-            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings",\r
-            "/word/webSettings.xml",\r
-            null\r
-    );\r
-    public static final XWPFRelation HEADER = new XWPFRelation(\r
-            "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",\r
-            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",\r
-            "/word/header#.xml",\r
-            null\r
-    );\r
-    public static final XWPFRelation FOOTER = new XWPFRelation(\r
-            "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",\r
-            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer",\r
-            "/word/footer#.xml",\r
-            null\r
-    );\r
-    public static final XWPFRelation HYPERLINK = new XWPFRelation(\r
-            null,\r
-            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",\r
-            null,\r
-            null\r
-    );\r
-    public static final XWPFRelation COMMENT = new XWPFRelation(\r
-            null,\r
-            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",\r
-            null,\r
-            null\r
-    );\r
-\r
-\r
-    private XWPFRelation(String type, String rel, String defaultName, Class<? extends POIXMLDocumentPart> cls) {\r
-        super(type, rel, defaultName, cls);\r
-\r
-        if (cls != null && !_table.containsKey(rel)) _table.put(rel, this);\r
-    }\r
-\r
-    /**\r
-     * Get POIXMLRelation by relation type\r
-     *\r
-     * @param rel relation type, for example,\r
-     *            <code>http://schemas.openxmlformats.org/officeDocument/2006/relationships/image</code>\r
-     * @return registered POIXMLRelation or null if not found\r
-     */\r
-    public static XWPFRelation getInstance(String rel) {\r
-        return _table.get(rel);\r
-    }\r
-\r
-}\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.xwpf.usermodel;
+
+import org.apache.poi.POIXMLRelation;
+import org.apache.poi.POIXMLDocumentPart;
+
+import java.util.Map;
+import java.util.HashMap;
+
+/**
+ * @author Yegor Kozlov
+ */
+public final class XWPFRelation extends POIXMLRelation {
+
+    /**
+     * A map to lookup POIXMLRelation by its relation type
+     */
+    protected static Map<String, XWPFRelation> _table = new HashMap<String, XWPFRelation>();
+
+
+    public static final XWPFRelation DOCUMENT = new XWPFRelation(
+            "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
+            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
+            "/word/document.xml",
+            null
+    );
+    public static final XWPFRelation FONT_TABLE = new XWPFRelation(
+            "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml",
+            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",
+            "/word/fontTable.xml",
+            null
+    );
+    public static final XWPFRelation SETTINGS = new XWPFRelation(
+            "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml",
+            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",
+            "/word/settings.xml",
+            null
+    );
+    public static final XWPFRelation STYLES = new XWPFRelation(
+            "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml",
+            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
+            "/word/styles.xml",
+            null
+    );
+    public static final XWPFRelation WEB_SETTINGS = new XWPFRelation(
+            "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml",
+            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings",
+            "/word/webSettings.xml",
+            null
+    );
+    public static final XWPFRelation HEADER = new XWPFRelation(
+            "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
+            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",
+            "/word/header#.xml",
+            null
+    );
+    public static final XWPFRelation FOOTER = new XWPFRelation(
+            "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
+            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer",
+            "/word/footer#.xml",
+            null
+    );
+    public static final XWPFRelation HYPERLINK = new XWPFRelation(
+            null,
+            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
+            null,
+            null
+    );
+    public static final XWPFRelation COMMENT = new XWPFRelation(
+            null,
+            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
+            null,
+            null
+    );
+
+
+    private XWPFRelation(String type, String rel, String defaultName, Class<? extends POIXMLDocumentPart> cls) {
+        super(type, rel, defaultName, cls);
+
+        if (cls != null && !_table.containsKey(rel)) _table.put(rel, this);
+    }
+
+    /**
+     * Get POIXMLRelation by relation type
+     *
+     * @param rel relation type, for example,
+     *            <code>http://schemas.openxmlformats.org/officeDocument/2006/relationships/image</code>
+     * @return registered POIXMLRelation or null if not found
+     */
+    public static XWPFRelation getInstance(String rel) {
+        return _table.get(rel);
+    }
+
+}