incubator-odf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From liud...@apache.org
Subject svn commit: r1424353 [3/3] - in /incubator/odf/trunk: odfdom/src/main/java/org/odftoolkit/odfdom/pkg/ odfdom/src/main/java/org/odftoolkit/odfdom/pkg/manifest/ odfdom/src/test/java/org/odftoolkit/odfdom/doc/ odfdom/src/test/java/org/odftoolkit/odfdom/in...
Date Thu, 20 Dec 2012 07:33:34 GMT
Modified: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfPackageDocument.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfPackageDocument.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfPackageDocument.java (original)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfPackageDocument.java Thu Dec 20 07:33:34 2012
@@ -90,7 +90,6 @@ public class OdfPackageDocument implemen
 	 * used.
 	 */
 	protected OdfPackageDocument(OdfPackage pkg, String internalPath, String mediaTypeString) {
-		super();
 		if (pkg != null) {
 			mPackage = pkg;
 			mDocumentPathInPackage = internalPath;

Modified: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfValidationException.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfValidationException.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfValidationException.java (original)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfValidationException.java Thu Dec 20 07:33:34 2012
@@ -23,7 +23,11 @@ package org.odftoolkit.odfdom.pkg;
 
 import org.xml.sax.SAXParseException;
 
-/** This ODF specific validation excpetion faciliates the usage of a SAXParseException for none XML validation, used by an  <code>ErrorHandler</code>. */
+/**
+ * This ODF specific validation exception facilities the usage of a
+ * SAXParseException for none XML validation, used by an
+ * <code>ErrorHandler</code>.
+ */
 public class OdfValidationException extends SAXParseException {
 
 	private ValidationConstraint mConstraint;
@@ -32,10 +36,15 @@ public class OdfValidationException exte
 	private static final String SOURCE_SUFFIX = "'";
 
 	/**
-	 * An OdfValidationException should be used for any validation result related to an ODF package.
-	 * This constructor should only be used for SaxParseExceptions unrelated to XML.
-	 * This constructor sets the public and system ID for XML and line and column number of the super class will be set to be invalid.
-	@param constraint the predefined constaint message */
+	 * An OdfValidationException should be used for any validation result
+	 * related to an ODF package. This constructor should only be used for
+	 * SaxParseExceptions unrelated to XML. This constructor sets the public and
+	 * system ID for XML and line and column number of the super class will be
+	 * set to be invalid.
+	 * 
+	 * @param constraint
+	 *            the predefined constant message
+	 */
 	public OdfValidationException(ValidationConstraint constraint) {
 		// The constraint convention is the first parameter to be the sourcePath of the ODF document/package causing the exception
 		super(String.format(constraint.getMessage(), NO_SOURCE), null, null, -1, -1);
@@ -43,12 +52,21 @@ public class OdfValidationException exte
 	}
 
 	/**
-	 * An OdfValidationException should be used for any validation result related to an ODF package.
-	 * This constructor should only be used for SaxParseExceptions unrelated to XML.
-	 * This constructor sets the public and system ID for XML and line and column number of the super class will be set to be invalid.
-	@param constraint the predefined constaint message
-	@param sourcePath the source path of the exception. For instance, it might be an ODF package or ODF document.
-	@param messageParameters allow the customization of a constraint message with parameters.*/
+	 * An OdfValidationException should be used for any validation result
+	 * related to an ODF package. This constructor should only be used for
+	 * SaxParseExceptions unrelated to XML. This constructor sets the public and
+	 * system ID for XML and line and column number of the super class will be
+	 * set to be invalid.
+	 * 
+	 * @param constraint
+	 *            the predefined constaint message
+	 * @param sourcePath
+	 *            the source path of the exception. For instance, it might be an
+	 *            ODF package or ODF document.
+	 * @param messageParameters
+	 *            allow the customization of a constraint message with
+	 *            parameters.
+	 */
 	public OdfValidationException(ValidationConstraint constraint, String sourcePath, Object... messageParameters) {
 		// The constraint convention is the first parameter to be the sourcePath of the ODF document/package causing the exception
 		super(formatMessage(constraint, sourcePath, messageParameters), null, null, -1, -1);
@@ -56,13 +74,23 @@ public class OdfValidationException exte
 	}
 
 	/**
-	 * An OdfValidationException should be used for any validation result related to an ODF package.
-	 * This constructor should only be used for SaxParseExceptions unrelated to XML.
-	 * This constructor sets the public and system ID for XML and line and column number of the super class will be set to be invalid.
-	 * @param e root exception to be embeddded
-	 * @param constraint the predefined constaint message
-	 * @param sourcePath the source path of the exception. For instance, it might be an ODF package or ODF document.
-	 * @param messageParameters allow the customization of a constraint message with parameters.*/
+	 * An OdfValidationException should be used for any validation result
+	 * related to an ODF package. This constructor should only be used for
+	 * SaxParseExceptions unrelated to XML. This constructor sets the public and
+	 * system ID for XML and line and column number of the super class will be
+	 * set to be invalid.
+	 * 
+	 * @param e
+	 *            root exception to be embedded
+	 * @param constraint
+	 *            the predefined constant message
+	 * @param sourcePath
+	 *            the source path of the exception. For instance, it might be an
+	 *            ODF package or ODF document.
+	 * @param messageParameters
+	 *            allow the customization of a constraint message with
+	 *            parameters.
+	 */
 	public OdfValidationException(ValidationConstraint constraint, String sourcePath, Exception e, Object... messageParameters) {
 		// The constraint convention is the first parameter to be the sourcePath of the ODF document/package causing the exception
 		super(formatMessage(constraint, sourcePath, messageParameters), null, null, -1, -1, e);

Modified: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfXMLFactory.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfXMLFactory.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfXMLFactory.java (original)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/OdfXMLFactory.java Thu Dec 20 07:33:34 2012
@@ -3,7 +3,7 @@
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
  *
  * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
- *
+ * 
  * Use is subject to license terms.
  *
  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
@@ -135,6 +135,8 @@ public class OdfXMLFactory {
 						localName = stok.nextToken();
 					}
 					className = getOdfIncubatorNodeClassName(prefix, localName);
+				} else if ("manifest".equals(prefix)) {
+					className = getOdfPKGNodeClassName(prefix, localName, nodeType);
 				} else {
 					className = getOdfDOMNodeClassName(prefix, localName, nodeType);
 				}
@@ -176,7 +178,21 @@ public class OdfXMLFactory {
 
 		return className.toString();
 	}
-
+	
+	private static String getOdfPKGNodeClassName(String prefix, String localName, String nodeType) {
+		StringBuilder className = new StringBuilder("org.odftoolkit.odfdom.pkg." + prefix + ".");
+		if (localName.indexOf(LOCAL_NAME_DELIMITER) != -1) {
+			StringTokenizer stok = new StringTokenizer(localName, LOCAL_NAME_DELIMITER);
+			while (stok.hasMoreElements()) {
+				className = className.append(toUpperCaseFirstCharacter(stok.nextToken()));
+			}
+		} else {
+			className = className.append(toUpperCaseFirstCharacter(localName));
+		}
+		className.append(toUpperCaseFirstCharacter(nodeType));
+		return className.toString();
+	}
+	
 	private static String getOdfDOMNodeClassName(String prefix, String localName, String nodeType) {
 		StringBuilder className = new StringBuilder("org.odftoolkit.odfdom.dom." + nodeType + "." + prefix + ".");
 		className = className.append(toUpperCaseFirstCharacter(prefix));

Modified: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/ZipHelper.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/ZipHelper.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/ZipHelper.java (original)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/ZipHelper.java Thu Dec 20 07:33:34 2012
@@ -82,7 +82,8 @@ class ZipHelper {
 						try {
 							zipEntry = inputStream.getNextEntry();
 						} catch (java.util.zip.ZipException e) {
-							// JDK 6 -- the try/catch is workaround for a specific JDK 5 only problem
+							// JDK 6 -- the try/catch is workaround for a
+							// specific JDK 5 only problem
 							if (!e.getMessage().contains("missing entry name") && !System.getProperty("Java.version").equals("1.5.0")) {
 								Logger.getLogger(ZipHelper.class.getName()).info("ZIP ENTRY not found");
 								throw e;
@@ -103,7 +104,8 @@ class ZipHelper {
 			try {
 				int zipMethod = zipEntry.getMethod();
 				if (zipMethod != ZipEntry.STORED && zipMethod != ZipEntry.DEFLATED) {
-					mPackage.getErrorHandler().error(new OdfValidationException(OdfPackageConstraint.PACKAGE_ENTRY_USING_INVALID_COMPRESSION, mPackage.getBaseURI(), filePath));
+					mPackage.getErrorHandler().error(
+							new OdfValidationException(OdfPackageConstraint.PACKAGE_ENTRY_USING_INVALID_COMPRESSION, mPackage.getBaseURI(), filePath));
 				}
 			} catch (SAXException ex) {
 				Logger.getLogger(OdfPackage.class.getName()).log(Level.SEVERE, null, ex);
@@ -116,8 +118,7 @@ class ZipHelper {
 		if (mZipFile != null) {
 			return mZipFile.getInputStream(entry);
 		} else {
-			ZipInputStream inputStream = new ZipInputStream(
-					new ByteArrayInputStream(mZipBuffer));
+			ZipInputStream inputStream = new ZipInputStream(new ByteArrayInputStream(mZipBuffer));
 			ZipEntry zipEntry = inputStream.getNextEntry();
 			while (zipEntry != null) {
 				if (zipEntry.getName().equalsIgnoreCase(entry.getName())) {
@@ -129,8 +130,7 @@ class ZipHelper {
 		}
 	}
 
-	private InputStream readAsInputStream(ZipInputStream inputStream)
-			throws IOException {
+	private InputStream readAsInputStream(ZipInputStream inputStream) throws IOException {
 		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 		if (outputStream != null) {
 			byte[] buf = new byte[4096];

Modified: incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/manifest/OdfFileEntry.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/manifest/OdfFileEntry.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/manifest/OdfFileEntry.java (original)
+++ incubator/odf/trunk/odfdom/src/main/java/org/odftoolkit/odfdom/pkg/manifest/OdfFileEntry.java Thu Dec 20 07:33:34 2012
@@ -25,210 +25,222 @@ import java.lang.reflect.Method;
 import java.util.HashMap;
 import java.util.Map;
 
+import org.odftoolkit.odfdom.pkg.OdfElement;
+
 public class OdfFileEntry {
 
-//    private Logger mLog = Logger.getLogger(OdfFileEntry.class.getName());    
-    private String mPath;
-    private String mMediaType = EMPTY_STRING;
-    private int mSize = -1;
-    private EncryptionData mEncryptionData;    // The following static attributes are used for JDK 5 media type detection
-    private static Map<String, String> MEDIA_TYPE_MAP = null;
+	private FileEntryElement mFileEntryElement;
+
+	private static Map<String, String> MEDIA_TYPE_MAP = null;
 	private static final String EMPTY_STRING = "";
-    private static final String DEFAULT_TYPE = "application/octet-stream";
-    private static final String APPLICATION_POSTSCRIPT = "application/postscript";
-    private static final String APPLICATION_RTF = "application/rtf";
-    private static final String APPLICATION_X_TEX = "application/x-tex";
-    private static final String APPLICATION_X_TEXINFO = "application/x-texinfo";
-    private static final String APPLICATION_X_TROFF = "application/x-troff";
-    private static final String AUDIO_BASIC = "audio/basic";
-    private static final String AUDIO_MIDI = "audio/midi";
-    private static final String AUDIO_X_AIFC = "audio/x-aifc";
-    private static final String AUDIO_X_AIFF = "audio/x-aiff";
-    private static final String AUDIO_X_MPEG = "audio/x-mpeg";
-    private static final String AUDIO_X_WAV = "audio/x-wav";
-    private static final String IMAGE_GIF = "image/gif";
-    private static final String IMAGE_IEF = "image/ief";
-    private static final String IMAGE_JPEG = "image/jpeg";
-    private static final String IMAGE_PNG = "image/png";
-    private static final String IMAGE_TIFF = "image/tiff";
-    private static final String IMAGE_X_XWINDOWDUMP = "image/x-xwindowdump";
-    private static final String TEXT_HTML = "text/html";
-    private static final String TEXT_PLAIN = "text/plain";
-    private static final String TEXT_XML = "text/xml";    
-    private static final String VIDEO_MEPG = "video/mpeg";
-    private static final String VIDEO_QUICKTIME = "video/quicktime";
-    private static final String VIDEO_X_MSVIDEO = "video/x-msvideo";
-
-    public OdfFileEntry() {
-    }
-
-	/**
-	 *  @param path the path of the <manifest:file-entry>
-	 *	Use <code>null</code> for no mediaType */
-    public OdfFileEntry(String path) {
-        mPath = path;
-    }
-
-	/** 
-	 *  @param path the path of the <manifest:file-entry>
-	 *  @param mediaType of the file.
-	 *	Use <code>null</code> for no mediaType */
-    public OdfFileEntry(String path, String mediaType) {
-        mPath = path;
-		if(mediaType == null){
-			mediaType = EMPTY_STRING;
-		}else{
-			mMediaType = mediaType;
+	private static final String DEFAULT_TYPE = "application/octet-stream";
+	private static final String APPLICATION_POSTSCRIPT = "application/postscript";
+	private static final String APPLICATION_RTF = "application/rtf";
+	private static final String APPLICATION_X_TEX = "application/x-tex";
+	private static final String APPLICATION_X_TEXINFO = "application/x-texinfo";
+	private static final String APPLICATION_X_TROFF = "application/x-troff";
+	private static final String AUDIO_BASIC = "audio/basic";
+	private static final String AUDIO_MIDI = "audio/midi";
+	private static final String AUDIO_X_AIFC = "audio/x-aifc";
+	private static final String AUDIO_X_AIFF = "audio/x-aiff";
+	private static final String AUDIO_X_MPEG = "audio/x-mpeg";
+	private static final String AUDIO_X_WAV = "audio/x-wav";
+	private static final String IMAGE_GIF = "image/gif";
+	private static final String IMAGE_IEF = "image/ief";
+	private static final String IMAGE_JPEG = "image/jpeg";
+	private static final String IMAGE_PNG = "image/png";
+	private static final String IMAGE_TIFF = "image/tiff";
+	private static final String IMAGE_X_XWINDOWDUMP = "image/x-xwindowdump";
+	private static final String TEXT_HTML = "text/html";
+	private static final String TEXT_PLAIN = "text/plain";
+	private static final String TEXT_XML = "text/xml";
+	private static final String VIDEO_MEPG = "video/mpeg";
+	private static final String VIDEO_QUICKTIME = "video/quicktime";
+	private static final String VIDEO_X_MSVIDEO = "video/x-msvideo";
+
+	/**
+	 * @param fileEntryElement
+	 *            the OdfElement of the <manifest:file-entry>
+	 */
+	public OdfFileEntry(FileEntryElement fileEntryElement) {
+		mFileEntryElement = fileEntryElement;
+	}
+
+	public void setPath(String path) {
+		mFileEntryElement.setFullPathAttribute(path);
+	}
+
+	public String getPath() {
+		return mFileEntryElement.getFullPathAttribute();
+	}
+
+	/**
+	 * @param mediaType
+	 *            of the file. Use <code>null</code> or an empty string to unset
+	 *            the mediaType to an empty string.
+	 */
+	public void setMediaTypeString(String mediaType) {
+		if (mediaType != null) {
+			mFileEntryElement.setMediaTypeAttribute(mediaType);
+		} else {
+			mFileEntryElement.setMediaTypeAttribute(EMPTY_STRING);
 		}
-    }
+	}
+
+	/**
+	 * @return the mediatype of the mandatory &lt;manifest:file-entry&gt;
+	 *         attribute. If no mediatype exists an empty string is returned
+	 */
+	public String getMediaTypeString() {
+		return mFileEntryElement.getMediaTypeAttribute();
+	}
 
-    public OdfFileEntry(String path, String mediaType, int size) {
-        mPath = path;
-		if(mediaType == null){
-			mediaType = EMPTY_STRING;
-		}else{
-			mMediaType = mediaType;
+	/**
+	 * Get the media type from the given file reference
+	 * 
+	 * @param fileRef
+	 *            the reference to the file the media type is questioned
+	 * 
+	 * @return the mediaType string of the given file reference
+	 */
+	public static String getMediaTypeString(String fileRef) {
+		String mediaType = null;
+		try {
+			// use 'JavaBeans Activation Framework' if available (as library or
+			// as part of JDK 6)
+			Class<?> mimetypesClass = Class.forName("javax.activation.MimetypesFileTypeMap");
+			Method getContentTypeMethod = mimetypesClass.getMethod("getContentType", String.class);
+			mediaType = (String) getContentTypeMethod.invoke(getContentTypeMethod, fileRef);
+		} catch (Exception e) {
+			// otherwise (JDK 5 without library of 'JavaBeans Activation
+			// Framework')
+			// use local fallback implementation
+			// mLog.fine("Using own mediatype handling as 'JavaBeans Activation Framework' not found: "
+			// + e.getMessage());
+			mediaType = findMediaTypeString(fileRef);
 		}
-        mSize = size;
-    }
+		return mediaType;
+	}
 
-    public void setPath(String path) {
-        mPath = path;
-    }
-
-    public String getPath() {
-        return mPath;
-    }
-
-	/** @param mediaType of the file.
-	 *	Use <code>null</code> or an empty string to unset the mediaType to an empty string. */
-    public void setMediaTypeString(String mediaType) {
-		if(mediaType == null){
-			mediaType = EMPTY_STRING;
-		}else{
-			mMediaType = mediaType;
+	public void setSize(Integer size) {
+		if (size == null) {
+			mFileEntryElement.removeAttributeNS(SizeAttribute.ATTRIBUTE_NAME.getUri(),
+					SizeAttribute.ATTRIBUTE_NAME.getLocalName());
+		} else {
+			mFileEntryElement.setSizeAttribute(size);
 		}
-    }
+	}
 
-	/** @return the mediatype of the mandatory &lt;manifest:file-entry&gt; attribute.
-	 *  If no mediatype exists an empty string is returned*/
-    public String getMediaTypeString() {
-        return mMediaType;
-    }
-
-    /**
-     * Get the media type from the given file reference
-     * 
-     * @param fileRef the reference to the file the media type is questioned
-     * 
-     * @return the mediaType string of the given file reference
-     */
-    public static String getMediaTypeString(String fileRef) {
-        String mediaType = null;
-        try {
-            // use 'JavaBeans Activation Framework' if available (as library or as part of JDK 6)
-            Class<?> mimetypesClass = Class.forName("javax.activation.MimetypesFileTypeMap");
-            Method getContentTypeMethod = mimetypesClass.getMethod("getContentType", String.class);
-            mediaType = (String) getContentTypeMethod.invoke(getContentTypeMethod, fileRef);
-        } catch (Exception e) {
-            // otherwise (JDK 5 without library of 'JavaBeans Activation Framework')
-            // use local fallback implementation
-//          mLog.fine("Using own mediatype handling as 'JavaBeans Activation Framework' not found: " +  e.getMessage());
-            mediaType = findMediaTypeString(fileRef);
-        }
-        return mediaType;
-    }
-
-    /** Own mediatype functionality which can be removed as soon JDK 6 is base line */
-    private static String findMediaTypeString(String fileRef) {
-        String fileSuffix = null;
-        String mediaType = null;
-
-        int suffixStart = fileRef.lastIndexOf(".");
-        // default mediatype, if no dot exists        
-        if (suffixStart < 0) {
-            mediaType = DEFAULT_TYPE;
-        } else {
-            fileSuffix = fileRef.substring(suffixStart + 1);
-            // default mediattype, if the file ends with a dot, the suffix is empty
-            if (fileSuffix.length() == 0) {
-                mediaType = DEFAULT_TYPE;
-            } else {
-                if (MEDIA_TYPE_MAP == null) {
-                    initializeMediaTypeMap();
-                }
-                mediaType = MEDIA_TYPE_MAP.get(fileSuffix.toLowerCase());
-                // default mediatype, if no mediatype for this suffix exists
-                if (mediaType == null) {
-                    mediaType = DEFAULT_TYPE;
-                }
-            }
-        }
-        return mediaType;
-    }
-    // initializes Map for suffix to media type string mapping
-    private static void initializeMediaTypeMap() {
-        MEDIA_TYPE_MAP = new HashMap<String, String>(39);
-        MEDIA_TYPE_MAP.put("ai", APPLICATION_POSTSCRIPT);
-        MEDIA_TYPE_MAP.put("eps", APPLICATION_POSTSCRIPT);
-        MEDIA_TYPE_MAP.put("ps", APPLICATION_POSTSCRIPT);
-        MEDIA_TYPE_MAP.put("rtf", APPLICATION_RTF);
-        MEDIA_TYPE_MAP.put("tex", APPLICATION_X_TEX);
-        MEDIA_TYPE_MAP.put("texi", APPLICATION_X_TEXINFO);
-        MEDIA_TYPE_MAP.put("texinfo", APPLICATION_X_TEXINFO);
-        MEDIA_TYPE_MAP.put("t", APPLICATION_X_TROFF);
-        MEDIA_TYPE_MAP.put("tr", APPLICATION_X_TROFF);
-        MEDIA_TYPE_MAP.put("roff", APPLICATION_X_TROFF);
-        MEDIA_TYPE_MAP.put("au", AUDIO_BASIC);
-        MEDIA_TYPE_MAP.put("midi", AUDIO_MIDI);
-        MEDIA_TYPE_MAP.put("mid", AUDIO_MIDI);
-        MEDIA_TYPE_MAP.put("aifc", AUDIO_X_AIFC);
-        MEDIA_TYPE_MAP.put("aif", AUDIO_X_AIFF);
-        MEDIA_TYPE_MAP.put("aiff", AUDIO_X_AIFF);
-        MEDIA_TYPE_MAP.put("mpeg", AUDIO_X_MPEG);
-        MEDIA_TYPE_MAP.put("mpg", AUDIO_X_MPEG);
-        MEDIA_TYPE_MAP.put("wav", AUDIO_X_WAV);
-        MEDIA_TYPE_MAP.put("gif", IMAGE_GIF);
-        MEDIA_TYPE_MAP.put("ief", IMAGE_IEF);
-        MEDIA_TYPE_MAP.put("jpeg", IMAGE_JPEG);
-        MEDIA_TYPE_MAP.put("jpg", IMAGE_JPEG);
-        MEDIA_TYPE_MAP.put("jpe", IMAGE_JPEG);
-        MEDIA_TYPE_MAP.put("png", IMAGE_PNG);
-        MEDIA_TYPE_MAP.put("tiff", IMAGE_TIFF);
-        MEDIA_TYPE_MAP.put("tif", IMAGE_TIFF);
-        MEDIA_TYPE_MAP.put("xwd", IMAGE_X_XWINDOWDUMP);
-        MEDIA_TYPE_MAP.put("html", TEXT_HTML);
-        MEDIA_TYPE_MAP.put("htm", TEXT_HTML);
-        MEDIA_TYPE_MAP.put("xhtml", TEXT_HTML);
-        MEDIA_TYPE_MAP.put("txt", TEXT_PLAIN);
-        MEDIA_TYPE_MAP.put("text", TEXT_PLAIN);
-        MEDIA_TYPE_MAP.put("xml", TEXT_XML);        
-        MEDIA_TYPE_MAP.put("mpeg", VIDEO_MEPG);
-        MEDIA_TYPE_MAP.put("mpg", VIDEO_MEPG);
-        MEDIA_TYPE_MAP.put("mpe", VIDEO_MEPG);
-        MEDIA_TYPE_MAP.put("qt", VIDEO_QUICKTIME);
-        MEDIA_TYPE_MAP.put("mov", VIDEO_QUICKTIME);
-        MEDIA_TYPE_MAP.put("avi", VIDEO_X_MSVIDEO);
-    }
-
-    public void setSize(int size) {
-        mSize = size;
-    }
-
-    /**
-     * get the size or -1 if not set
-     */
-    public int getSize() {
-        return mSize;
-    }
-
-    public void setEncryptionData(EncryptionData encryptionData) {
-        mEncryptionData = encryptionData;
-    }
+	/**
+	 * Get the size.
+	 */
+	public Integer getSize() {
+		return mFileEntryElement.getSizeAttribute();
+	}
+
+	public void setEncryptionData(EncryptionDataElement encryptionData) {
+		EncryptionDataElement encryptionDataEle = getEncryptionData();
+		if (encryptionData != null) {
+			if (encryptionDataEle != null) {
+				mFileEntryElement.replaceChild(encryptionData, encryptionDataEle);
+			} else {
+				mFileEntryElement.appendChild(encryptionData);
+			}
+		} else {
+			if (encryptionDataEle != null) {
+				mFileEntryElement.removeChild(encryptionDataEle);
+			}
+		}
+	}
 
 	/** @return null if no encryption data had been set */
-    public EncryptionData getEncryptionData() {
-        return mEncryptionData;
-    }
-}
+	public EncryptionDataElement getEncryptionData() {
+		return OdfElement.findFirstChildNode(EncryptionDataElement.class, mFileEntryElement);
+	}
+
+	/**
+	 * Gets the OdfElement of this OdfFileEntry.
+	 * 
+	 * @return the OdfElement of this OdfFileEntry.
+	 */
+	public FileEntryElement getOdfElement() {
+		return mFileEntryElement;
+	}
 
+	/**
+	 * Own mediatype functionality which can be removed as soon JDK 6 is base
+	 * line
+	 */
+	private static String findMediaTypeString(String fileRef) {
+		String fileSuffix = null;
+		String mediaType = null;
+
+		int suffixStart = fileRef.lastIndexOf(".");
+		// default mediatype, if no dot exists
+		if (suffixStart < 0) {
+			mediaType = DEFAULT_TYPE;
+		} else {
+			fileSuffix = fileRef.substring(suffixStart + 1);
+			// default mediattype, if the file ends with a dot, the suffix is
+			// empty
+			if (fileSuffix.length() == 0) {
+				mediaType = DEFAULT_TYPE;
+			} else {
+				if (MEDIA_TYPE_MAP == null) {
+					initializeMediaTypeMap();
+				}
+				mediaType = MEDIA_TYPE_MAP.get(fileSuffix.toLowerCase());
+				// default mediatype, if no mediatype for this suffix exists
+				if (mediaType == null) {
+					mediaType = DEFAULT_TYPE;
+				}
+			}
+		}
+		return mediaType;
+	}
+
+	// initializes Map for suffix to media type string mapping
+	private static void initializeMediaTypeMap() {
+		MEDIA_TYPE_MAP = new HashMap<String, String>(39);
+		MEDIA_TYPE_MAP.put("ai", APPLICATION_POSTSCRIPT);
+		MEDIA_TYPE_MAP.put("eps", APPLICATION_POSTSCRIPT);
+		MEDIA_TYPE_MAP.put("ps", APPLICATION_POSTSCRIPT);
+		MEDIA_TYPE_MAP.put("rtf", APPLICATION_RTF);
+		MEDIA_TYPE_MAP.put("tex", APPLICATION_X_TEX);
+		MEDIA_TYPE_MAP.put("texi", APPLICATION_X_TEXINFO);
+		MEDIA_TYPE_MAP.put("texinfo", APPLICATION_X_TEXINFO);
+		MEDIA_TYPE_MAP.put("t", APPLICATION_X_TROFF);
+		MEDIA_TYPE_MAP.put("tr", APPLICATION_X_TROFF);
+		MEDIA_TYPE_MAP.put("roff", APPLICATION_X_TROFF);
+		MEDIA_TYPE_MAP.put("au", AUDIO_BASIC);
+		MEDIA_TYPE_MAP.put("midi", AUDIO_MIDI);
+		MEDIA_TYPE_MAP.put("mid", AUDIO_MIDI);
+		MEDIA_TYPE_MAP.put("aifc", AUDIO_X_AIFC);
+		MEDIA_TYPE_MAP.put("aif", AUDIO_X_AIFF);
+		MEDIA_TYPE_MAP.put("aiff", AUDIO_X_AIFF);
+		MEDIA_TYPE_MAP.put("mpeg", AUDIO_X_MPEG);
+		MEDIA_TYPE_MAP.put("mpg", AUDIO_X_MPEG);
+		MEDIA_TYPE_MAP.put("wav", AUDIO_X_WAV);
+		MEDIA_TYPE_MAP.put("gif", IMAGE_GIF);
+		MEDIA_TYPE_MAP.put("ief", IMAGE_IEF);
+		MEDIA_TYPE_MAP.put("jpeg", IMAGE_JPEG);
+		MEDIA_TYPE_MAP.put("jpg", IMAGE_JPEG);
+		MEDIA_TYPE_MAP.put("jpe", IMAGE_JPEG);
+		MEDIA_TYPE_MAP.put("png", IMAGE_PNG);
+		MEDIA_TYPE_MAP.put("tiff", IMAGE_TIFF);
+		MEDIA_TYPE_MAP.put("tif", IMAGE_TIFF);
+		MEDIA_TYPE_MAP.put("xwd", IMAGE_X_XWINDOWDUMP);
+		MEDIA_TYPE_MAP.put("html", TEXT_HTML);
+		MEDIA_TYPE_MAP.put("htm", TEXT_HTML);
+		MEDIA_TYPE_MAP.put("xhtml", TEXT_HTML);
+		MEDIA_TYPE_MAP.put("txt", TEXT_PLAIN);
+		MEDIA_TYPE_MAP.put("text", TEXT_PLAIN);
+		MEDIA_TYPE_MAP.put("xml", TEXT_XML);
+		MEDIA_TYPE_MAP.put("mpeg", VIDEO_MEPG);
+		MEDIA_TYPE_MAP.put("mpg", VIDEO_MEPG);
+		MEDIA_TYPE_MAP.put("mpe", VIDEO_MEPG);
+		MEDIA_TYPE_MAP.put("qt", VIDEO_QUICKTIME);
+		MEDIA_TYPE_MAP.put("mov", VIDEO_QUICKTIME);
+		MEDIA_TYPE_MAP.put("avi", VIDEO_X_MSVIDEO);
+	}
+}

Modified: incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/doc/DocumentTest.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/doc/DocumentTest.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/doc/DocumentTest.java (original)
+++ incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/doc/DocumentTest.java Thu Dec 20 07:33:34 2012
@@ -428,7 +428,7 @@ public class DocumentTest {
 		return stringBuilder.toString();
 	}
 
-	/** Saves the datastring as UTF8 to the given filePath */
+	/** Saves the data string as UTF8 to the given filePath */
 	private static void saveString(String dataString, String filePath) throws UnsupportedEncodingException, IOException {
 		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF8"));
 		out.append(dataString);
@@ -485,12 +485,12 @@ public class DocumentTest {
 		handler1.setTestFilePath("testInvalidPkg1.odt");
 		try {
 			// First Test / Handler2
-			OdfPackage pkg2 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler2.getTestFilePath())), handler2);
+			OdfPackage pkg2 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler2.getTestFilePath())), null, handler2);
 			OdfDocument doc2 = OdfDocument.loadDocument(pkg2);
 			Assert.assertNotNull(doc2);
 
 			// Second Test / Handler3
-			OdfPackage pkg3 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler3.getTestFilePath())), handler3);
+			OdfPackage pkg3 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler3.getTestFilePath())), null, handler3);
 			OdfDocument doc3 = OdfDocument.loadDocument(pkg3);
 			Assert.assertNotNull(doc3);
 			Map subDocs = doc3.loadSubDocuments();
@@ -498,7 +498,7 @@ public class DocumentTest {
 			Assert.assertEquals(PRESENTATION1_DOC_COUNT, subDocs.size());
 
 			// Third Test / Handler1
-			OdfPackage pkg1 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler1.getTestFilePath())), handler1);
+			OdfPackage pkg1 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler1.getTestFilePath())), null, handler1);
 			OdfDocument.loadDocument(pkg1);
 			Assert.fail();
 		} catch (Exception e) {

Modified: incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/incubator/meta/OfficeMetaTest.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/incubator/meta/OfficeMetaTest.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/incubator/meta/OfficeMetaTest.java (original)
+++ incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/incubator/meta/OfficeMetaTest.java Thu Dec 20 07:33:34 2012
@@ -71,9 +71,12 @@ public class OfficeMetaTest {
 
 	@After
 	public void tearDown() throws Exception {
+//		Thread.sleep(100);
 		doc.save(ResourceUtilities.getAbsolutePath(filename));
+		doc.close();
 		doc = null;
 		metadom = null;
+//		Thread.sleep(100);
 	}
 
 	@Test

Modified: incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/pkg/PackageTest.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/pkg/PackageTest.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/pkg/PackageTest.java (original)
+++ incubator/odf/trunk/odfdom/src/test/java/org/odftoolkit/odfdom/pkg/PackageTest.java Thu Dec 20 07:33:34 2012
@@ -60,15 +60,16 @@ import org.xml.sax.SAXException;
 import org.xml.sax.helpers.DefaultHandler;
 
 public class PackageTest {
-
+	
 	private static final Logger LOG = Logger.getLogger(PackageTest.class.getName());
 	private static final String mImagePath = "src/main/javadoc/doc-files/";
 	private static final String mImageName = "ODFDOM-Layered-Model.png";
 	private static final String mImageMediaType = "image/png";
 	private static final String XSL_CONCAT = "xslt/concatfiles.xsl";
 	private static final String XSL_OUTPUT = "ResolverTest.html";
-	//ToDo: Package Structure for test output possbile?
-	//private static final String XSL_OUTPUT ="pkg" + File.separator + "ResolverTest.html";
+	// ToDo: Package Structure for test output possbile?
+	// private static final String XSL_OUTPUT ="pkg" + File.separator +
+	// "ResolverTest.html";
 	private static final String SIMPLE_ODT = "test2.odt";
 	private static final String ODF_FORMULAR_TEST_FILE = "SimpleFormula.odf";
 	private static final String IMAGE_TEST_FILE = "testA.jpg";
@@ -76,13 +77,13 @@ public class PackageTest {
 	private static final String TARGET_STEP_1 = "PackageLoadTestStep1.ods";
 	private static final String TARGET_STEP_2 = "PackageLoadTestStep2.ods";
 	private static final String TARGET_STEP_3 = "PackageLoadTestStep3.ods";
-
+	
 	public PackageTest() {
 	}
-
+	
 	@Test
 	public void testNotCompressImages() throws Exception {
-		//create test presentation
+		// create test presentation
 		OdfPresentationDocument odp = OdfPresentationDocument.newPresentationDocument();
 		OfficePresentationElement officePresentation = odp.getContentRoot();
 		DrawPageElement page = officePresentation.newDrawPageElement(null);
@@ -90,8 +91,8 @@ public class PackageTest {
 		OdfDrawImage image = (OdfDrawImage) frame.newDrawImageElement();
 		image.newImage(ResourceUtilities.getURI(IMAGE_TEST_FILE));
 		odp.save(ResourceUtilities.newTestOutputFile(IMAGE_PRESENTATION));
-
-		//test if the image is not compressed
+		
+		// test if the image is not compressed
 		ZipInputStream zinput = new ZipInputStream(ResourceUtilities.getTestResourceAsStream(IMAGE_PRESENTATION));
 		ZipEntry entry = zinput.getNextEntry();
 		while (entry != null) {
@@ -104,16 +105,16 @@ public class PackageTest {
 			entry = zinput.getNextEntry();
 		}
 	}
-
+	
 	@Test
 	public void loadPackage() {
 		try {
-
+			
 			// LOAD PACKAGE FORMULA
 			LOG.info("Loading an unsupported ODF Formula document as an ODF Package!");
 			OdfPackage formulaPackage = OdfPackage.loadPackage(ResourceUtilities.getAbsolutePath(ODF_FORMULAR_TEST_FILE));
 			Assert.assertNotNull(formulaPackage);
-
+			
 			// LOAD PACKAGE IMAGE
 			LOG.info("Loading an unsupported image file as an ODF Package!");
 			try {
@@ -127,12 +128,12 @@ public class PackageTest {
 					Assert.fail();
 				}
 			}
-
+			
 			// LOAD PACKAGE IMAGE (WITH ERROR HANDLER)
 			LOG.info("Loading an unsupported image file as an ODF Package (with error handler)!");
 			try {
 				// Exception is expected by error handler!
-				OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(IMAGE_TEST_FILE)), new DefaultHandler());
+				OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(IMAGE_TEST_FILE)), null, new DefaultHandler());
 				Assert.fail();
 			} catch (SAXException e) {
 				String errorMsg = OdfPackageConstraint.PACKAGE_IS_NO_ZIP.getMessage();
@@ -146,7 +147,7 @@ public class PackageTest {
 			Assert.fail(e.getMessage());
 		}
 	}
-
+	
 	@Test
 	public void testPackage() {
 		File tmpFile1 = ResourceUtilities.newTestOutputFile(TARGET_STEP_1);
@@ -161,18 +162,18 @@ public class PackageTest {
 			LOG.log(Level.SEVERE, mImagePath, ex);
 			Assert.fail();
 		}
-
+		
 		long lengthBefore = tmpFile1.length();
 		try {
 			// not allowed to change the document simply by open and save
 			OdfPackage odfPackage = OdfPackage.loadPackage(tmpFile1);
-
+			
 			URI imageURI = new URI(mImagePath + mImageName);
 			// testing encoded none ASCII in URL path
 			String pkgRef1 = AnyURI.encodePath("Pictures/a&b.jpg");
 			LOG.log(Level.INFO, "Attempt to write graphic to package path: {0}", pkgRef1);
 			odfPackage.insert(uri2ByteArray(imageURI), pkgRef1, mImageMediaType);
-
+			
 			// testing allowed none-ASCII in URL path (see rfc1808.txt)
 			String pkgRef2 = "Pictures/a&%" + "\u00ea" + "\u00f1" + "\u00fc" + "b.jpg";
 			LOG.log(Level.INFO, "Attempt to write graphic to package path: {0}", pkgRef2);
@@ -187,16 +188,16 @@ public class PackageTest {
 			odfPackage.save(tmpFile3);
 			long lengthAfter3 = tmpFile3.length();
 			odfPackage.close();
-
+			
 			// the package without the images should be as long as before
 			Assert.assertTrue("The files \n\t" + tmpFile1.getAbsolutePath() + " and \n\t" + tmpFile3.getAbsolutePath() + " differ!", lengthBefore == lengthAfter3);
-
+			
 		} catch (Exception ex) {
 			LOG.log(Level.SEVERE, mImagePath, ex);
 			Assert.fail();
 		}
 	}
-
+	
 	private static byte[] uri2ByteArray(URI uri) {
 		byte[] fileBytes = null;
 		try {
@@ -207,7 +208,8 @@ public class PackageTest {
 			} else {
 				// otherwise create a file class to open the transformStream
 				fileStream = new FileInputStream(uri.toString());
-				// TODO: error handling in this case! -> allow method insert(URI, ppath, mtype)?
+				// TODO: error handling in this case! -> allow method
+				// insert(URI, ppath, mtype)?
 			}
 			ByteArrayOutputStream baos = new ByteArrayOutputStream();
 			BufferedInputStream bis = new BufferedInputStream(fileStream);
@@ -220,8 +222,11 @@ public class PackageTest {
 		}
 		return fileBytes;
 	}
-
-	/** Testing the XML helper and the OdfPackage to handle two files at the same time (have them open) */
+	
+	/**
+	 * Testing the XML helper and the OdfPackage to handle two files at the same
+	 * time (have them open)
+	 */
 	@Test
 	public void testResolverWithXSLT() {
 		try {
@@ -242,9 +247,9 @@ public class PackageTest {
 			Logger.getLogger(PackageTest.class.getName()).log(Level.SEVERE, t.getMessage(), t);
 			Assert.fail();
 		}
-
+		
 	}
-
+	
 	@Test
 	public void validationTestDefault() {
 		try {
@@ -255,43 +260,48 @@ public class PackageTest {
 			LOG.log(Level.SEVERE, null, ex);
 			Assert.fail();
 		}
-
+		
 		// default no error handler: fatal errors are reported
 		try {
 			OdfPackage.loadPackage(ResourceUtilities.getAbsolutePath("testA.jpg"));
 			Assert.fail();
-                } catch (Exception e) {
+		} catch (Exception e) {
 			String errorMsg = OdfPackageConstraint.PACKAGE_IS_NO_ZIP.getMessage();
 			if (!e.getMessage().endsWith(errorMsg.substring(errorMsg.indexOf("%1$s") + 4))) {
 				Assert.fail();
 			}
 		}
 	}
-        
-        @Test
-        public void loadPackageWithoutManifest() throws Exception {
-            // regression for ODFTOOLKIT-327: invalid package without errorhandler
-            // doesn't throw NPE
-            ByteArrayOutputStream out = new ByteArrayOutputStream();
-            ZipOutputStream zipped = new ZipOutputStream(out);
-            ZipEntry entry = new ZipEntry("someentry");
-            zipped.putNextEntry(entry);
-            zipped.close();
-            
-            byte [] data = out.toByteArray();
-            ByteArrayInputStream in = new ByteArrayInputStream(data);
-            OdfPackage pkg = OdfPackage.loadPackage(in);
-            
-            Assert.assertNotNull(pkg);
-        }
-
+	
+	@Test
+	public void loadPackageWithoutManifest() {
+		try {
+			// regression for ODFTOOLKIT-327: invalid package without
+			// errorhandler
+			// doesn't throw NPE
+			ByteArrayOutputStream out = new ByteArrayOutputStream();
+			ZipOutputStream zipped = new ZipOutputStream(out);
+			ZipEntry entry = new ZipEntry("someentry");
+			zipped.putNextEntry(entry);
+			zipped.close();
+			
+			byte[] data = out.toByteArray();
+			ByteArrayInputStream in = new ByteArrayInputStream(data);
+			OdfPackage pkg = OdfPackage.loadPackage(in);
+			Assert.assertNotNull(pkg);
+		} catch (Exception ex) {
+			LOG.log(Level.SEVERE, null, ex);
+			Assert.fail();
+		}
+	}
+	
 	@Test
 	public void validationTest() {
-
+		
 		// TESTDOC1: Expected ODF Warnings
 		Map expectedWarning1 = new HashMap();
 		expectedWarning1.put(OdfPackageConstraint.MANIFEST_LISTS_DIRECTORY, 10);
-
+		
 		// TESTDOC1: Expected ODF Errors
 		Map expectedErrors1 = new HashMap();
 		expectedErrors1.put(OdfPackageConstraint.MIMETYPE_NOT_FIRST_IN_PACKAGE, 1);
@@ -301,21 +311,19 @@ public class PackageTest {
 		expectedErrors1.put(OdfPackageConstraint.MANIFEST_LISTS_NONEXISTENT_FILE, 1);
 		ErrorHandlerStub handler1 = new ErrorHandlerStub(expectedWarning1, expectedErrors1, null);
 		handler1.setTestFilePath("testInvalidPkg1.odt");
-
-
+		
 		// TESTDOC2: Expected ODF Warnings
 		Map expectedWarning2 = new HashMap();
 		expectedWarning2.put(OdfPackageConstraint.MIMETYPE_NOT_IN_PACKAGE, 1);
 		expectedWarning2.put(OdfPackageConstraint.MANIFEST_LISTS_DIRECTORY, 10);
-
+		
 		// TESTDOC2: Expected ODF Errors
 		Map expectedErrors2 = new HashMap();
 		expectedErrors2.put(OdfPackageConstraint.MANIFEST_DOES_NOT_LIST_FILE, 1);
 		expectedErrors2.put(OdfPackageConstraint.MANIFEST_LISTS_NONEXISTENT_FILE, 3);
 		ErrorHandlerStub handler2 = new ErrorHandlerStub(expectedWarning2, expectedErrors2, null);
 		handler2.setTestFilePath("testInvalidPkg2.odt");
-
-
+		
 		// TESTDOC3 DESCRIPTION - only mimetype file in package
 		// TESTDOC3: Expected ODF Errors
 		Map expectedErrors3 = new HashMap();
@@ -323,23 +331,22 @@ public class PackageTest {
 		expectedErrors3.put(OdfPackageConstraint.MIMETYPE_WITHOUT_MANIFEST_MEDIATYPE, 1);
 		ErrorHandlerStub handler3 = new ErrorHandlerStub(null, expectedErrors3, null);
 		handler3.setTestFilePath("testInvalidPkg3.odt");
-
-
+		
 		// TESTDOC4: Expected ODF FatalErrors
 		Map<ValidationConstraint, Integer> expectedFatalErrors4 = new HashMap<ValidationConstraint, Integer>();
 		// loading a graphic instead an ODF document
 		expectedFatalErrors4.put(OdfPackageConstraint.PACKAGE_IS_NO_ZIP, 1);
 		ErrorHandlerStub handler4 = new ErrorHandlerStub(null, null, expectedFatalErrors4);
-
+		
 		try {
-			OdfPackage pkg1 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler1.getTestFilePath())), handler1);
+			OdfPackage pkg1 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler1.getTestFilePath())), null, handler1);
 			Assert.assertNotNull(pkg1);
-			OdfPackage pkg2 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler2.getTestFilePath())), handler2);
+			OdfPackage pkg2 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler2.getTestFilePath())), null, handler2);
 			Assert.assertNotNull(pkg2);
-			OdfPackage pkg3 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler3.getTestFilePath())), handler3);
+			OdfPackage pkg3 = OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath(handler3.getTestFilePath())), null, handler3);
 			Assert.assertNotNull(pkg3);
 			try {
-				OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath("testA.jpg")), handler4);
+				OdfPackage.loadPackage(new File(ResourceUtilities.getAbsolutePath("testA.jpg")), null, handler4);
 				Assert.fail();
 			} catch (Exception e) {
 				String errorMsg = OdfPackageConstraint.PACKAGE_IS_NO_ZIP.getMessage();
@@ -356,4 +363,22 @@ public class PackageTest {
 		handler3.validate();
 		handler4.validate();
 	}
-}    
+	
+	@Test
+	public void testPackagePassword() {
+		File tmpFile = ResourceUtilities.newTestOutputFile("PackagePassword.ods");
+		OdfDocument doc = null;
+		try {
+			doc = OdfSpreadsheetDocument.newSpreadsheetDocument();
+			doc.getPackage().setPassword("password");
+			doc.save(tmpFile);
+			doc.close();
+			OdfPackage odfPackage = OdfPackage.loadPackage(tmpFile, "password", null);
+			byte[] contentBytes = odfPackage.getBytes("content.xml");
+			Assert.assertNotNull(contentBytes);
+		} catch (Exception ex) {
+			LOG.log(Level.SEVERE, "password test failed.", ex);
+			Assert.fail();
+		}
+	}
+}

