commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mart...@apache.org
Subject svn commit: r349357 - in /jakarta/commons/proper/fileupload/trunk/src: java/org/apache/commons/fileupload/disk/DiskFileItem.java test/org/apache/commons/fileupload/DiskFileItemSerializeTest.java
Date Mon, 28 Nov 2005 03:59:36 GMT
Author: martinc
Date: Sun Nov 27 19:59:34 2005
New Revision: 349357

URL: http://svn.apache.org/viewcvs?rev=349357&view=rev
Log:
Bugzilla #32785 - Make DiskFileItem serializable. Thanks to Niall Pemberton for the suggestion
and patch.

Added:
    jakarta/commons/proper/fileupload/trunk/src/test/org/apache/commons/fileupload/DiskFileItemSerializeTest.java
  (with props)
Modified:
    jakarta/commons/proper/fileupload/trunk/src/java/org/apache/commons/fileupload/disk/DiskFileItem.java

Modified: jakarta/commons/proper/fileupload/trunk/src/java/org/apache/commons/fileupload/disk/DiskFileItem.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/fileupload/trunk/src/java/org/apache/commons/fileupload/disk/DiskFileItem.java?rev=349357&r1=349356&r2=349357&view=diff
==============================================================================
--- jakarta/commons/proper/fileupload/trunk/src/java/org/apache/commons/fileupload/disk/DiskFileItem.java
(original)
+++ jakarta/commons/proper/fileupload/trunk/src/java/org/apache/commons/fileupload/disk/DiskFileItem.java
Sun Nov 27 19:59:34 2005
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2004 The Apache Software Foundation
+ * Copyright 2001-2005 The Apache Software Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -24,9 +24,12 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectInputStream;
 import java.io.UnsupportedEncodingException;
 import java.rmi.server.UID;
 import java.util.Map;
+import org.apache.commons.io.CopyUtils;
 import org.apache.commons.io.FileCleaner;
 import org.apache.commons.io.output.DeferredFileOutputStream;
 
@@ -141,7 +144,12 @@
     /**
      * Output stream for this item.
      */
-    private DeferredFileOutputStream dfos;
+    private transient DeferredFileOutputStream dfos;
+
+    /**
+     * File to allow for serialization of the content of this item.
+     */
+    private File dfosFile;
 
 
     // ----------------------------------------------------------- Constructors
