cxf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From a.@apache.org
Subject svn commit: r1441370 - in /cxf/trunk/api/src: main/java/org/apache/cxf/io/ test/java/org/apache/cxf/io/
Date Fri, 01 Feb 2013 10:11:29 GMT
Author: ay
Date: Fri Feb  1 10:11:29 2013
New Revision: 1441370

URL: http://svn.apache.org/viewvc?rev=1441370&view=rev
Log:
[CXF-4798] Allow CachedWriter and CachedOutputStream to be configured using the same props

Added:
    cxf/trunk/api/src/main/java/org/apache/cxf/io/CipherPair.java
    cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedStreamTestBase.java   (with props)
Modified:
    cxf/trunk/api/src/main/java/org/apache/cxf/io/CachedOutputStream.java
    cxf/trunk/api/src/main/java/org/apache/cxf/io/CachedWriter.java
    cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedOutputStreamTest.java
    cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedWriterTest.java

Modified: cxf/trunk/api/src/main/java/org/apache/cxf/io/CachedOutputStream.java
URL: http://svn.apache.org/viewvc/cxf/trunk/api/src/main/java/org/apache/cxf/io/CachedOutputStream.java?rev=1441370&r1=1441369&r2=1441370&view=diff
==============================================================================
--- cxf/trunk/api/src/main/java/org/apache/cxf/io/CachedOutputStream.java (original)
+++ cxf/trunk/api/src/main/java/org/apache/cxf/io/CachedOutputStream.java Fri Feb  1 10:11:29
2013
@@ -34,17 +34,12 @@ import java.io.PipedInputStream;
 import java.io.PipedOutputStream;
 import java.io.Reader;
 import java.security.GeneralSecurityException;
-import java.security.Key;
-import java.security.SecureRandom;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
-import javax.crypto.Cipher;
 import javax.crypto.CipherInputStream;
 import javax.crypto.CipherOutputStream;
-import javax.crypto.KeyGenerator;
-import javax.crypto.spec.IvParameterSpec;
 
 import org.apache.cxf.Bus;
 import org.apache.cxf.BusFactory;
@@ -92,8 +87,7 @@ public class CachedOutputStream extends 
     private File outputDir = DEFAULT_TEMP_DIR;
     private boolean allowDeleteOfFile = true;
     private String cipherTransformation = defaultCipherTransformation;
-    private Cipher enccipher;
-    private Cipher deccipher;
+    private CipherPair ciphers;
 
     private List<CachedOutputStreamCallback> callbacks;
     