Modified: incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/Document.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/Document.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/Document.java (original)
+++ incubator/odf/trunk/simple/src/main/java/org/odftoolkit/simple/Document.java Thu Dec 20 07:33:34 2012
@@ -113,9 +113,9 @@ public abstract class Document extends O
 	private TableContainerImpl tableContainerImpl;
 	private static final Pattern CONTROL_CHAR_PATTERN = Pattern.compile("\\p{Cntrl}");
 	private static final String EMPTY_STRING = "";
-	
+
 	private IdentityHashMap<OdfElement, Component> mComponentRepository = new IdentityHashMap<OdfElement, Component>();
-	
+
 	// FIXME: This field is only used in method copyResourcesFrom to improve
 	// copy performance, should not be used in any other way.
 	// methods loadDocument(String documentPath) and loadDocument(File file)
@@ -166,11 +166,11 @@ public abstract class Document extends O
 		IMAGE("application/vnd.oasis.opendocument.image", "odi"), 
 		IMAGE_TEMPLATE("application/vnd.oasis.opendocument.image-template", "oti"), 
 		PRESENTATION("application/vnd.oasis.opendocument.presentation", "odp"), 
-		PRESENTATION_TEMPLATE("application/vnd.oasis.opendocument.presentation-template", "otp"),
+		PRESENTATION_TEMPLATE("application/vnd.oasis.opendocument.presentation-template", "otp"), 
 		SPREADSHEET("application/vnd.oasis.opendocument.spreadsheet", "ods"), 
 		SPREADSHEET_TEMPLATE("application/vnd.oasis.opendocument.spreadsheet-template", "ots"), 
 		TEXT("application/vnd.oasis.opendocument.text", "odt"), 
