[infinispan-commits] Infinispan SVN: r186 - in trunk/cachestore/s3: src/main and 4 other directories.

infinispan-commits at lists.jboss.org infinispan-commits at lists.jboss.org
Tue Apr 28 07:56:08 EDT 2009


Author: adriancole
Date: 2009-04-28 07:56:08 -0400 (Tue, 28 Apr 2009)
New Revision: 186

Added:
   trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/jclouds/
   trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/jclouds/JCloudsBucket.java
   trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/jclouds/JCloudsConnection.java
   trunk/cachestore/s3/src/main/resources/
   trunk/cachestore/s3/src/main/resources/jclouds.properties
Modified:
   trunk/cachestore/s3/pom.xml
   trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/S3CacheStore.java
   trunk/cachestore/s3/src/test/java/org/infinispan/loader/s3/S3CacheStoreIntegrationTest.java
Log:
ISPN-28 added support for jclouds cachestore

Modified: trunk/cachestore/s3/pom.xml
===================================================================
--- trunk/cachestore/s3/pom.xml	2009-04-28 09:31:17 UTC (rev 185)
+++ trunk/cachestore/s3/pom.xml	2009-04-28 11:56:08 UTC (rev 186)
@@ -14,6 +14,11 @@
     <name>Infinispan Amazon S3 CacheStore</name>
     <description>Infinispan Amazon S3 CacheStore module</description>
 
+    <properties>
+        <jclouds.aws.accesskeyid></jclouds.aws.accesskeyid>
+        <jclouds.aws.secretaccesskey></jclouds.aws.secretaccesskey>
+    </properties>
+
     <dependencies>
         <dependency>
             <groupId>${project-package}</groupId>
@@ -30,11 +35,51 @@
         </dependency>
 
         <dependency>
+            <groupId>org.jclouds</groupId>
+            <artifactId>jclouds-s3</artifactId>
+            <version>1.0-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>org.jclouds</groupId>
+            <artifactId>jclouds-s3nio</artifactId>
+            <version>1.0-SNAPSHOT</version>
+        </dependency>
+        
+        <dependency>
             <groupId>commons-io</groupId>
             <artifactId>commons-io</artifactId>
             <version>1.4</version>
             <scope>test</scope>
         </dependency>
     </dependencies>
+    <repositories>
+        <repository>
+            <id>jclouds</id>
+            <url>http://jclouds.googlecode.com/svn/trunk/repo</url>
+        </repository>
+    </repositories>
+    <build>
+        <plugins>
+            <plugin>
+               <groupId>org.apache.maven.plugins</groupId>
+               <artifactId>maven-surefire-plugin</artifactId>
+               <version>2.4.3</version>
+               <configuration>
+                 <forkMode>once</forkMode>
+                 <parallel>false</parallel>
+                    <systemProperties>
+                        <property>
+                            <name>jclouds.aws.accesskeyid</name>
+                            <value>${jclouds.aws.accesskeyid}</value>
+                        </property>
+                        <property>
+                            <name>jclouds.aws.secretaccesskey</name>
+                            <value>${jclouds.aws.secretaccesskey}</value>
+                        </property>
+                    </systemProperties>
+               </configuration>
+            </plugin>
+        </plugins>
+    </build>
 
 </project>

Modified: trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/S3CacheStore.java
===================================================================
--- trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/S3CacheStore.java	2009-04-28 09:31:17 UTC (rev 185)
+++ trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/S3CacheStore.java	2009-04-28 11:56:08 UTC (rev 186)
@@ -44,8 +44,7 @@
     * {@inheritDoc} This initializes the internal <tt>s3Connection</tt> to a default implementation
     */
    public void init(CacheLoaderConfig config, Cache cache, Marshaller m) {
-      throw new UnsupportedOperationException("no default implementation, yet");
-//        init(config, cache, m, null, null);
+        init(config, cache, m, null, null);
    }
 
    @Override