@@ -545,7 +539,7 @@ public class CachedOutputStream extends 
                 };
                 streamList.add(fileInputStream);
                 if (cipherTransformation != null) {
-                    fileInputStream = new CipherInputStream(fileInputStream, deccipher) {
+                    fileInputStream = new CipherInputStream(fileInputStream, ciphers.getDecryptor())
{
                         boolean closed;
                         public void close() throws IOException {
                             if (!closed) {
@@ -629,41 +623,17 @@ public class CachedOutputStream extends 
         defaultCipherTransformation = n;
     }
 
-    private synchronized void initCiphers() throws GeneralSecurityException {
-        if (enccipher == null) {
-            int d = cipherTransformation.indexOf('/');
-            String a;
-            if (d > 0) {
-                a = cipherTransformation.substring(0, d);
-            } else {
-                a = cipherTransformation;
-            }
-            try {
-                KeyGenerator keygen = KeyGenerator.getInstance(a);
-                keygen.init(new SecureRandom());
-                Key key = keygen.generateKey();
-                enccipher = Cipher.getInstance(cipherTransformation);
-                deccipher = Cipher.getInstance(cipherTransformation);
-                enccipher.init(Cipher.ENCRYPT_MODE, key);
-                final byte[] ivp = enccipher.getIV();
-                deccipher.init(Cipher.DECRYPT_MODE, key, ivp == null ? null : new IvParameterSpec(ivp));
-            } catch (GeneralSecurityException e) {
-                enccipher = null;
-                deccipher = null;
-                throw e;
-            }
-        }
-    }
-
     private OutputStream createOutputStream(File file) throws IOException {
         OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
         if (cipherTransformation != null) {
             try {
-                initCiphers();
+                if (ciphers == null) {
+                    ciphers = new CipherPair(cipherTransformation);
+                }
             } catch (GeneralSecurityException e) {
                 throw new IOException(e.getMessage(), e);
             }
-            out = new CipherOutputStream(out, enccipher) {
+            out = new CipherOutputStream(out, ciphers.getEncryptor()) {
                 boolean closed;
                 public void close() throws IOException {
                     if (!closed) {
@@ -679,7 +649,7 @@ public class CachedOutputStream extends 
     private InputStream createInputStream(File file) throws IOException {
         InputStream in = new FileInputStream(file);
         if (cipherTransformation != null) {
-            in = new CipherInputStream(in, deccipher) {
+            in = new CipherInputStream(in, ciphers.getDecryptor()) {
                 boolean closed;
                 public void close() throws IOException {
                     if (!closed) {

Modified: cxf/trunk/api/src/main/java/org/apache/cxf/io/CachedWriter.java
URL: http://svn.apache.org/viewvc/cxf/trunk/api/src/main/java/org/apache/cxf/io/CachedWriter.java?rev=1441370&r1=1441369&r2=1441370&view=diff
==============================================================================
--- cxf/trunk/api/src/main/java/org/apache/cxf/io/CachedWriter.java (original)
+++ cxf/trunk/api/src/main/java/org/apache/cxf/io/CachedWriter.java Fri Feb  1 10:11:29 2013
@@ -19,6 +19,7 @@
 
 package org.apache.cxf.io;
 
+import java.io.BufferedOutputStream;
 import java.io.CharArrayReader;
 import java.io.CharArrayWriter;
 import java.io.File;
@@ -26,14 +27,22 @@ import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.InputStreamReader;
+import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.Reader;
 import java.io.Writer;
+import java.security.GeneralSecurityException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
+import javax.crypto.CipherInputStream;
+import javax.crypto.CipherOutputStream;
+
+import org.apache.cxf.Bus;
+import org.apache.cxf.BusFactory;
 import org.apache.cxf.common.util.SystemPropertyAction;
 import org.apache.cxf.helpers.FileUtils;
 import org.apache.cxf.helpers.IOUtils;
@@ -42,9 +51,14 @@ public class CachedWriter extends Writer
     private static final File DEFAULT_TEMP_DIR;
     private static int defaultThreshold;
     private static long defaultMaxSize;
+    private static String defaultCipherTransformation;
     static {
         
-        String s = SystemPropertyAction.getPropertyOrNull("org.apache.cxf.io.CachedWriter.OutputDirectory");
+        String s = SystemPropertyAction.getPropertyOrNull("org.apache.cxf.io.CachedOutputStream.OutputDirectory");
+        if (s == null) {
+            // lookup the deprecated property
+            s = SystemPropertyAction.getPropertyOrNull("org.apache.cxf.io.CachedWriter.OutputDirectory");
+        }
         if (s != null) {
             File f = new File(s);
             if (f.exists() && f.isDirectory()) {
@@ -58,6 +72,7 @@ public class CachedWriter extends Writer
 
         setDefaultThreshold(-1);
         setDefaultMaxSize(-1);
+        setDefaultCipherTransformation(null);
     }
 
     protected boolean outputLocked;
@@ -74,6 +89,8 @@ public class CachedWriter extends Writer
     private File tempFile;
     private File outputDir = DEFAULT_TEMP_DIR;
     private boolean allowDeleteOfFile = true;
+    private String cipherTransformation = defaultCipherTransformation;
+    private CipherPair ciphers;
 
     private List<CachedWriterCallback> callbacks;
     
@@ -91,13 +108,39 @@ public class CachedWriter extends Writer
     
 
     public CachedWriter() {
-        currentStream = new LoadingCharArrayWriter();
+        this(defaultThreshold);
+
         inmem = true;
     }
 
     public CachedWriter(long threshold) {
-        this();
-        this.threshold = threshold; 
+        this.threshold = threshold;
+        currentStream = new LoadingCharArrayWriter();
+        inmem = true;
+        readBusProperties();
+    }
+
+    private void readBusProperties() {
+        Bus b = BusFactory.getThreadDefaultBus(false);
+        if (b != null) {
+            String v = getBusProperty(b, "bus.io.CachedOutputStream.Threshold", null);
+            if (v != null && threshold == defaultThreshold) {
+                threshold = Integer.parseInt(v);
+            }
+            v = getBusProperty(b, "bus.io.CachedOutputStream.MaxSize", null);
+            if (v != null) {
+                maxSize = Integer.parseInt(v);
+            }
+            v = getBusProperty(b, "bus.io.CachedOutputStream.CipherTransformation", null);
+            if (v != null) {
+                cipherTransformation = v;
+            }
+        }
+    }
+
+    private static String getBusProperty(Bus b, String key, String dflt) {
+        String v = (String)b.getProperty(key);
+        return v != null ? v : dflt;
     }
 
     public void holdTempFile() {
@@ -234,8 +277,8 @@ public class CachedWriter extends Writer
                 // read the file
                 currentStream.close();
                 if (copyOldContent) {
-                    FileInputStream fin = new FileInputStream(tempFile);
-                    IOUtils.copyAndCloseInput(new InputStreamReader(fin, "UTF-8"), out);
+                    InputStreamReader fin = createInputStreamReader(tempFile);
+                    IOUtils.copyAndCloseInput(fin, out);
                 }
                 streamList.remove(currentStream);
                 deleteTempFile();
@@ -263,7 +306,7 @@ public class CachedWriter extends Writer
             // read the file
             Reader fin = null;
             try {
-                fin = new InputStreamReader(new FileInputStream(tempFile), "UTF-8");
+                fin = createInputStreamReader(tempFile);
                 CharArrayWriter out = new CharArrayWriter((int)tempFile.length());
                 char bytes[] = new char[1024];
                 int x = fin.read(bytes);
@@ -292,7 +335,7 @@ public class CachedWriter extends Writer
             // read the file
             Reader fin = null;
             try {
-                fin = new InputStreamReader(new FileInputStream(tempFile), "UTF-8");
+                fin = createInputStreamReader(tempFile);
                 char bytes[] = new char[1024];
                 int x = fin.read(bytes);
                 while (x != -1) {
@@ -327,7 +370,7 @@ public class CachedWriter extends Writer
             // read the file
             Reader fin = null;
             try {
-                fin = new InputStreamReader(new FileInputStream(tempFile), "UTF-8");
+                fin = createInputStreamReader(tempFile);
                 char bytes[] = new char[1024];
                 long x = fin.read(bytes);
                 while (x != -1) {
@@ -362,10 +405,8 @@ public class CachedWriter extends Writer
             }
         } else {
             // read the file
-            FileInputStream fin = new FileInputStream(tempFile);
-            Reader r = null;
+            Reader r = createInputStreamReader(tempFile);
             try {
-                r = new InputStreamReader(fin, "UTF-8");
                 char chars[] = new char[1024];
                 int x = r.read(chars);
                 while (x != -1) {
@@ -438,8 +479,7 @@ public class CachedWriter extends Writer
             } else {
                 tempFile = FileUtils.createTempFile("cos", "tmp", outputDir, false);
             }
-            FileOutputStream fout = new FileOutputStream(tempFile);
-            currentStream = new OutputStreamWriter(fout, "UTF-8");
+            currentStream = createOutputStreamWriter(tempFile);
             bout.writeTo(currentStream);
             inmem = false;
             streamList.add(currentStream);
@@ -471,7 +511,7 @@ public class CachedWriter extends Writer
             }
         } else {
             try {
-                FileInputStream fileInputStream = new FileInputStream(tempFile) {
+                InputStream fileInputStream = new FileInputStream(tempFile) {
                     boolean closed;
                     public void close() throws IOException {
                         if (!closed) {
@@ -482,6 +522,17 @@ public class CachedWriter extends Writer
                     }
                 };
                 streamList.add(fileInputStream);
+                if (cipherTransformation != null) {
+                    fileInputStream = new CipherInputStream(fileInputStream, ciphers.getDecryptor())
{
+                        boolean closed;
+                        public void close() throws IOException {
+                            if (!closed) {
+                                super.close();
+                                closed = true;
+                            }
+                        }
+                    };
+                }
                 return new InputStreamReader(fileInputStream, "UTF-8");
             } catch (FileNotFoundException e) {
                 throw new IOException("Cached file was deleted, " + e.toString());
@@ -523,19 +574,29 @@ public class CachedWriter extends Writer
     public void setMaxSize(long maxSize) {
         this.maxSize = maxSize;
     }
+
+    public void setCipherTransformation(String cipherTransformation) {
+        this.cipherTransformation = cipherTransformation;
+    }
     
     public static void setDefaultMaxSize(long l) {
         if (l == -1) {
-            String s = System.getProperty("org.apache.cxf.io.CachedWriter.MaxSize",
-                    "-1");
+            String s = System.getProperty("org.apache.cxf.io.CachedOutputStream.MaxSize");
+            if (s == null) {
+                // lookup the deprecated property
+                s = System.getProperty("org.apache.cxf.io.CachedWriter.MaxSize", "-1");
+            }
             l = Long.parseLong(s);
         }
         defaultMaxSize = l;
     }
     public static void setDefaultThreshold(int i) {
         if (i == -1) {
-            String s = SystemPropertyAction.getProperty("org.apache.cxf.io.CachedWriter.Threshold",
-                "-1");
+            String s = SystemPropertyAction.getProperty("org.apache.cxf.io.CachedOutputStream.Threshold");
+            if (s == null) {
+                // lookup the deprecated property
+                s = SystemPropertyAction.getProperty("org.apache.cxf.io.CachedWriter.Threshold",
"-1");
+            }
             i = Integer.parseInt(s);
             if (i <= 0) {
                 i = 64 * 1024;
@@ -545,4 +606,50 @@ public class CachedWriter extends Writer
         
     }
 
+    public static void setDefaultCipherTransformation(String n) {
+        if (n == null) {
+            n = SystemPropertyAction.getPropertyOrNull("org.apache.cxf.io.CachedOutputStream.CipherTransformation");
+        }
+        defaultCipherTransformation = n;
+    }
+
+    private OutputStreamWriter createOutputStreamWriter(File file) throws IOException {
+        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
+        if (cipherTransformation != null) {
+            try {
+                if (ciphers == null) {
+                    ciphers = new CipherPair(cipherTransformation);
+                }
+            } catch (GeneralSecurityException e) {
+                throw new IOException(e.getMessage(), e);
+            }
+            out = new CipherOutputStream(out, ciphers.getEncryptor()) {
+                boolean closed;
+                public void close() throws IOException {
+                    if (!closed) {
+                        super.close();
+                        closed = true;
+                    }
+                }
+            };
+        }
+        return new OutputStreamWriter(out, "utf-8");
+    }
+
+    private InputStreamReader createInputStreamReader(File file) throws IOException {
+        InputStream in = new FileInputStream(file);
+        if (cipherTransformation != null) {
+            in = new CipherInputStream(in, ciphers.getDecryptor()) {
+                boolean closed;
+                public void close() throws IOException {
+                    if (!closed) {
+                        super.close();
+                        closed = true;
+                    }
+                }
+            };
+        }
+        return new InputStreamReader(in, "utf-8");
+    }
+
 }

Added: cxf/trunk/api/src/main/java/org/apache/cxf/io/CipherPair.java
URL: http://svn.apache.org/viewvc/cxf/trunk/api/src/main/java/org/apache/cxf/io/CipherPair.java?rev=1441370&view=auto
==============================================================================
--- cxf/trunk/api/src/main/java/org/apache/cxf/io/CipherPair.java (added)
+++ cxf/trunk/api/src/main/java/org/apache/cxf/io/CipherPair.java Fri Feb  1 10:11:29 2013
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.io;
+
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.SecureRandom;
+
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.spec.IvParameterSpec;
+
+/**
+ * A class to hold a pair of encryption and decryption ciphers.
+ */
+public class CipherPair {
+    private String transformation;
+    private Cipher enccipher;
+    private Cipher deccipher;
+    
+    public CipherPair(String transformation) throws GeneralSecurityException {
+        this.transformation = transformation;
+        
+        int d = transformation.indexOf('/');
+        String a;
+        if (d > 0) {
+            a = transformation.substring(0, d);
+        } else {
+            a = transformation;
+        }
+        try {
+            KeyGenerator keygen = KeyGenerator.getInstance(a);
+            keygen.init(new SecureRandom());
+            Key key = keygen.generateKey();
+            enccipher = Cipher.getInstance(transformation);
+            deccipher = Cipher.getInstance(transformation);
+            enccipher.init(Cipher.ENCRYPT_MODE, key);
+            final byte[] ivp = enccipher.getIV();
+            deccipher.init(Cipher.DECRYPT_MODE, key, ivp == null ? null : new IvParameterSpec(ivp));
+        } catch (GeneralSecurityException e) {
+            enccipher = null;
+            deccipher = null;
+            throw e;
+        }
+    }
+    
+    public String getTransformation() {
+        return transformation;
+    }
+    
+    public Cipher getEncryptor() {
+        return enccipher;
+    }
+    
+    public Cipher getDecryptor() {
+        return deccipher;
+    }
+}

Modified: cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedOutputStreamTest.java
URL: http://svn.apache.org/viewvc/cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedOutputStreamTest.java?rev=1441370&r1=1441369&r2=1441370&view=diff
==============================================================================
--- cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedOutputStreamTest.java (original)
+++ cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedOutputStreamTest.java Fri Feb  1 10:11:29
2013
@@ -20,184 +20,62 @@ package org.apache.cxf.io;
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
-import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 
-import org.apache.cxf.Bus;
-import org.apache.cxf.BusFactory;
-import org.easymock.EasyMock;
-import org.easymock.IMocksControl;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class CachedOutputStreamTest extends Assert {    
+public class CachedOutputStreamTest extends CachedStreamTestBase {
     
-    @Test
-    public void testResetOut() throws IOException {
-        CachedOutputStream cos = new CachedOutputStream();        
-        String result = initTestData(16);
-        cos.write(result.getBytes());
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        cos.resetOut(out, true);
-        String test = out.toString();        
-        assertEquals("The test stream content isn't same ", test , result);
-        cos.close();
+    @Override
+    protected void reloadDefaultProperties() {
+        CachedOutputStream.setDefaultThreshold(-1);
+        CachedOutputStream.setDefaultMaxSize(-1);
+        CachedOutputStream.setDefaultCipherTransformation(null);
     }
     
-    @Test
-    public void testDeleteTmpFile() throws IOException {
-        CachedOutputStream cos = new CachedOutputStream();        
-        //ensure output data size larger then 64k which will generate tmp file
-        String result = initTestData(65);
-        cos.write(result.getBytes());
-        //assert tmp file is generated
-        File tempFile = cos.getTempFile();
-        assertNotNull(tempFile);
-        assertTrue(tempFile.exists());
-        cos.close();
-        //assert tmp file is deleted after close the CachedOutputStream
-        assertFalse(tempFile.exists());
+    @Override
+    protected Object createCache() {
+        return new CachedOutputStream();
     }
-
-    @Test
-    public void testDeleteTmpFile2() throws IOException {
-        CachedOutputStream cos = new CachedOutputStream();        
-        //ensure output data size larger then 64k which will generate tmp file
-        String result = initTestData(65);
-        cos.write(result.getBytes());
-        //assert tmp file is generated
-        File tempFile = cos.getTempFile();
-        assertNotNull(tempFile);
-        assertTrue(tempFile.exists());
-        InputStream in = cos.getInputStream();
-        cos.close();
-        //assert tmp file is not deleted when the input stream is open
-        assertTrue(tempFile.exists());
-        in.close();
-        //assert tmp file is deleted after the input stream is closed
-        assertFalse(tempFile.exists());
+    
+    @Override
+    protected Object createCache(long threshold) {
+        return createCache(threshold, null);
     }
-
-    @Test
-    public void testEncryptAndDecryptWithDeleteOnClose() throws IOException {
+    
+    @Override
+    protected Object createCache(long threshold, String transformation) {
         CachedOutputStream cos = new CachedOutputStream();
-        cos.setThreshold(4);
-        // need a 8-bit cipher so that all bytes are flushed when the stream is flushed.
-        cos.setCipherTransformation("RC4");
-        
-        final String text = "Hello Secret World!";
-        cos.write(text.getBytes("UTF-8"));
-        cos.flush();
-        
-        File tmpfile = cos.getTempFile();
-        assertNotNull(tmpfile);
-        
-        final String enctext = readFromStream(new FileInputStream(tmpfile));
-        assertFalse("text is not encoded", text.equals(enctext));
-
-        InputStream fin = cos.getInputStream();
-
-        assertTrue("file is deleted", tmpfile.exists());
-        
-        final String dectext = readFromStream(fin);
-        assertEquals("text is not decoded correctly", text, dectext);
-
-        // the file is deleted when cos is closed while all the associated inputs are closed
-        assertTrue("file is deleted", tmpfile.exists());
-        cos.close();
-        assertFalse("file is not deleted", tmpfile.exists());
+        cos.setThreshold(threshold);
+        cos.setCipherTransformation(transformation);
+        return cos;
     }
-
-    @Test
-    public void testEncryptAndDecryptWithDeleteOnInClose() throws IOException {
-        CachedOutputStream cos = new CachedOutputStream();
-        cos.setThreshold(4);
-        // need a 8-bit cipher so that all bytes are flushed when the stream is flushed.
-        cos.setCipherTransformation("RC4");
-        
-        final String text = "Hello Secret World!";
-        cos.write(text.getBytes("UTF-8"));
+    
+    @Override
+    protected String getResetOutValue(String result, Object cache) throws IOException {
+        CachedOutputStream cos = (CachedOutputStream)cache;
+        cos.write(result.getBytes());
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        cos.resetOut(out, true);
+        return out.toString();        
+    }
+    
+    @Override
+    protected File getTmpFile(String result, Object cache) throws IOException {
+        CachedOutputStream cos = (CachedOutputStream)cache;
+        cos.write(result.getBytes("utf-8"));
         cos.flush();
-        
-        File tmpfile = cos.getTempFile();
-        assertNotNull(tmpfile);
-        
-        final String enctext = readFromStream(new FileInputStream(tmpfile));
-        assertFalse("text is not encoded", text.equals(enctext));
-
-        InputStream fin = cos.getInputStream();
-
-        cos.close();
-        assertTrue("file is deleted", tmpfile.exists());
-        
-        // the file is deleted when cos is closed while all the associated inputs are closed
-        final String dectext = readFromStream(fin);
-        assertEquals("text is not decoded correctly", text, dectext);
-        assertFalse("file is not deleted", tmpfile.exists());
+        return cos.getTempFile();
     }
 
-    @Test
-    public void testUseBusProps() throws Exception {
-        Bus oldbus = BusFactory.getThreadDefaultBus(false); 
-        try {
-            CachedOutputStream cos = new CachedOutputStream(64);
-            cos.write("Hello World!".getBytes());
-            cos.flush();
-            assertNull("expects no tmp file", cos.getTempFile());
-            cos.close();
-            
-            IMocksControl control = EasyMock.createControl();
-            
-            Bus b = control.createMock(Bus.class);
-            EasyMock.expect(b.getProperty("bus.io.CachedOutputStream.Threshold")).andReturn("4");
-            EasyMock.expect(b.getProperty("bus.io.CachedOutputStream.MaxSize")).andReturn(null);
-            EasyMock.expect(b.getProperty("bus.io.CachedOutputStream.CipherTransformation")).andReturn(null);
-        
-            BusFactory.setThreadDefaultBus(b);
-            
-            control.replay();
-
-            cos = new CachedOutputStream();
-            cos.write("Hello World!".getBytes());
-            cos.flush();
-            assertNotNull("expects a tmp file", cos.getTempFile());
-            cos.close();
-            
-            control.verify();
-        } finally {
-            BusFactory.setThreadDefaultBus(oldbus);
-        }
-    }
-    
-    private static String readFromStream(InputStream is) throws IOException {
-        ByteArrayOutputStream buf = new ByteArrayOutputStream();
-        try {
-            byte[] b = new byte[100];
-            for (;;) {
-                int n = is.read(b, 0, b.length);
-                if (n < 0) {
-                    break;
-                }
-                buf.write(b, 0, n);
-            }
-        } finally {
-            is.close();
-        }
-        return new String(buf.toByteArray(), "UTF-8");
-    }
-    
-    String initTestData(int packetSize) {
-        String temp = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+?><[]/0123456789";
-        String result = new String();
-        for (int i = 0; i <  1024 * packetSize / temp.length(); i++) {
-            result = result + temp;
-        }
-        return result;
+    @Override
+    protected Object getInputStreamObject(Object cache) throws IOException {
+        return ((CachedOutputStream)cache).getInputStream();
     }
     
-
+    @Override
+    protected String readFromStreamObject(Object obj) throws IOException {
+        return readFromStream((InputStream)obj);
+    }
 }
     
    

Added: cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedStreamTestBase.java
URL: http://svn.apache.org/viewvc/cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedStreamTestBase.java?rev=1441370&view=auto
==============================================================================
--- cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedStreamTestBase.java (added)
+++ cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedStreamTestBase.java Fri Feb  1 10:11:29
2013
@@ -0,0 +1,250 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.io;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+
+import org.apache.cxf.Bus;
+import org.apache.cxf.BusFactory;
+import org.easymock.EasyMock;
+import org.easymock.IMocksControl;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public abstract class CachedStreamTestBase extends Assert {
+    protected abstract void reloadDefaultProperties();
+    protected abstract Object createCache();
+    protected abstract Object createCache(long threshold);
+    protected abstract Object createCache(long threshold, String transformation);
+    protected abstract String getResetOutValue(String result, Object cache) throws IOException;
+    protected abstract File getTmpFile(String result, Object cache) throws IOException;
+    protected abstract Object getInputStreamObject(Object cache) throws IOException;
+    protected abstract String readFromStreamObject(Object cache) throws IOException;
+    
+    @Test
+    public void testResetOut() throws IOException {
+        String result = initTestData(16);
+        Object cache = createCache();
+        String test = getResetOutValue(result, cache);
+        assertEquals("The test stream content isn't same ", test , result);
+        close(cache);
+    }
+    
+    @Test
+    public void testDeleteTmpFile() throws IOException {
+        Object cache = createCache();
+        //ensure output data size larger then 64k which will generate tmp file
+        String result = initTestData(65);
+        File tempFile = getTmpFile(result, cache);
+        assertNotNull(tempFile);
+        //assert tmp file is generated
+        assertTrue(tempFile.exists());
+        close(cache);
+        //assert tmp file is deleted after close the CachedOutputStream
+        assertFalse(tempFile.exists());
+    }
+
+    @Test
+    public void testDeleteTmpFile2() throws IOException {
+        Object cache = createCache();
+        //ensure output data size larger then 64k which will generate tmp file
+        String result = initTestData(65);
+        File tempFile = getTmpFile(result, cache);
+        assertNotNull(tempFile);
+        //assert tmp file is generated
+        assertTrue(tempFile.exists());
+        Object in = getInputStreamObject(cache);
+        close(cache);
+        //assert tmp file is not deleted when the input stream is open
+        assertTrue(tempFile.exists());
+        close(in);
+        //assert tmp file is deleted after the input stream is closed
+        assertFalse(tempFile.exists());
+    }
+    
+    @Test
+    public void testEncryptAndDecryptWithDeleteOnClose() throws IOException {
+        // need a 8-bit cipher so that all bytes are flushed when the stream is flushed.
+        Object cache = createCache(4, "RC4");
+        final String text = "Hello Secret World!";
+        File tmpfile = getTmpFile(text, cache);
+        assertNotNull(tmpfile);
+
+        final String enctext = readFromStream(new FileInputStream(tmpfile));
+        assertFalse("text is not encoded", text.equals(enctext));
+
+        Object fin = getInputStreamObject(cache);
+
+        assertTrue("file is deleted", tmpfile.exists());
+        
+        final String dectext = readFromStreamObject(fin);
+        assertEquals("text is not decoded correctly", text, dectext);
+
+        // the file is deleted when cos is closed while all the associated inputs are closed
+        assertTrue("file is deleted", tmpfile.exists());
+        close(cache);
+        assertFalse("file is not deleted", tmpfile.exists());
+    }
+
+    @Test
+    public void testEncryptAndDecryptWithDeleteOnInClose() throws IOException {
+        // need a 8-bit cipher so that all bytes are flushed when the stream is flushed.
+        Object cache = createCache(4, "RC4");
+        final String text = "Hello Secret World!";
+        File tmpfile = getTmpFile(text, cache);
+        assertNotNull(tmpfile);
+        
+        final String enctext = readFromStream(new FileInputStream(tmpfile));
+        assertFalse("text is not encoded", text.equals(enctext));
+
+        Object fin = getInputStreamObject(cache);
+
+        close(cache);
+        assertTrue("file is deleted", tmpfile.exists());
+        
+        // the file is deleted when cos is closed while all the associated inputs are closed
+        final String dectext = readFromStreamObject(fin);
+        assertEquals("text is not decoded correctly", text, dectext);
+        assertFalse("file is not deleted", tmpfile.exists());
+    }
+
+
+    @Test
+    public void testUseSysProps() throws Exception {
+        String old = System.getProperty("org.apache.cxf.io.CachedOutputStream.Threshold");
+        try {
+            System.clearProperty("org.apache.cxf.io.CachedOutputStream.Threshold");
+            reloadDefaultProperties();
+            Object cache = createCache();
+            File tmpfile = getTmpFile("Hello World!", cache);
+            assertNull("expects no tmp file", tmpfile);
+            close(cache);
+            
+            System.setProperty("org.apache.cxf.io.CachedOutputStream.Threshold", "4");
+            reloadDefaultProperties();
+            cache = createCache();
+            tmpfile = getTmpFile("Hello World!", cache);
+            assertNotNull("expects a tmp file", tmpfile);
+            assertTrue("expects a tmp file", tmpfile.exists());
+            close(cache);
+            assertFalse("expects no tmp file", tmpfile.exists());
+        } finally {
+            if (old != null) {
+                System.setProperty("org.apache.cxf.io.CachedOutputStream.Threshold", old);
+            }
+        }
+    }
+
+
+    @Test
+    public void testUseBusProps() throws Exception {
+        Bus oldbus = BusFactory.getThreadDefaultBus(false); 
+        try {
+            Object cache = createCache(64);
+            File tmpfile = getTmpFile("Hello World!", cache);
+            assertNull("expects no tmp file", tmpfile);
+            close(cache);
+            
+            IMocksControl control = EasyMock.createControl();
+            
+            Bus b = control.createMock(Bus.class);
+            EasyMock.expect(b.getProperty("bus.io.CachedOutputStream.Threshold")).andReturn("4");
+            EasyMock.expect(b.getProperty("bus.io.CachedOutputStream.MaxSize")).andReturn(null);
+            EasyMock.expect(b.getProperty("bus.io.CachedOutputStream.CipherTransformation")).andReturn(null);
+        
+            BusFactory.setThreadDefaultBus(b);
+            
+            control.replay();
+
+            cache = createCache();
+            tmpfile = getTmpFile("Hello World!", cache);
+            assertNotNull("expects a tmp file", tmpfile);
+            assertTrue("expects a tmp file", tmpfile.exists());
+            close(cache);
+            assertFalse("expects no tmp file", tmpfile.exists());
+            
+            control.verify();
+        } finally {
+            BusFactory.setThreadDefaultBus(oldbus);
+        }
+    }
+    
+    private static void close(Object obj) throws IOException {
+        if (obj instanceof CachedOutputStream) {
+            ((CachedOutputStream)obj).close();
+        } else if (obj instanceof CachedWriter) {
+            ((CachedWriter)obj).close();
+        } else if (obj instanceof InputStream) {
+            ((InputStream)obj).close();
+        } else if (obj instanceof Reader) {
+            ((Reader)obj).close();
+        }
+    }
+
+    protected static String readFromStream(InputStream is) throws IOException {
+        ByteArrayOutputStream buf = new ByteArrayOutputStream();
+        try {
+            byte[] b = new byte[100];
+            for (;;) {
+                int n = is.read(b, 0, b.length);
+                if (n < 0) {
+                    break;
+                }
+                buf.write(b, 0, n);
+            }
+        } finally {
+            is.close();
+        }
+        return new String(buf.toByteArray(), "UTF-8");
+    }
+ 
+    protected static String readFromReader(Reader is) throws IOException {
+        StringBuffer buf = new StringBuffer();
+        try {
+            char[] b = new char[100];
+            for (;;) {
+                int n = is.read(b, 0, b.length);
+                if (n < 0) {
+                    break;
+                }
+                buf.append(b, 0, n);
+            }
+        } finally {
+            is.close();
+        }
+        return buf.toString();
+    }
+    
+    private static String initTestData(int packetSize) {
+        String temp = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+?><[]/0123456789";
+        String result = new String();
+        for (int i = 0; i <  1024 * packetSize / temp.length(); i++) {
+            result = result + temp;
+        }
+        return result;
+    }
+}
+    
+   

Propchange: cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedStreamTestBase.java
------------------------------------------------------------------------------
    svn:executable = *

Modified: cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedWriterTest.java
URL: http://svn.apache.org/viewvc/cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedWriterTest.java?rev=1441370&r1=1441369&r2=1441370&view=diff
==============================================================================
--- cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedWriterTest.java (original)
+++ cxf/trunk/api/src/test/java/org/apache/cxf/io/CachedWriterTest.java Fri Feb  1 10:11:29
2013
@@ -23,67 +23,58 @@ import java.io.IOException;
 import java.io.Reader;
 import java.io.StringWriter;
 
-import org.junit.Assert;
-import org.junit.Test;
+public class CachedWriterTest extends CachedStreamTestBase {
+    @Override
+    protected void reloadDefaultProperties() {
+        CachedWriter.setDefaultThreshold(-1);
+        CachedWriter.setDefaultMaxSize(-1);
+        CachedWriter.setDefaultCipherTransformation(null);
+    }
 
-public class CachedWriterTest extends Assert {    
+    @Override
+    protected Object createCache() {
+        return new CachedWriter();
+    }
+    
+    @Override
+    protected Object createCache(long threshold) {
+        return createCache(threshold, null);
+    }
     
-    @Test
-    public void testResetOut() throws IOException {
-        CachedWriter cos = new CachedWriter();        
-        String result = initTestData(16);
+    @Override
+    protected Object createCache(long threshold, String transformation) {
+        CachedWriter cos = new CachedWriter();
+        cos.setThreshold(threshold);
+        cos.setCipherTransformation(transformation);
+        return cos;
+    }
+    
+    @Override
+    protected String getResetOutValue(String result, Object cache) throws IOException {
+        CachedWriter cos = (CachedWriter)cache;
         cos.write(result);
         StringWriter out = new StringWriter();
         cos.resetOut(out, true);
-        String test = out.toString();
-        assertEquals("The test stream content isn't same ", test , result);
-        cos.close();
+        return out.toString();
     }
     
-    @Test
-    public void testDeleteTmpFile() throws IOException {
-        CachedWriter cos = new CachedWriter();        
-        //ensure output data size larger then 64k which will generate tmp file
-        String result = initTestData(65);
+    @Override
+    protected File getTmpFile(String result, Object cache) throws IOException {
+        CachedWriter cos = (CachedWriter)cache;
         cos.write(result);
-        //assert tmp file is generated
-        File tempFile = cos.getTempFile();
-        assertNotNull(tempFile);
-        assertTrue(tempFile.exists());
-        cos.close();
-        //assert tmp file is deleted after close the CachedOutputStream
-        assertFalse(tempFile.exists());
+        cos.flush();
+        return cos.getTempFile();
     }
 
-    @Test
-    public void testDeleteTmpFile2() throws IOException {
-        CachedWriter cos = new CachedWriter();
-        //ensure output data size larger then 64k which will generate tmp file
-        String result = initTestData(65);
-        cos.write(result);
-        //assert tmp file is generated
-        File tempFile = cos.getTempFile();
-        assertNotNull(tempFile);
-        assertTrue(tempFile.exists());
-        Reader in = cos.getReader();
-        cos.close();
-        //assert tmp file is not deleted when the reader is open
-        assertTrue(tempFile.exists());
-        in.close();
-        //assert tmp file is deleted after the reader is closed
-        assertFalse(tempFile.exists());
+    @Override
+    protected Object getInputStreamObject(Object cache) throws IOException {
+        return ((CachedWriter)cache).getReader();
     }
 
-    String initTestData(int packetSize) {
-        String temp = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+?><[]/0123456789";
-        String result = new String();
-        for (int i = 0; i <  1024 * packetSize / temp.length(); i++) {
-            result = result + temp;
-        }
-        return result;
+    @Override
+    protected String readFromStreamObject(Object obj) throws IOException {
+        return readFromReader((Reader)obj);
     }
-    
-
 }
     
    



Mime
View raw message