@@ -190,7 +198,7 @@
      */
     public InputStream getInputStream()
         throws IOException {
-        if (!dfos.isInMemory()) {
+        if (!isInMemory()) {
             return new FileInputStream(dfos.getFile());
         }
 
@@ -250,7 +258,11 @@
      *         from memory; <code>false</code> otherwise.
      */
     public boolean isInMemory() {
-        return (dfos.isInMemory());
+        if (cachedContent != null) {
+            return true;
+        } else {
+            return dfos.isInMemory();
+        }
     }
 
 
@@ -278,7 +290,7 @@
      * @return The contents of the file as an array of bytes.
      */
     public byte[] get() {
-        if (dfos.isInMemory()) {
+        if (isInMemory()) {
             if (cachedContent == null) {
                 cachedContent = dfos.getData();
             }
@@ -602,7 +614,15 @@
         }
         return id;
     }
-    
+
+
+
+
+    /**
+
+     * Returns a string representation of this object.
+
+     */
     public String toString() {
     	return "name=" + this.getName()
 			+ ", StoreLocation=" 
@@ -613,6 +633,69 @@
 			+ "isFormField=" + isFormField()
 			+ ", FieldName="
 			+ this.getFieldName();
+    }
+
+
+
+    // -------------------------------------------------- Serialization methods
+
+
+
+
+    /**
+     * Writes the state of this object during serialization.
+
+     *
+
+     * @param out The stream to which the state should be written.
+
+     *
+
+     * @throws IOException if an error occurs.
+     */
+    private void writeObject(ObjectOutputStream out) throws IOException {
+        // Read the data
+        if (dfos.isInMemory()) {
+            cachedContent = get();
+        } else {
+            cachedContent = null;
+            dfosFile = dfos.getFile();
+        }
+
+        // write out values
+        out.defaultWriteObject();
+    }
+
+    /**
+     * Reads the state of this object during deserialization.
+
+     *
+
+     * @param in The stream from which the state should be read.
+     *
+
+     * @throws IOException if an error occurs.
+     * @throws ClassNotFoundException if class cannot be found.
+     */
+    private void readObject(ObjectInputStream in)
+
+            throws IOException, ClassNotFoundException {
+        // read values
+        in.defaultReadObject();
+        
+        OutputStream output = getOutputStream();
+        if (cachedContent != null) {
+            output.write(cachedContent);
+        } else {
+            FileInputStream input = new FileInputStream(dfosFile);
+
+            CopyUtils.copy(input, output);
+            dfosFile.delete();
+            dfosFile = null;
+        }
+        output.close();
+
+        cachedContent = null;
     }
 
 }

Added: jakarta/commons/proper/fileupload/trunk/src/test/org/apache/commons/fileupload/DiskFileItemSerializeTest.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/proper/fileupload/trunk/src/test/org/apache/commons/fileupload/DiskFileItemSerializeTest.java?rev=349357&view=auto
==============================================================================
--- jakarta/commons/proper/fileupload/trunk/src/test/org/apache/commons/fileupload/DiskFileItemSerializeTest.java
(added)
+++ jakarta/commons/proper/fileupload/trunk/src/test/org/apache/commons/fileupload/DiskFileItemSerializeTest.java
Sun Nov 27 19:59:34 2005
@@ -0,0 +1,271 @@
+/*
+ * Copyright 2005 The Apache Software Foundation
+ *
+ * Licensed 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.commons.fileupload;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.Arrays;
+
+import junit.framework.TestCase;
+import org.apache.commons.fileupload.disk.DiskFileItem;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+
+
+/**
+ * Serialization Unit tests for 
+ *  {@link org.apache.commons.fileupload.disk.DiskFileItemTest}.
+ */
+public class DiskFileItemSerializeTest extends TestCase
+ {
+
+    /**
+     * Content type for regular form items.
+     */
+    private static final String textContentType = "text/plain";
+
+    /**
+     * Content type for file uploads.
+     */
+    private static final String fileContentType = "application/octet-stream";
+
+    /**
+     * Very low threshold for testing memory versus disk options.
+     */
+    private static final int threshold = 16;
+
+    /**
+     * Standard JUnit test case constructor.
+     *
+     * @param name The name of the test case.
+     */
+    public DiskFileItemSerializeTest(String name)
+    {
+        super(name);
+    }
+
+    /**
+     * Test creation of a field for which the amount of data falls below the
+     * configured threshold.
+     */
+    public void testBelowThreshold()
+    {
+
+        // Create the FileItem
+        byte[] testFieldValueBytes = createContentBytes(threshold - 1);
+        FileItem item = createFileItem(testFieldValueBytes);
+
+        // Check state is as expected
+        assertTrue("Initial: in memory", item.isInMemory());
+        assertEquals("Initial: size", item.getSize(), testFieldValueBytes.length);
+        compareBytes("Initial", item.get(), testFieldValueBytes);
+
+        // Serialize & Deserialize
+        try
+        {
+            FileItem newItem = (FileItem)serializeDeserialize(item);
+
+            // Test deserialized content is as expected
+            assertTrue("Check in memory", newItem.isInMemory());
+            compareBytes("Check", testFieldValueBytes, newItem.get());
+
+            // Compare FileItem's (except byte[])
+            compareFileItems(item, newItem);
+
+        }
+        catch(Exception e)
+        {
+            fail("Error Serializing/Deserializing: " + e);
+        }
+
+
+    }
+
+    /**
+     * Test creation of a field for which the amount of data equals the
+     * configured threshold.
+     */
+    public void testThreshold() {
+        // Create the FileItem
+        byte[] testFieldValueBytes = createContentBytes(threshold);
+        FileItem item = createFileItem(testFieldValueBytes);
+
+        // Check state is as expected
+        assertTrue("Initial: in memory", item.isInMemory());
+        assertEquals("Initial: size", item.getSize(), testFieldValueBytes.length);
+        compareBytes("Initial", item.get(), testFieldValueBytes);
+
+
+        // Serialize & Deserialize
+        try
+        {
+            FileItem newItem = (FileItem)serializeDeserialize(item);
+
+            // Test deserialized content is as expected
+            assertTrue("Check in memory", newItem.isInMemory());
+            compareBytes("Check", testFieldValueBytes, newItem.get());
+
+            // Compare FileItem's (except byte[])
+            compareFileItems(item, newItem);
+
+        }
+        catch(Exception e)
+        {
+            fail("Error Serializing/Deserializing: " + e);
+        }
+    }
+
+    /**
+     * Test creation of a field for which the amount of data falls above the
+     * configured threshold.
+     */
+    public void testAboveThreshold() {
+
+        // Create the FileItem
+        byte[] testFieldValueBytes = createContentBytes(threshold + 1);
+        FileItem item = createFileItem(testFieldValueBytes);
+
+        // Check state is as expected
+        assertFalse("Initial: in memory", item.isInMemory());
+        assertEquals("Initial: size", item.getSize(), testFieldValueBytes.length);
+        compareBytes("Initial", item.get(), testFieldValueBytes);
+
+        // Serialize & Deserialize
+        try
+        {
+            FileItem newItem = (FileItem)serializeDeserialize(item);
+
+            // Test deserialized content is as expected
+            assertFalse("Check in memory", newItem.isInMemory());
+            compareBytes("Check", testFieldValueBytes, newItem.get());
+
+            // Compare FileItem's (except byte[])
+            compareFileItems(item, newItem);
+
+        }
+        catch(Exception e)
+        {
+            fail("Error Serializing/Deserializing: " + e);
+        }
+    }
+
+    /**
+     * Compare FileItem's (except the byte[] content)
+     */
+    private void compareFileItems(FileItem origItem, FileItem newItem) {
+        assertTrue("Compare: is in Memory",   origItem.isInMemory()   == newItem.isInMemory());
+        assertTrue("Compare: is Form Field",  origItem.isFormField()  == newItem.isFormField());
+        assertEquals("Compare: Field Name",   origItem.getFieldName(),   newItem.getFieldName());
+        assertEquals("Compare: Content Type", origItem.getContentType(), newItem.getContentType());
+        assertEquals("Compare: File Name",    origItem.getName(),        newItem.getName());
+    }
+
+    /**
+     * Compare content bytes.
+     */
+    private void compareBytes(String text, byte[] origBytes, byte[] newBytes) {
+        if (origBytes == null) {
+            fail(text + " origBytes are null");
+        }
+        if (newBytes == null) {
+            fail(text + " newBytes are null");
+        }
+        assertEquals(text + " byte[] length", origBytes.length, newBytes.length);
+        for (int i = 0; i < origBytes.length; i++) {
+            assertEquals(text + " byte[" + i + "]", origBytes[i], newBytes[i]);
+        }
+    }
+
+    /**
+     * Create content bytes of a specified size.
+     */
+    private byte[] createContentBytes(int size) {
+        StringBuffer buffer = new StringBuffer(size);
+        byte count = 0;
+        for (int i = 0; i < size; i++) {
+            buffer.append(count+"");
+            count++;
+            if (count > 9) {
+                count = 0;
+            }
+        }
+        return buffer.toString().getBytes();
+    }
+
+    /**
+     * Create a FileItem with the specfied content bytes.
+     */
+    private FileItem createFileItem(byte[] contentBytes) {
+        FileItemFactory factory = new DiskFileItemFactory(threshold, null);
+        String textFieldName = "textField";
+
+        FileItem item = factory.createItem(
+                textFieldName,
+                textContentType,
+                true,
+                "My File Name"
+        );
+        try
+        {
+            OutputStream os = item.getOutputStream();
+            os.write(contentBytes);
+            os.close();
+        }
+        catch(IOException e)
+        {
+            fail("Unexpected IOException" + e);
+        }
+
+        return item;
+
+    }
+
+    /**
+     * Do serialization and deserialization.
+     */
+    private Object serializeDeserialize(Object target) {
+
+        // Serialize the test object
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        try {
+            ObjectOutputStream oos = new ObjectOutputStream(baos);
+            oos.writeObject(target);
+            oos.flush();
+            oos.close();
+        } catch (Exception e) {
+            fail("Exception during serialization: " + e);
+        }
+
+        // Deserialize the test object
+        Object result = null;
+        try {
+            ByteArrayInputStream bais =
+                new ByteArrayInputStream(baos.toByteArray());
+            ObjectInputStream ois = new ObjectInputStream(bais);
+            result = ois.readObject();
+            bais.close();
+        } catch (Exception e) {
+            fail("Exception during deserialization: " + e);
+        }
+        return result;
+
+    }
+
+}

Propchange: jakarta/commons/proper/fileupload/trunk/src/test/org/apache/commons/fileupload/DiskFileItemSerializeTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: jakarta/commons/proper/fileupload/trunk/src/test/org/apache/commons/fileupload/DiskFileItemSerializeTest.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL



---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message