-		TEXT_MASTER("application/vnd.oasis.opendocument.text-master", "odm"),
+		TEXT_MASTER("application/vnd.oasis.opendocument.text-master", "odm"), 
 		TEXT_TEMPLATE("application/vnd.oasis.opendocument.text-template", "ott"), 
 		TEXT_WEB("application/vnd.oasis.opendocument.text-web", "oth");
 
@@ -250,7 +250,30 @@ public abstract class Document extends O
 	 * 
 	 * <p>
 	 * Document relies on the file being available for read access over the
-	 * whole lifecycle of Document.
+	 * whole life cycle of Document.
+	 * </p>
+	 * 
+	 * @param documentPath
+	 *            - the path from where the document can be loaded
+	 * @param password
+	 *            - file password.
+	 * @return the Document from the given path or NULL if the media type is not
+	 *         supported by SIMPLE.
+	 * @throws java.lang.Exception
+	 *             - if the document could not be created.
+	 * @since 0.8
+	 */
+	public static Document loadDocument(String documentPath, String password) throws Exception {
+		File file = new File(documentPath);
+		return loadDocument(file, password);
+	}
+
+	/**
+	 * Loads a Document from the provided path.
+	 * 
+	 * <p>
+	 * Document relies on the file being available for read access over the
+	 * whole life cycle of Document.
 	 * </p>
 	 * 
 	 * @param documentPath
@@ -262,9 +285,7 @@ public abstract class Document extends O
 	 */
 	public static Document loadDocument(String documentPath) throws Exception {
 		File file = new File(documentPath);
-		Document doc = loadDocument(OdfPackage.loadPackage(documentPath));
-		doc.setFile(file);
-		return doc;
+		return loadDocument(file);
 	}
 
 	/**
@@ -309,6 +330,29 @@ public abstract class Document extends O
 	}
 
 	/**
+	 * Creates a Document from the Document provided by a File.
+	 * 
+	 * <p>
+	 * Document relies on the file being available for read access over the
+	 * whole lifecycle of Document.
+	 * </p>
+	 * 
+	 * @param file
+	 *            - a file representing the ODF document.
+	 * @param password
+	 *            - file password.
+	 * @return the document created from the given File
+	 * @throws java.lang.Exception
+	 *             - if the document could not be created.
+	 * @since 0.7
+	 */
+	public static Document loadDocument(File file, String password) throws Exception {
+		Document doc = loadDocument(OdfPackage.loadPackage(file, password, null));
+		doc.setFile(file);
+		return doc;
+	}
+
+	/**
 	 * Creates a Document from the Document provided by an ODF package.
 	 * 
 	 * @param odfPackage
@@ -335,8 +379,7 @@ public abstract class Document extends O
 	public static Document loadDocument(OdfPackage odfPackage, String internalPath) throws Exception {
 		String documentMediaType = odfPackage.getMediaTypeString(internalPath);
 		if (documentMediaType == null) {
-			throw new IllegalArgumentException("Given internalPath '" + internalPath
-					+ "' is an illegal or inappropriate argument.");
+			throw new IllegalArgumentException("Given internalPath '" + internalPath + "' is an illegal or inappropriate argument.");
 		}
 		OdfMediaType odfMediaType = OdfMediaType.getOdfMediaType(documentMediaType);
 		if (odfMediaType == null) {
@@ -345,8 +388,7 @@ public abstract class Document extends O
 			if (matcherCTRL.find()) {
 				documentMediaType = matcherCTRL.replaceAll(EMPTY_STRING);
 			}
-			OdfValidationException ve = new OdfValidationException(OdfSchemaConstraint.DOCUMENT_WITHOUT_ODF_MIMETYPE,
-					internalPath, documentMediaType);
+			OdfValidationException ve = new OdfValidationException(OdfSchemaConstraint.DOCUMENT_WITHOUT_ODF_MIMETYPE, internalPath, documentMediaType);
 			if (errorHandler != null) {
 				errorHandler.fatalError(ve);
 			}
@@ -355,6 +397,17 @@ public abstract class Document extends O
 		return newDocument(odfPackage, internalPath, odfMediaType);
 	}
 
+	/**
+	 * Sets password of this document.
+	 * 
+	 * @param password
+	 *            the password of this document.
+	 * @since 0.8
+	 */
+	public void setPassword(String password) {
+		getPackage().setPassword(password);
+	}
+
 	// return null if the media type can not be recognized.
 	private static Document loadDocumentFromTemplate(OdfMediaType odfMediaType) throws Exception {
 
@@ -412,8 +465,7 @@ public abstract class Document extends O
 			// case IMAGE_TEMPLATE:
 
 		default:
-			throw new IllegalArgumentException("Given mediaType '" + odfMediaType.toString()
-					+ "' is either not yet supported or not an ODF mediatype!");
+			throw new IllegalArgumentException("Given mediaType '" + odfMediaType.toString() + "' is either not yet supported or not an ODF mediatype!");
 		}
 	}
 