Added: trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/jclouds/JCloudsBucket.java
===================================================================
--- trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/jclouds/JCloudsBucket.java	                        (rev 0)
+++ trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/jclouds/JCloudsBucket.java	2009-04-28 11:56:08 UTC (rev 186)
@@ -0,0 +1,145 @@
+package org.infinispan.loader.s3.jclouds;
+
+import org.infinispan.loader.bucket.Bucket;
+import org.infinispan.loader.s3.S3ConnectionException;
+import org.jclouds.aws.s3.domain.S3Bucket;
+import org.jclouds.aws.s3.domain.S3Object;
+
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Future;
+
+/**
+ * A {@link org.jclouds.aws.s3.S3Connection jclouds} implementation of {@link org.infinispan.loader.s3.S3Bucket}.
+ * <p/>
+ * Tuning and configuration parameters can be overridden by creating <tt>jets3t.properties</tt> and adding it to your
+ * classpath.
+ *
+ * @author Adrian Cole
+ * @link http://jets3t.s3.amazonaws.com/toolkit/configuration.html
+ * @since 1.0
+ */
+public class JCloudsBucket implements org.infinispan.loader.s3.S3Bucket<S3Bucket, org.infinispan.loader.s3.jclouds.JCloudsConnection> {
+    private String name;
+
+    public void init(JCloudsConnection connection, S3Bucket bucket) {
+        this.connection = connection;
+        this.rootS3Bucket = bucket;
+        this.name = bucket.getName();
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    private JCloudsConnection connection;
+    protected S3Bucket rootS3Bucket;
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public Bucket get(String key) throws S3ConnectionException {
+        Bucket bucket = null;
+        InputStream is = null;
+        ObjectInputStream ois = null;
+
+        try {
+            S3Object s3Object = connection.getConnection().getObject(rootS3Bucket, key).get();
+            // it is possible that the object never existed. in this case, fall out.
+            if (s3Object != null && s3Object.getContent() != null) {
+                is = (InputStream) s3Object.getContent();
+                bucket = (Bucket) connection.marshaller.objectFromStream(is);
+                // TODO hack until we are sure the bucket has an immutable name
+                bucket.setBucketName(key);
+            }
+        } catch (Exception e) {
+            throw connection.convertToS3ConnectionException("Error while reading from object: " + key, e);
+        } finally {
+            safeClose(ois);
+            safeClose(is);
+        }
+        return bucket;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void remove(String key) throws S3ConnectionException {
+        try {
+            connection.getConnection().deleteObject(rootS3Bucket, key).get();
+        } catch (Exception ex) {
+            throw connection.convertToS3ConnectionException("Exception removing key " + key, ex);
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public Set<String> keySet() throws S3ConnectionException {
+        return connection.keysInBucket(rootS3Bucket);
+    }
+
+    public Set<Bucket> values() throws S3ConnectionException {
+        Set<Bucket> buckets = new HashSet<Bucket>();
+        for (String s : keySet()) {
+            Bucket bucket = get(s);
+            if (bucket != null)
+                buckets.add(bucket);
+        }
+        return buckets;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void clear() throws S3ConnectionException {
+        try {
+            List<Future<Boolean>> deletes = new ArrayList<Future<Boolean>>();
+            for (String key : keySet()) {
+                deletes.add(connection.getConnection().deleteObject(rootS3Bucket, key));
+            }
+            for (Future<Boolean> delete : deletes) {
+                if (!delete.get())
+                    throw new S3ConnectionException("could not delete entry");
+            }
+        } catch (Exception ex) {
+            throw connection.convertToS3ConnectionException("Exception clearing store", ex);
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void insert(Bucket b) throws S3ConnectionException {
+        try {
+            if (b.getEntries().isEmpty()) {
+                if (!connection.getConnection().deleteObject(rootS3Bucket, b.getBucketName()).get())
+                    throw new S3ConnectionException(String.format("Could not delete object [%2s] in s3bucket [%1s] ", rootS3Bucket.getName(), b.getBucketName()));
+            } else {
+                S3Object s3Object = new S3Object();
+                s3Object.setKey(b.getBucketName());
+                s3Object.setContent(connection.marshaller.objectToByteBuffer(b));
+                s3Object.setContentType("application/octet-string");
+                String id = connection.getConnection().addObject(rootS3Bucket, s3Object).get();
+                assert id != null : String.format("Should have received an id for entry %1s:%2s ", rootS3Bucket.getName(), b.getBucketName());
+            }
+        } catch (Exception ex) {
+            throw connection.convertToS3ConnectionException("Exception while saving bucket " + b, ex);
+        }
+    }
+
+    protected final void safeClose(InputStream stream) throws S3ConnectionException {
+        if (stream == null) return;
+        try {
+            stream.close();
+        } catch (Exception e) {
+            throw new S3ConnectionException("Problems closing input stream", e);
+        }
+    }
+
+}
\ No newline at end of file

Added: trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/jclouds/JCloudsConnection.java
===================================================================
--- trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/jclouds/JCloudsConnection.java	                        (rev 0)
+++ trunk/cachestore/s3/src/main/java/org/infinispan/loader/s3/jclouds/JCloudsConnection.java	2009-04-28 11:56:08 UTC (rev 186)
@@ -0,0 +1,144 @@
+package org.infinispan.loader.s3.jclouds;
+
+import org.infinispan.loader.s3.S3CacheStoreConfig;
+import org.infinispan.loader.s3.S3Connection;
+import org.infinispan.loader.s3.S3ConnectionException;
+import org.infinispan.marshall.Marshaller;
+import org.jclouds.aws.s3.S3ConnectionFactory;
+import org.jclouds.aws.s3.nio.config.S3HttpNioConnectionPoolClientModule;
+import org.jclouds.aws.s3.domain.S3Bucket;
+import org.jclouds.aws.s3.domain.S3Object;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+/**
+ * // TODO: Adrian: Document this!
+ *
+ * @author Adrian Cole
+ */
+public class JCloudsConnection implements S3Connection<org.jclouds.aws.s3.S3Connection, org.jclouds.aws.s3.domain.S3Bucket> {
+    protected org.jclouds.aws.s3.S3Connection s3Service;
+    protected Marshaller marshaller;
+
+    /**
+     * {@inheritDoc}
+     */
+    public void connect(S3CacheStoreConfig config, Marshaller m) throws S3ConnectionException {
+        //TODO max connections
+        //TODO proxy host/port
+        InputStream propertiesIS = null;
+        try {
+            propertiesIS = JCloudsConnection.class.getResourceAsStream("/jclouds.properties");
+            Properties properties = new Properties();
+            properties.load(propertiesIS);
+            if (!config.isSecure()) {
+                properties.put("jclouds.http.port", "80");
+                properties.put("jclouds.http.secure", "false");
+            }
+            if (!properties.containsKey("jclouds.aws.accesskeyid"))
+                properties.put("jclouds.aws.accesskeyid", config.getAwsAccessKey());
+            if (!properties.containsKey("jclouds.aws.secretaccesskey"))
+                properties.put("jclouds.aws.secretaccesskey", config.getAwsSecretKey());
+            this.s3Service = S3ConnectionFactory.getConnection(properties, new S3HttpNioConnectionPoolClientModule());
+            if (this.s3Service == null) {
+                throw new S3ConnectionException("Could not connect");
+            }
+
+        } catch (Exception ex) {
+            throw convertToS3ConnectionException("Exception connecting to s3", ex);
+        }
+        this.marshaller = m;
+    }
+
+    public org.jclouds.aws.s3.S3Connection getConnection() throws S3ConnectionException {
+        return s3Service;
+    }
+
+    /**
+     * @see //TODO org.jets3t.service.S3Service#getOrCreateBucket(String)
+     */
+    public org.jclouds.aws.s3.domain.S3Bucket verifyOrCreateBucket(String bucketName) throws S3ConnectionException {
+        try {
+            org.jclouds.aws.s3.domain.S3Bucket bucket = new org.jclouds.aws.s3.domain.S3Bucket();
+            bucket.setName(bucketName);
+            s3Service.createBucketIfNotExists(bucket).get();
+            return bucket;
+        } catch (Exception ex) {
+            throw convertToS3ConnectionException("Exception retrieving or creating s3 bucket " + bucketName, ex);
+        }
+    }
+
+    public void destroyBucket(String name) throws S3ConnectionException {
+        try {
+            org.jclouds.aws.s3.domain.S3Bucket bucket = new org.jclouds.aws.s3.domain.S3Bucket();
+            bucket.setName(name);
+            for (S3Object object : s3Service.getBucket(bucket).get().getContents()) {
+                s3Service.deleteObject(bucket, object.getKey());
+            }
+            s3Service.deleteBucket(bucket);
+        } catch (Exception ex) {
+            throw convertToS3ConnectionException("Exception removing s3 bucket " + name, ex);
+        }
+    }
+
+
+    Set<String> keysInBucket(S3Bucket bucket) throws S3ConnectionException {
+        try {
+            Set<String> keys = new HashSet<String>();
+            for (S3Object object : s3Service.getBucket(bucket).get().getContents()) {
+                keys.add(object.getKey());
+            }
+            return keys;
+        } catch (Exception ex) {
+            throw convertToS3ConnectionException("Exception while listing bucket " + bucket, ex);
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void copyBucket(String sourceBucket, String destinationBucket) throws S3ConnectionException {
+
+
+        Set<String> sourceKeys = null;
+        try {
+            S3Bucket source = new S3Bucket();
+            source.setName(sourceBucket);
+            source = s3Service.getBucket(source).get();
+            sourceKeys = keysInBucket(source);
+            S3Bucket dest = new S3Bucket();
+            dest.setName(destinationBucket);
+
+            for (String key : sourceKeys) {
+                try {
+                    S3Object object = new S3Object();
+                    object.setKey(key);
+                    s3Service.copyObject(source, object, dest, object).get();
+                } catch (Exception ex) {
+                    throw convertToS3ConnectionException("Exception while copying key " + key + " from bucket " + sourceBucket, ex);
+                }
+            }
+        } catch (Exception ex) {
+            throw convertToS3ConnectionException("Cannot access bucket " + sourceBucket, ex);
+        }
+
+    }
+
+
+    public void disconnect() {
+        try {
+            s3Service.close();
+        } catch (IOException e) {
+            e.printStackTrace();  // TODO: Adrian: Customise this generated block
+        }
+    }
+
+    S3ConnectionException convertToS3ConnectionException(String message, Exception caught) {
+        return (caught instanceof S3ConnectionException) ? (S3ConnectionException) caught :
+                new S3ConnectionException(message, caught);
+    }
+}

Added: trunk/cachestore/s3/src/main/resources/jclouds.properties
===================================================================
--- trunk/cachestore/s3/src/main/resources/jclouds.properties	                        (rev 0)
+++ trunk/cachestore/s3/src/main/resources/jclouds.properties	2009-04-28 11:56:08 UTC (rev 186)
@@ -0,0 +1,13 @@
+jclouds.http.address=s3.amazonaws.com
+jclouds.http.port=443
+jclouds.http.secure=true
+jclouds.http.pool.max_connection_reuse=75
+jclouds.http.pool.max_session_failures=2
+jclouds.http.pool.request_invoker_threads=1
+jclouds.http.pool.io_worker_threads=2
+jclouds.pool.max_connections=12
+jclouds.http.pool.max_connection_reuse=75
+jclouds.http.pool.max_session_failures=2
+jclouds.http.pool.request_invoker_threads=1
+jclouds.http.pool.io_worker_threads=2
+jclouds.pool.max_connections=12
\ No newline at end of file

Modified: trunk/cachestore/s3/src/test/java/org/infinispan/loader/s3/S3CacheStoreIntegrationTest.java
===================================================================
--- trunk/cachestore/s3/src/test/java/org/infinispan/loader/s3/S3CacheStoreIntegrationTest.java	2009-04-28 09:31:17 UTC (rev 185)
+++ trunk/cachestore/s3/src/test/java/org/infinispan/loader/s3/S3CacheStoreIntegrationTest.java	2009-04-28 11:56:08 UTC (rev 186)
@@ -7,16 +7,12 @@
 import org.infinispan.loader.BaseCacheStoreTest;
 import org.infinispan.loader.CacheLoaderException;
 import org.infinispan.loader.CacheStore;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.BeforeTest;
-import org.testng.annotations.Test;
+import org.infinispan.loader.s3.jclouds.JCloudsBucket;
+import org.infinispan.loader.s3.jclouds.JCloudsConnection;
+import static org.testng.Assert.assertEquals;
+import org.testng.annotations.*;
 
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
+import java.io.*;
 import java.util.HashSet;
 import java.util.Set;
 
@@ -25,154 +21,177 @@
  * @version $Id$
  * @since 4.0
  */
- at Test(groups = "unit", enabled = true, sequential = true, testName = "loader.s3.S3CacheStoreIntegrationTest")
+ at Test(groups = "unit", sequential = true, testName = "loader.s3.S3CacheStoreIntegrationTest")
 public class S3CacheStoreIntegrationTest extends BaseCacheStoreTest {
-   private String proxyHost;
-   private int proxyPort = -1;
-   private int maxConnections = 20;
-   private boolean isSecure = false;
-   private Class<? extends S3Connection> connectionClass;
-   private Class<? extends S3Bucket> bucketClass;
-   private String csBucket;
-   private String cs2Bucket;
-   private String accessKey;
-   private String secretKey;
+    private String proxyHost;
+    private int proxyPort = -1;
+    private int maxConnections = 20;
+    private boolean isSecure = false;
+    private Class<? extends S3Connection> connectionClass;
+    private Class<? extends S3Bucket> bucketClass;
+    private String csBucket;
+    private String cs2Bucket;
+    private String accessKey;
+    private String secretKey;
 
-   @BeforeTest(enabled = true)
-   public void initMockConnection() {
-      csBucket = "infinispantesting";
-      cs2Bucket = csBucket + "2";
-      accessKey = "dummyaccess";
-      secretKey = "dummysecret";
-      connectionClass = MockS3Connection.class;
-      bucketClass = MockS3Bucket.class;
-   }
+    private static final String sysAWSAccessKeyId = System
+            .getProperty("jclouds.aws.accesskeyid");
+    private static final String sysAWSSecretAccessKey = System
+            .getProperty("jclouds.aws.secretaccesskey");
 
-   protected CacheStore createCacheStore() throws Exception {
-      return createAndStartCacheStore(csBucket);
-   }
+    @BeforeTest
+    @Parameters({"jclouds.aws.accesskeyid", "jclouds.aws.secretaccesskey"})
+    protected void setUpClient(@Optional String AWSAccessKeyId,
+                               @Optional String AWSSecretAccessKey) throws Exception {
 
-   protected CacheStore createAnotherCacheStore() throws Exception {
-      return createAndStartCacheStore(cs2Bucket);
-   }
+        accessKey = (AWSAccessKeyId == null) ? sysAWSAccessKeyId : AWSAccessKeyId;
+        secretKey = (AWSSecretAccessKey == null) ? sysAWSSecretAccessKey : AWSSecretAccessKey;
 
-   private CacheStore createAndStartCacheStore(String bucket) throws Exception {
-      S3CacheStore cs = new S3CacheStore();
-      S3CacheStoreConfig cfg = new S3CacheStoreConfig();
-      cfg.setBucket(bucket);
-      cfg.setAwsAccessKey(accessKey);
-      cfg.setAwsSecretKey(secretKey);
-      cfg.setProxyHost(proxyHost);
-      cfg.setProxyPort(proxyPort);
-      cfg.setSecure(isSecure);
-      cfg.setMaxConnections(maxConnections);
-      cfg.setPurgeSynchronously(true); // for more accurate unit testing
-      cs.init(cfg, getCache(), getMarshaller(), connectionClass.newInstance(), bucketClass.newInstance());
-      cs.start();
-      return cs;
-   }
+        if (accessKey == null || accessKey.trim().equals("") ||
+                secretKey == null || secretKey.trim().equals("")) {
+            accessKey = "dummy";
+            secretKey = "dummy";
+            connectionClass = MockS3Connection.class;
+            bucketClass = MockS3Bucket.class;
+        } else {
+            connectionClass = JCloudsConnection.class;
+            bucketClass = JCloudsBucket.class;
+            proxyHost = "localhost";  // TODO  not yet used
+            proxyPort = 8888; // TODO  not yet used
+        }
+        csBucket = System.getProperty("user.name")
+                + "." + this.getClass().getName();
+        System.err.printf("accessKey: %1s, connectionClass: %2s, bucketClass: %3s, bucket: %4s%n", accessKey,
+                connectionClass, bucketClass, csBucket);
 
-   /*  Changes below are needed to support testing of multiple cache stores */
+        cs2Bucket = csBucket + "2";
+    }
 
-   protected CacheStore cs2;
+    protected CacheStore createCacheStore() throws Exception {
+        return createAndStartCacheStore(csBucket);
+    }
 
-   @BeforeMethod
-   @Override
-   public void setUp() throws Exception {
-      super.setUp();
-      cs.clear();
-      Set entries = cs.loadAll();
-      assert entries.size() == 0;
-      cs2 = createAnotherCacheStore();
-      cs2.clear();
-      entries = cs2.loadAll();
-      assert entries.size() == 0;
-   }
+    protected CacheStore createAnotherCacheStore() throws Exception {
+        return createAndStartCacheStore(cs2Bucket);
+    }
 
+    private CacheStore createAndStartCacheStore(String bucket) throws Exception {
+        S3CacheStore cs = new S3CacheStore();
+        S3CacheStoreConfig cfg = new S3CacheStoreConfig();
+        cfg.setBucket(bucket);
+        cfg.setAwsAccessKey(accessKey);
+        cfg.setAwsSecretKey(secretKey);
+        cfg.setProxyHost(proxyHost);
+        cfg.setProxyPort(proxyPort);
+        cfg.setSecure(isSecure);
+        cfg.setMaxConnections(maxConnections);
+        cfg.setPurgeSynchronously(true); // for more accurate unit testing
+        cs.init(cfg, getCache(), getMarshaller(), connectionClass.newInstance(), bucketClass.newInstance());
+        cs.start();
+        return cs;
+    }
 
-   @AfterMethod
-   @Override
-   public void tearDown() throws CacheLoaderException {
-      if (cs != null) {
-         cs.clear();
-         cs.stop();
+    /*  Changes below are needed to support testing of multiple cache stores */
 
-      }
-      cs = null;
-      if (cs2 != null) {
-         cs2.clear();
+    protected CacheStore cs2;
 
-         cs2.stop();
-      }
-      cs2 = null;
-   }
+    @BeforeMethod
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        cs.clear();
+        Set entries = cs.loadAll();
+        assert entries.size() == 0;
+        cs2 = createAnotherCacheStore();
+        cs2.clear();
+        entries = cs2.loadAll();
+        assert entries.size() == 0;
+    }
 
 
-   @SuppressWarnings("unchecked")
-   @Override
-   public void testStreamingAPI() throws IOException, ClassNotFoundException, CacheLoaderException {
-      cs.store(InternalEntryFactory.create("k1", "v1", -1, -1));
-      cs.store(InternalEntryFactory.create("k2", "v2", -1, -1));
-      cs.store(InternalEntryFactory.create("k3", "v3", -1, -1));
+    @AfterMethod
+    @Override
+    public void tearDown() throws CacheLoaderException {
+        if (cs != null) {
+            cs.clear();
+            cs.stop();
 
-      ByteArrayOutputStream out = new ByteArrayOutputStream();
-      ObjectOutputStream oos = new ObjectOutputStream(out);
-      cs.toStream(new UnclosableObjectOutputStream(oos));
-      oos.flush();
-      oos.close();
-      out.close();
-      ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
-      cs2.fromStream(new UnclosableObjectInputStream(ois));
+        }
+        cs = null;
+        if (cs2 != null) {
+            cs2.clear();
 
-      Set<InternalCacheEntry> set = cs2.loadAll();
+            cs2.stop();
+        }
+        cs2 = null;
+    }
 
-      assert set.size() == 3;
-      Set expected = new HashSet();
-      expected.add("k1");
-      expected.add("k2");
-      expected.add("k3");
-      for (InternalCacheEntry se : set) assert expected.remove(se.getKey());
-      assert expected.isEmpty();
-   }
 
+    @SuppressWarnings("unchecked")
+    @Override
+    public void testStreamingAPI() throws IOException, ClassNotFoundException, CacheLoaderException {
+        cs.store(InternalEntryFactory.create("k1", "v1", -1, -1));
+        cs.store(InternalEntryFactory.create("k2", "v2", -1, -1));
+        cs.store(InternalEntryFactory.create("k3", "v3", -1, -1));
 
-   @SuppressWarnings("unchecked")
-   @Override
-   public void testStreamingAPIReusingStreams() throws IOException, ClassNotFoundException, CacheLoaderException {
-      cs.store(InternalEntryFactory.create("k1", "v1", -1, -1));
-      cs.store(InternalEntryFactory.create("k2", "v2", -1, -1));
-      cs.store(InternalEntryFactory.create("k3", "v3", -1, -1));
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        ObjectOutputStream oos = new ObjectOutputStream(out);
+        cs.toStream(new UnclosableObjectOutputStream(oos));
+        oos.flush();
+        oos.close();
+        out.close();
+        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
+        cs2.fromStream(new UnclosableObjectInputStream(ois));
 
-      ByteArrayOutputStream out = new ByteArrayOutputStream();
-      byte[] dummyStartBytes = {1, 2, 3, 4, 5, 6, 7, 8};
-      byte[] dummyEndBytes = {8, 7, 6, 5, 4, 3, 2, 1};
-      out.write(dummyStartBytes);
-      ObjectOutputStream oos = new ObjectOutputStream(out);
-      cs.toStream(new UnclosableObjectOutputStream(oos));
-      oos.flush();
-      oos.close();
-      out.write(dummyEndBytes);
-      out.close();
+        Set<InternalCacheEntry> set = cs2.loadAll();
 
-      // first pop the start bytes
-      byte[] dummy = new byte[8];
-      ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
-      int bytesRead = in.read(dummy, 0, 8);
-      assert bytesRead == 8;
-      for (int i = 1; i < 9; i++) assert dummy[i - 1] == i : "Start byte stream corrupted!";
-      cs2.fromStream(new UnclosableObjectInputStream(new ObjectInputStream(in)));
-      bytesRead = in.read(dummy, 0, 8);
-      assert bytesRead == 8;
-      for (int i = 8; i > 0; i--) assert dummy[8 - i] == i : "Start byte stream corrupted!";
+        assertEquals(set.size(), 3);
+        Set expected = new HashSet();
+        expected.add("k1");
+        expected.add("k2");
+        expected.add("k3");
+        for (InternalCacheEntry se : set) assert expected.remove(se.getKey());
+        assert expected.isEmpty();
+    }
 
-      Set<InternalCacheEntry> set = cs2.loadAll();
 
-      assert set.size() == 3;
-      Set expected = new HashSet();
-      expected.add("k1");
-      expected.add("k2");
-      expected.add("k3");
-      for (InternalCacheEntry se : set) assert expected.remove(se.getKey());
-      assert expected.isEmpty();
-   }
+    @SuppressWarnings("unchecked")
+    @Override
+    public void testStreamingAPIReusingStreams() throws IOException, ClassNotFoundException, CacheLoaderException {
+        cs.store(InternalEntryFactory.create("k1", "v1", -1, -1));
+        cs.store(InternalEntryFactory.create("k2", "v2", -1, -1));
+        cs.store(InternalEntryFactory.create("k3", "v3", -1, -1));
+
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        byte[] dummyStartBytes = {1, 2, 3, 4, 5, 6, 7, 8};
+        byte[] dummyEndBytes = {8, 7, 6, 5, 4, 3, 2, 1};
+        out.write(dummyStartBytes);
+        ObjectOutputStream oos = new ObjectOutputStream(out);
+        cs.toStream(new UnclosableObjectOutputStream(oos));
+        oos.flush();
+        oos.close();
+        out.write(dummyEndBytes);
+        out.close();
+
+        // first pop the start bytes
+        byte[] dummy = new byte[8];
+        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
+        int bytesRead = in.read(dummy, 0, 8);
+        assertEquals(bytesRead, 8);
+        for (int i = 1; i < 9; i++) assert dummy[i - 1] == i : "Start byte stream corrupted!";
+        cs2.fromStream(new UnclosableObjectInputStream(new ObjectInputStream(in)));
+        bytesRead = in.read(dummy, 0, 8);
+        assertEquals(bytesRead, 8);
+        for (int i = 8; i > 0; i--) assert dummy[8 - i] == i : "Start byte stream corrupted!";
+
+        Set<InternalCacheEntry> set = cs2.loadAll();
+
+        assertEquals(set.size(), 3);
+        Set expected = new HashSet();
+        expected.add("k1");
+        expected.add("k2");
+        expected.add("k3");
+        for (InternalCacheEntry se : set) assert expected.remove(se.getKey());
+        assert expected.isEmpty();
+    }
 }
\ No newline at end of file




More information about the infinispan-commits mailing list