@@ -457,8 +509,7 @@ public abstract class Document extends O
 			break;
 
 		case PRESENTATION_TEMPLATE:
-			newDoc = new PresentationDocument(pkg, internalPath,
-					PresentationDocument.OdfMediaType.PRESENTATION_TEMPLATE);
+			newDoc = new PresentationDocument(pkg, internalPath, PresentationDocument.OdfMediaType.PRESENTATION_TEMPLATE);
 			break;
 
 		case GRAPHICS:
@@ -481,8 +532,7 @@ public abstract class Document extends O
 
 		default:
 			newDoc = null;
-			throw new IllegalArgumentException("Given mediaType '" + odfMediaType.mMediaType
-					+ "' is not yet supported!");
+			throw new IllegalArgumentException("Given mediaType '" + odfMediaType.mMediaType + "' is not yet supported!");
 		}
 		// returning null if MediaType is not supported
 		return newDoc;
@@ -735,6 +785,58 @@ public abstract class Document extends O
 	}
 
 	/**
+	 * Save the document to a given file with given password.
+	 * 
+	 * <p>
+	 * If the input file has been cached (this is the case when loading from an
+	 * InputStream), the input file can be overwritten.
+	 * </p>
+	 * 
+	 * <p>
+	 * Otherwise it's allowed to overwrite the input file as long as the same
+	 * path name is used that was used for loading (no symbolic link foo2.odt
+	 * pointing to the loaded file foo1.odt, no network path X:\foo.odt pointing
+	 * to the loaded file D:\foo.odt).
+	 * </p>
+	 * 
+	 * <p>
+	 * When saving the embedded document to a stand alone document, all files of
+	 * the embedded document will be copied to a new document package. If the
+	 * embedded document is outside of the current document directory, you have
+	 * to embed it to the sub directory and refresh the link of the embedded
+	 * document. You should reload it from the given file to get the saved
+	 * embedded document.
+	 * 
+	 * @param file
+	 *            the file to save the document.
+	 * @param file
+	 *            the password of this document.
+	 * 
+	 * @throws java.lang.Exception
+	 *             if the document could not be saved
+	 * @since 0.8
+	 */
+	public void save(File file, String password) throws Exception {
+		// 2DO FLUSH AND SAVE IN PACKAGE
+		flushDoms();
+		updateMetaData();
+		if (!isRootDocument()) {
+			Document newDoc = loadDocumentFromTemplate(getOdfMediaType());
+			newDoc.insertDocument(this, ROOT_DOCUMENT_PATH);
+			newDoc.updateMetaData();
+			newDoc.mPackage.setPassword(password);
+			newDoc.mPackage.save(file);
+			// ToDo: (Issue 219 - PackageRefactoring) - Return the document,
+			// when not closing!
+			// Should we close the sources now? User will never receive the open
+			// package!
+		} else {
+			mPackage.setPassword(password);
+			mPackage.save(file);
+		}
+	}
+
+	/**
 	 * Close the OdfPackage and release all temporary created data. Acter
 	 * execution of this method, this class is no longer usable. Do this as the
 	 * last action to free resources. Closing an already closed document has no
@@ -813,22 +915,19 @@ public abstract class Document extends O
 			OdfDrawFrame drawFrame = contentDom.newOdfElement(OdfDrawFrame.class);
 			XPath xpath = contentDom.getXPath();
 			if (this instanceof SpreadsheetDocument) {
-				TableTableCellElement lastCell = (TableTableCellElement) xpath.evaluate("//table:table-cell[last()]",
-						contentDom, XPathConstants.NODE);
+				TableTableCellElement lastCell = (TableTableCellElement) xpath.evaluate("//table:table-cell[last()]", contentDom, XPathConstants.NODE);
 				lastCell.appendChild(drawFrame);
 				drawFrame.removeAttribute("text:anchor-type");
 
 			} else if (this instanceof TextDocument) {
-				TextPElement lastPara = (TextPElement) xpath.evaluate("//text:p[last()]", contentDom,
-						XPathConstants.NODE);
+				TextPElement lastPara = (TextPElement) xpath.evaluate("//text:p[last()]", contentDom, XPathConstants.NODE);
 				if (lastPara == null) {
 					lastPara = ((TextDocument) this).newParagraph();
 				}
 				lastPara.appendChild(drawFrame);
 				drawFrame.setTextAnchorTypeAttribute(TextAnchorTypeAttribute.Value.PARAGRAPH.toString());
 			} else if (this instanceof PresentationDocument) {
-				DrawPageElement lastPage = (DrawPageElement) xpath.evaluate("//draw:page[last()]", contentDom,
-						XPathConstants.NODE);
+				DrawPageElement lastPage = (DrawPageElement) xpath.evaluate("//draw:page[last()]", contentDom, XPathConstants.NODE);
 				lastPage.appendChild(drawFrame);
 			}
 			OdfDrawImage image = (OdfDrawImage) drawFrame.newDrawImageElement();
@@ -915,8 +1014,7 @@ public abstract class Document extends O
 				DatatypeFactory aFactory = DatatypeFactory.newInstance();
 				metaData.setEditingDuration(new Duration(aFactory.newDurationDayTime(editingDuration)));
 			} catch (DatatypeConfigurationException e) {
-				Logger.getLogger(Document.class.getName()).log(Level.SEVERE,
-						"editing duration update fail as DatatypeFactory can not be instanced", e);
+				Logger.getLogger(Document.class.getName()).log(Level.SEVERE, "editing duration update fail as DatatypeFactory can not be instanced", e);
 			}
 		}
 	}
@@ -1109,8 +1207,7 @@ public abstract class Document extends O
 		}
 	}
 
-	private Locale getDefaultLanguageByProperty(OdfStyleProperty countryProp, OdfStyleProperty languageProp)
-			throws Exception {
+	private Locale getDefaultLanguageByProperty(OdfStyleProperty countryProp, OdfStyleProperty languageProp) throws Exception {
 		String lang = null, ctry = null;
 
 		OdfOfficeStyles styles = getStylesDom().getOfficeStyles();
@@ -1163,10 +1260,8 @@ public abstract class Document extends O
 		if (getScriptType(locale) != ScriptType.CJK)
 			return;
 		String user_language = locale.getLanguage();
-		if (!user_language.equals(Locale.CHINESE.getLanguage())
-				&& !user_language.equals(Locale.TRADITIONAL_CHINESE.getLanguage())
-				&& !user_language.equals(Locale.JAPANESE.getLanguage())
-				&& !user_language.equals(Locale.KOREAN.getLanguage()))
+		if (!user_language.equals(Locale.CHINESE.getLanguage()) && !user_language.equals(Locale.TRADITIONAL_CHINESE.getLanguage())
+				&& !user_language.equals(Locale.JAPANESE.getLanguage()) && !user_language.equals(Locale.KOREAN.getLanguage()))
 			return;
 
 		OdfOfficeStyles styles = getStylesDom().getOfficeStyles();
@@ -1232,8 +1327,7 @@ public abstract class Document extends O
 
 			// Search in style.xml
 			root = getStylesDom().getRootElement();
-			OfficeMasterStylesElement masterStyle = OdfElement
-					.findFirstChildNode(OfficeMasterStylesElement.class, root);
+			OfficeMasterStylesElement masterStyle = OdfElement.findFirstChildNode(OfficeMasterStylesElement.class, root);
 			sectionList = masterStyle.getElementsByTagNameNS(OdfDocumentNamespace.TEXT.getUri(), "section");
 			for (int i = 0; i < sectionList.getLength(); i++) {
 				element = (TextSectionElement) sectionList.item(i);
@@ -1271,11 +1365,9 @@ public abstract class Document extends O
 			}
 
 			root = getStylesDom().getRootElement();
-			OfficeMasterStylesElement masterStyle = OdfElement
-					.findFirstChildNode(OfficeMasterStylesElement.class, root);
+			OfficeMasterStylesElement masterStyle = OdfElement.findFirstChildNode(OfficeMasterStylesElement.class, root);
 			xpath = getStylesDom().getXPath();
-			element = (TextSectionElement) xpath.evaluate(".//text:section[@text:name=\"" + name + "\"]", masterStyle,
-					XPathConstants.NODE);
+			element = (TextSectionElement) xpath.evaluate(".//text:section[@text:name=\"" + name + "\"]", masterStyle, XPathConstants.NODE);
 			if (element != null) {
 				return Section.getInstance(element);
 			}
@@ -1499,8 +1591,7 @@ public abstract class Document extends O
 					if (objectRenameMap.containsKey(refObjPath)) {
 						// this object has been copied already
 						newObjPath = objectRenameMap.get(refObjPath);
-						object.setAttributeNS(OdfDocumentNamespace.XLINK.getUri(), "xlink:href",
-								hasPrefix ? (prefix + newObjPath) : newObjPath);
+						object.setAttributeNS(OdfDocumentNamespace.XLINK.getUri(), "xlink:href", hasPrefix ? (prefix + newObjPath) : newObjPath);
 						continue;
 					}
 					// check if the current document contains the same path
@@ -1519,15 +1610,13 @@ public abstract class Document extends O
 							// then change the name before the suffix string
 							int dotIndex = refObjPath.indexOf(".");
 							if (dotIndex != -1) {
-								newObjPath = refObjPath.substring(0, dotIndex) + "-" + makeUniqueName()
-										+ refObjPath.substring(dotIndex);
+								newObjPath = refObjPath.substring(0, dotIndex) + "-" + makeUniqueName() + refObjPath.substring(dotIndex);
 							} else {
 								newObjPath = refObjPath + "-" + makeUniqueName();
 							}
 							objectRenameMap.put(refObjPath, newObjPath);
 						}
-						object.setAttributeNS(OdfDocumentNamespace.XLINK.getUri(), "xlink:href",
-								hasPrefix ? (prefix + newObjPath) : newObjPath);
+						object.setAttributeNS(OdfDocumentNamespace.XLINK.getUri(), "xlink:href", hasPrefix ? (prefix + newObjPath) : newObjPath);
 					} else
 						objectRenameMap.put(refObjPath, refObjPath);
 				}
@@ -1811,15 +1900,13 @@ public abstract class Document extends O
 							// then change the name before the suffix string
 							int dotIndex = refObjPath.indexOf(".");
 							if (dotIndex != -1) {
-								newObjPath = refObjPath.substring(0, dotIndex) + "-" + makeUniqueName()
-										+ refObjPath.substring(dotIndex);
+								newObjPath = refObjPath.substring(0, dotIndex) + "-" + makeUniqueName() + refObjPath.substring(dotIndex);
 							} else {
 								newObjPath = refObjPath + "-" + makeUniqueName();
 							}
 							objectRenameMap.put(refObjPath, newObjPath);
 						}
-						object.setAttributeNS(OdfDocumentNamespace.XLINK.getUri(), "xlink:href",
-								hasPrefix ? (prefix + newObjPath) : newObjPath);
+						object.setAttributeNS(OdfDocumentNamespace.XLINK.getUri(), "xlink:href", hasPrefix ? (prefix + newObjPath) : newObjPath);
 					}
 					InputStream is = srcDoc.getPackage().getInputStream(refObjPath);
 					if (is != null) {
@@ -1856,20 +1943,16 @@ public abstract class Document extends O
 			// attribute
 			// 1.1. style:name of content.xml
 			String styleQName = "style:name";
-			NodeList srcStyleDefNodeList = (NodeList) xpath.evaluate(
-					"*/office:automatic-styles/*[@" + styleQName + "]", srcContentDom, XPathConstants.NODESET);
+			NodeList srcStyleDefNodeList = (NodeList) xpath.evaluate("*/office:automatic-styles/*[@" + styleQName + "]", srcContentDom, XPathConstants.NODESET);
 			IdentityHashMap<OdfElement, List<OdfElement>> srcContentStyleCloneEleList = new IdentityHashMap<OdfElement, List<OdfElement>>();
 			IdentityHashMap<OdfElement, OdfElement> appendContentStyleList = new IdentityHashMap<OdfElement, OdfElement>();
-			getCopyStyleList(null, sourceCloneEle, styleQName, srcStyleDefNodeList, srcContentStyleCloneEleList,
-					appendContentStyleList, tempList, true);
+			getCopyStyleList(null, sourceCloneEle, styleQName, srcStyleDefNodeList, srcContentStyleCloneEleList, appendContentStyleList, tempList, true);
 			// 1.2. style:name of styles.xml
-			srcStyleDefNodeList = (NodeList) xpath.evaluate(".//*[@" + styleQName + "]", srcDoc.getStylesDom(),
-					XPathConstants.NODESET);
+			srcStyleDefNodeList = (NodeList) xpath.evaluate(".//*[@" + styleQName + "]", srcDoc.getStylesDom(), XPathConstants.NODESET);
 			IdentityHashMap<OdfElement, List<OdfElement>> srcStylesStyleCloneEleList = new IdentityHashMap<OdfElement, List<OdfElement>>();
 			IdentityHashMap<OdfElement, OdfElement> appendStylesStyleList = new IdentityHashMap<OdfElement, OdfElement>();
 			tempList.clear();
-			getCopyStyleList(null, sourceCloneEle, styleQName, srcStyleDefNodeList, srcStylesStyleCloneEleList,
-					appendStylesStyleList, tempList, true);
+			getCopyStyleList(null, sourceCloneEle, styleQName, srcStyleDefNodeList, srcStylesStyleCloneEleList, appendStylesStyleList, tempList, true);
 			// 1.3 rename, copy the referred style element to the corresponding
 			// position in the dom tree
 			insertCollectedStyle(styleQName, srcContentStyleCloneEleList, getContentDom(), appendContentStyleList);
@@ -1885,23 +1968,22 @@ public abstract class Document extends O
 			// element, so only search it in styles.xml dom
 			tempList.clear();
 			styleQName = "draw:name";
-			srcStyleDefNodeList = (NodeList) xpath.evaluate(".//*[@" + styleQName + "]", srcDoc.getStylesDom(),
-					XPathConstants.NODESET);
+			srcStyleDefNodeList = (NodeList) xpath.evaluate(".//*[@" + styleQName + "]", srcDoc.getStylesDom(), XPathConstants.NODESET);
 			IdentityHashMap<OdfElement, List<OdfElement>> srcDrawStyleCloneEleList = new IdentityHashMap<OdfElement, List<OdfElement>>();
 			IdentityHashMap<OdfElement, OdfElement> appendDrawStyleList = new IdentityHashMap<OdfElement, OdfElement>();
 			Iterator<OdfElement> iter = appendContentStyleList.keySet().iterator();
 			while (iter.hasNext()) {
 				OdfElement styleElement = iter.next();
 				OdfElement cloneStyleElement = appendContentStyleList.get(styleElement);
-				getCopyStyleList(styleElement, cloneStyleElement, styleQName, srcStyleDefNodeList,
-						srcDrawStyleCloneEleList, appendDrawStyleList, tempList, false);
+				getCopyStyleList(styleElement, cloneStyleElement, styleQName, srcStyleDefNodeList, srcDrawStyleCloneEleList, appendDrawStyleList, tempList,
+						false);
 			}
 			iter = appendStylesStyleList.keySet().iterator();
 			while (iter.hasNext()) {
 				OdfElement styleElement = iter.next();
 				OdfElement cloneStyleElement = appendStylesStyleList.get(styleElement);
-				getCopyStyleList(styleElement, cloneStyleElement, styleQName, srcStyleDefNodeList,
-						srcDrawStyleCloneEleList, appendDrawStyleList, tempList, false);
+				getCopyStyleList(styleElement, cloneStyleElement, styleQName, srcStyleDefNodeList, srcDrawStyleCloneEleList, appendDrawStyleList, tempList,
+						false);
 			}
 			// 2.2 rename, copy the referred style element to the corresponding
 			// position in the dom tree
@@ -1919,8 +2001,7 @@ public abstract class Document extends O
 	// referred style name of the element which reference this style
 	// 3. All the style which also contains other style reference, should be
 	// copied to the source document.
-	private void insertCollectedStyle(String styleQName,
-			IdentityHashMap<OdfElement, List<OdfElement>> srcStyleCloneEleList, OdfFileDom dom,
+	private void insertCollectedStyle(String styleQName, IdentityHashMap<OdfElement, List<OdfElement>> srcStyleCloneEleList, OdfFileDom dom,
 			IdentityHashMap<OdfElement, OdfElement> appendStyleList) {
 		try {
 			String stylePrefix = OdfNamespace.getPrefixPart(styleQName);
@@ -1932,8 +2013,7 @@ public abstract class Document extends O
 			XPath xpath = dom.getXPath();
 			NodeList destStyleNodeList;
 			if (dom instanceof OdfContentDom)
-				destStyleNodeList = (NodeList) xpath.evaluate("*/office:automatic-styles/*[@" + styleQName + "]", dom,
-						XPathConstants.NODESET);
+				destStyleNodeList = (NodeList) xpath.evaluate("*/office:automatic-styles/*[@" + styleQName + "]", dom, XPathConstants.NODESET);
 			else
 				destStyleNodeList = (NodeList) xpath.evaluate(".//*[@" + styleQName + "]", dom, XPathConstants.NODESET);
 			Iterator<OdfElement> iter = srcStyleCloneEleList.keySet().iterator();
@@ -1965,8 +2045,7 @@ public abstract class Document extends O
 							// if not, the cloneStyleElement should rename,
 							// rather than reuse the new style name
 							cloneStyleElement.setAttributeNS(styleURI, styleQName, styleNameIter);
-							if ((destStyleElementWithNewName != null)
-									&& destStyleElementWithNewName.equals(cloneStyleElement)) {
+							if ((destStyleElementWithNewName != null) && destStyleElementWithNewName.equals(cloneStyleElement)) {
 								newStyleName = styleNameIter;
 								break;
 							}
@@ -1987,8 +2066,8 @@ public abstract class Document extends O
 						// if display name should also be renamed
 						String displayName = cloneStyleElement.getAttributeNS(styleURI, "display-name");
 						if ((displayName != null) && (displayName.length() > 0)) {
-							cloneStyleElement.setAttributeNS(styleURI, stylePrefix + ":display-name", displayName
-									+ newStyleName.substring(newStyleName.length() - 8));
+							cloneStyleElement.setAttributeNS(styleURI, stylePrefix + ":display-name",
+									displayName + newStyleName.substring(newStyleName.length() - 8));
 						}
 					}
 				}
@@ -2036,8 +2115,8 @@ public abstract class Document extends O
 	// if loop == true, get the style definition element reference other style
 	// definition element
 	private void getCopyStyleList(OdfElement ele, OdfElement cloneEle, String styleQName, NodeList srcStyleNodeList,
-			IdentityHashMap<OdfElement, List<OdfElement>> copyStyleEleList,
-			IdentityHashMap<OdfElement, OdfElement> appendStyleList, List<String> attrStrList, boolean loop) {
+			IdentityHashMap<OdfElement, List<OdfElement>> copyStyleEleList, IdentityHashMap<OdfElement, OdfElement> appendStyleList, List<String> attrStrList,
+			boolean loop) {
 		try {
 			String styleLocalName = OdfNamespace.getLocalPart(styleQName);
 			String stylePrefix = OdfNamespace.getPrefixPart(styleQName);
@@ -2062,8 +2141,7 @@ public abstract class Document extends O
 						}
 						attrStrList.add(attrStr + "=" + "\"" + styleName + "\"");
 						XPath xpath = ((OdfFileDom) cloneEle.getOwnerDocument()).getXPath();
-						NodeList styleRefNodes = (NodeList) xpath.evaluate(
-								".//*[@" + attrStr + "='" + styleName + "']", cloneEle, XPathConstants.NODESET);
+						NodeList styleRefNodes = (NodeList) xpath.evaluate(".//*[@" + attrStr + "='" + styleName + "']", cloneEle, XPathConstants.NODESET);
 						boolean isExist = false;
 						for (int j = 0; j <= styleRefNodes.getLength(); j++) {
 							OdfElement styleRefElement = null;
@@ -2096,8 +2174,8 @@ public abstract class Document extends O
 								appendStyleList.put(styleElement, cloneStyleElement);
 							}
 							if (loop && !hasLoopStyleDef) {
-								getCopyStyleList(styleElement, cloneStyleElement, styleQName, srcStyleNodeList,
-										copyStyleEleList, appendStyleList, attrStrList, loop);
+								getCopyStyleList(styleElement, cloneStyleElement, styleQName, srcStyleNodeList, copyStyleEleList, appendStyleList, attrStrList,
+										loop);
 							}
 						}
 						index = cloneEleStr.indexOf("=\"" + styleName + "\"", index + styleName.length());
@@ -2266,11 +2344,9 @@ public abstract class Document extends O
 				int relation = odfEle.compareDocumentPosition(object);
 				// if slide element contains the returned element which has the
 				// xlink:href reference
-				if ((relation & Node.DOCUMENT_POSITION_CONTAINED_BY) > 0 && refObjPath != null
-						&& refObjPath.length() > 0) {
+				if ((relation & Node.DOCUMENT_POSITION_CONTAINED_BY) > 0 && refObjPath != null && refObjPath.length() > 0) {
 					// the path of the object is start with "./"
-					NodeList pathNodes = (NodeList) xpath.evaluate("//*[@xlink:href='" + refObjPath + "']",
-							getContentDom(), XPathConstants.NODESET);
+					NodeList pathNodes = (NodeList) xpath.evaluate("//*[@xlink:href='" + refObjPath + "']", getContentDom(), XPathConstants.NODESET);
 					int refCount = pathNodes.getLength();
 					if (refCount == 1) {
 						// delete "./"
@@ -2336,8 +2412,7 @@ public abstract class Document extends O
 					if (styleName != null) {
 						// search the styleName contained at the current page
 						// element
-						NodeList styleNodes = (NodeList) xpath.evaluate("//*[@*='" + styleName + "']", contentDom,
-								XPathConstants.NODESET);
+						NodeList styleNodes = (NodeList) xpath.evaluate("//*[@*='" + styleName + "']", contentDom, XPathConstants.NODESET);
 						int styleCnt = styleNodes.getLength();
 						if (styleCnt > 1) {
 							// the first styleName is occurred in the style
@@ -2399,7 +2474,7 @@ public abstract class Document extends O
 	public TableBuilder getTableBuilder() {
 		return getTableContainerImpl().getTableBuilder();
 	}
-	
+
 	protected TableContainer getTableContainerImpl() {
 		if (tableContainerImpl == null) {
 			tableContainerImpl = new TableContainerImpl();

Modified: incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/DocumentTest.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/DocumentTest.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/DocumentTest.java (original)
+++ incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/DocumentTest.java Thu Dec 20 07:33:34 2012
@@ -377,6 +377,41 @@ public class DocumentTest {
 			Assert.fail(e.getMessage());
 		}
 	}
+	
+	@Test
+	public void testDocumentPassword() {
+		File passwordOutputFile = ResourceUtilities.newTestOutputFile("PasswordDocument.odt");
+		File noPassOutputFile = ResourceUtilities.newTestOutputFile("NoPasswordDocument.odt");
+		try {
+			TextDocument doc = TextDocument.newTextDocument();
+			doc.addParagraph("blablabla...");
+			doc.setPassword("password");
+			doc.save(passwordOutputFile);
+			
+			Document redoc = Document.loadDocument(passwordOutputFile, "password");
+			//test load content.xml
+			Assert.assertNotNull(redoc.getContentRoot().toString());
+			//test load styles.xml
+			((TextDocument) redoc).getHeader().addTable();
+			//test load meta.xml
+			Assert.assertNotNull(redoc.getOfficeMetadata().getCreator());
+			
+			//remove password
+			redoc.setPassword(null);
+			redoc.save(noPassOutputFile);
+			
+			//test inserted document
+			doc = TextDocument.newTextDocument();
+			doc.addParagraph("embed_document");
+			redoc.insertDocument(doc, "/embed");
+			redoc.setPassword("password");
+			
+			redoc.save(passwordOutputFile);
+		} catch (Exception ex) {
+			LOG.log(Level.SEVERE, "document password test failed.", ex);
+			Assert.fail();
+		}
+	}
 
 	@Test
 	public void testSetLocale() {

Modified: incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/SpreadsheetDocumentTest.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/SpreadsheetDocumentTest.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/SpreadsheetDocumentTest.java (original)
+++ incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/SpreadsheetDocumentTest.java Thu Dec 20 07:33:34 2012
@@ -132,13 +132,13 @@ public class SpreadsheetDocumentTest {
 			Assert.assertNotNull(spChart);
 			spChart.setChartType(ChartType.AREA);
 			//save
-			spDocument.save(ResourceUtilities.getAbsolutePath(TEST_FILE));
+			spDocument.save(ResourceUtilities.getTestOutput("Chart_"+TEST_FILE));
 			
 			Assert.assertEquals(dataset, spChart.getChartData());
 			Assert.assertEquals("XXXTitle", spChart.getChartTitle());
 			Assert.assertEquals(ChartType.AREA, spChart.getChartType());
 			
-			System.out.println("spChart--> " + spChart);
+			LOG.log(Level.INFO,"spChart--> " + spChart);
 			
 		} catch (Exception e) {
 			LOG.log(Level.SEVERE, e.getMessage(), e);
@@ -226,7 +226,7 @@ public class SpreadsheetDocumentTest {
 		Table tablem = spDocument.getSheetByIndex(0);
 		Assert.assertNotSame(tablea, tablem);
 		
-		//spDocument.save(ResourceUtilities.getAbsolutePath(TEST_FILE));
+		spDocument.save(ResourceUtilities.getAbsolutePath(TEST_FILE));
 	}
 	
 	@Test

Modified: incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/meta/OfficeMetaTest.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/meta/OfficeMetaTest.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/meta/OfficeMetaTest.java (original)
+++ incubator/odf/trunk/simple/src/test/java/org/odftoolkit/simple/meta/OfficeMetaTest.java Thu Dec 20 07:33:34 2012
@@ -293,6 +293,7 @@ public class OfficeMetaTest {
         File persistedDocument = File.createTempFile(getClass().getName(), ".odt");
         persistedDocument.deleteOnExit();
 	doc.save(persistedDocument);
+	Thread.sleep(100);
 	doc = (TextDocument) TextDocument.loadDocument(persistedDocument);
 	metadom = doc.getMetaDom();
 	fMetadata = new Meta(metadom);

Modified: incubator/odf/trunk/validator/src/main/java/org/odftoolkit/odfvalidator/ODFPackageValidator.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/validator/src/main/java/org/odftoolkit/odfvalidator/ODFPackageValidator.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/validator/src/main/java/org/odftoolkit/odfvalidator/ODFPackageValidator.java (original)
+++ incubator/odf/trunk/validator/src/main/java/org/odftoolkit/odfvalidator/ODFPackageValidator.java Thu Dec 20 07:33:34 2012
@@ -33,7 +33,7 @@ import javax.xml.transform.sax.SAXSource
 import javax.xml.validation.Validator;
 import org.odftoolkit.odfdom.doc.OdfDocument;
 import org.odftoolkit.odfdom.pkg.OdfPackage;
-import org.odftoolkit.odfdom.pkg.manifest.EncryptionData;
+import org.odftoolkit.odfdom.pkg.manifest.EncryptionDataElement;
 import org.odftoolkit.odfdom.pkg.manifest.OdfFileEntry;
 import org.xml.sax.InputSource;
 import org.xml.sax.XMLFilter;
@@ -361,7 +361,7 @@ abstract class ODFPackageValidator {
 	private boolean isEncrypted(String aEntryName, Logger aLogger) {
 		OdfFileEntry aFileEntry = getPackage(aLogger).getFileEntry(aEntryName);
 		if (aFileEntry != null) {
-			EncryptionData aEncData = aFileEntry.getEncryptionData();
+			EncryptionDataElement aEncData = aFileEntry.getEncryptionData();
 			if (aEncData != null) {
 				aLogger.logFatalError("stream content is encrypted. Validataion of encrypted content is not supported.");
 				return true;

Modified: incubator/odf/trunk/validator/src/test/java/org/odftoolkit/odfvalidator/InvalidPackageTest.java
URL: http://svn.apache.org/viewvc/incubator/odf/trunk/validator/src/test/java/org/odftoolkit/odfvalidator/InvalidPackageTest.java?rev=1424353&r1=1424352&r2=1424353&view=diff
==============================================================================
--- incubator/odf/trunk/validator/src/test/java/org/odftoolkit/odfvalidator/InvalidPackageTest.java (original)
+++ incubator/odf/trunk/validator/src/test/java/org/odftoolkit/odfvalidator/InvalidPackageTest.java Thu Dec 20 07:33:34 2012
@@ -105,6 +105,6 @@ public class InvalidPackageTest extends 
 			Assert.fail(t.toString());
 		}
 		Assert.assertTrue(output.contains("Error: The ODF package 'testInvalidPkg3.odt' shall contain the 'META-INF/manifest.xml' file"));
-		Assert.assertTrue(output.contains("testInvalidPkg3.odt:  Info: 3 errors, no warnings"));
+		Assert.assertTrue(output.contains("testInvalidPkg3.odt:  Info: 2 errors, no warnings"));
 	}
 }



Mime
View raw message