From 2e8e00a2d5ae79cbb5d7d324a7661bb12d97de5b Mon Sep 17 00:00:00 2001 From: Michael Nitschinger Date: Fri, 14 Dec 2012 09:33:00 +0100 Subject: [PATCH] Initial Commit. --- .gitignore | 2 + README.md | 188 ++++++++++++++++++ pom.xml | 41 ++++ .../spring/cache/CouchbaseCache.java | 116 +++++++++++ .../spring/cache/CouchbaseCacheManager.java | 76 +++++++ .../cache/CouchbaseCacheManagerTest.java | 73 +++++++ .../spring/cache/CouchbaseCacheTest.java | 113 +++++++++++ 7 files changed, 609 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 pom.xml create mode 100644 src/main/java/com/couchbase/spring/cache/CouchbaseCache.java create mode 100644 src/main/java/com/couchbase/spring/cache/CouchbaseCacheManager.java create mode 100644 src/test/java/com/couchbase/spring/cache/CouchbaseCacheManagerTest.java create mode 100644 src/test/java/com/couchbase/spring/cache/CouchbaseCacheTest.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..e08c7941 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +target/ +.DS_Store diff --git a/README.md b/README.md new file mode 100644 index 00000000..91aec146 --- /dev/null +++ b/README.md @@ -0,0 +1,188 @@ +Couchbase Java Spring Integration +================================= + +This project aims to bridge the gap between Spring and the Couchbase Java SDK. Currently, only Caching is supported but more features (like support for Spring Data) will be added in the near future. This project has been extracted from the Client SDK to provide a more flexible release cycle and to prevent the core SDK to be messed up with too much dependencies. + +Installation +------------ +This project is distributed as a maven package and can be included as follows: + +```xml + + + couchbase + couchbase-spring + 0.1.0-SNAPSHOT + +``` + +It is distributed from the [Couchbase Maven Repository](http://files.couchbase.com/maven2/): + +```xml + + + couchbase + Couchbase Maven Repository + default + http://files.couchbase.com/maven2/ + + false + + + +``` +Currently, the project depends on the following packages: + + * couchbase.couchbase-client: 1.1.0 + * org.springframework.spring-context: 3.1.3.RELEASE + * cglib.cglib: 2.2.2 + * (When Testing) junit.junit: 4.11 + +You don't need to download them by hand since they are resolved through Maven automatically. + +Dependency Injection Basics (Spring IoC) +---------------------------------------- +Technically, you can use the Spring Beans without the `couchbase-spring` project, but it is crucial to understand how it works because you'll need it for more advanced topics like caching. + +Normally, you would instantiate the `CouchbaseClient` by its constructor in your Java code. When working with beans, you need to define a bean that handles the construction for you like this: + +```xml + + + + + + + + + + + +``` + +This is equivalent to the following Java code: + +```java +ArrayList baseList = new ArrayList(); +baseList.add(URI.create("http://127.0.0.1:8091/pools")); +String bucketName = "default"; +String pwd = ""; +CouchbaseClient client = new CouchbaseClient(baseList, bucketName, pwd); +``` + +If you want to access the bean from your Java code, you can do it like this (you need to make sure that the `beans.xml` file is reachable from your `CLASSPATH`): + +```java +ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); +CouchbaseClient client = context.getBean("CouchbaseClient", CouchbaseClient.class); +``` + +Here, the `beans.xml` defines the bean we saw previously. Spring handles the construction of the object for us and we can then proceed to call the well-known methods on the object. You'll need this kind of approach when you want to use Couchbase for more parts then - lets say - Caching in your project. If you just want to use Caching, you don't even need to work with the CouchbaseClient directly at all. + +Caching with Couchbase in Spring +-------------------------------- +[Caching in Spring](http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/cache.html) mainly works bei annotating your cachable entities with the `@Cacheable` annotation. If you give it only a name like `@Cacheable("default")`, then it tries to use the `default` cache configuration. Before we can use it though, we need to define it. + +Look at the folling bean configuration, which we'll break down afterwards: + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +You should be able to identify the `couchbaseClient` bean, which we'll defined prevously. Here the important part is the `cacheManager` bean that spring will pick up automatically when the `` directive is found. The only configuration that you have to do is to tell the +`CouchbaseCacheManager` (who orchestrates the caches for you), which `CouchbaseClient` instances you want to map to which `name` (the `key`). In the example above, every time you use the `@Cacheable("default")` annotation, the `couchbaseClient` connection defined above is used to store and read the cache values. Since this is essentially a `HashMap`, you can add as many instances as you want, but keep in mind that you should mainly stick to one instance (bucket). Therefore, the configuration shown above should suffice most use cases (of course, please adapt the `CouchbaseClient` constructor params according to your environment). + +That's all it takes to have Couchbase cache your objects. Now we can go through a quick example to show how it works. Assume the following class inside the `com.couchbase.example` package: + +```java +package com.couchbase.spring; + +import org.springframework.cache.annotation.Cacheable; + +public class Bookstore { + + @Cacheable("default") + public String helloWorld(String name) { + return "Hello " + name + "!"; + } +} +``` + +To make Spring pick up this class, add the following bean to your config: + +```xml + +``` + +Consider the following simple application that makes use of the `Bookstore`: + +```java +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class App { + + @Autowired + static Bookstore bookstore; + + public static void main( String[] args ) { + ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); + bookstore = context.getBean("bookstore", Bookstore.class); + + System.out.println(bookstore.helloWorld("World")); + System.out.println(bookstore.helloWorld("World")); + System.out.println(bookstore.helloWorld("Michael")); + + } +} +``` + +We load up our `beans.xml` and get the referenced `bookstore` object out of it. Since the object is now under control of spring, it will pick up our annotation and when we call the `helloWorld()` method for the first time, the resulting object is serialized and stored in Couchbase. On the second try with the same argument, the method itself is not called anymore but loaded directly out of Couchbase! On the third call, since the argument is different, the new value is stored again in Couchbase (you can check the stored values inside the bucket through the Couchbase Server Admin UI). + +Be aware of the following things: + + * Objects are stored as serialized Java objects, not as JSON. You won't be able to read the values through the UI. + * If you use more than one argument, Spring will create a random key for it (see the [docs](http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/cache.html)). + * There are lots of other options available, again read the documentation for it. + +Currently, the customization context is very limited, but there is more functionality planned in the future. We'd love to hear your ideas and needs! \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..b19da210 --- /dev/null +++ b/pom.xml @@ -0,0 +1,41 @@ + + 4.0.0 + + couchbase + couchbase-spring + 0.1.0-SNAPSHOT + jar + + couchbase-spring + https://github.com/couchbaselabs/couchbase-spring + + + UTF-8 + + + + + couchbase + couchbase-client + 1.1.0 + + + org.springframework + spring-context + 3.1.3.RELEASE + jar + + + cglib + cglib + 2.2.2 + + + junit + junit + 4.11 + test + + + diff --git a/src/main/java/com/couchbase/spring/cache/CouchbaseCache.java b/src/main/java/com/couchbase/spring/cache/CouchbaseCache.java new file mode 100644 index 00000000..adc0b9fb --- /dev/null +++ b/src/main/java/com/couchbase/spring/cache/CouchbaseCache.java @@ -0,0 +1,116 @@ +/** + * Copyright (C) 2009-2012 Couchbase, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING + * IN THE SOFTWARE. + */ + +package com.couchbase.spring.cache; + +import com.couchbase.client.CouchbaseClient; +import org.springframework.cache.Cache; +import org.springframework.cache.support.SimpleValueWrapper; + +/** + * The CouchbaseCache class implements the common cache operations on top of + * a CouchbaseClient instance. + */ +public class CouchbaseCache implements Cache { + + /** + * The actual CouchbaseClient instance. + */ + private final CouchbaseClient client; + + /** + * The name of the cache. + */ + private final String name; + + /** + * Construct the cache and pass in the CouchbaseClient instance. + * + * @param client the CouchbaseClient instance. + */ + public CouchbaseCache(String name, CouchbaseClient client) { + this.name = name; + this.client = client; + } + + /** + * Returns the name of the cache. + * + * @return the name of the cache. + */ + public String getName() { + return name; + } + + /** + * Returns the actual CouchbaseClient instance. + * + * @return the actual CouchbaseClient instance. + */ + public CouchbaseClient getNativeCache() { + return this.client; + } + + /** + * Get an element from the cache. + * + * @param key the key to lookup against. + * @return the fetched value from Couchbase. + */ + public ValueWrapper get(Object key) { + String documentId = key.toString(); + Object result = this.client.get(documentId); + return (result != null ? new SimpleValueWrapper(result) : null); + } + + /** + * Store a object in Couchbase. + * + * @param key the Key of the storable object. + * @param value the Object to store. + */ + public void put(Object key, Object value) { + String documentId = key.toString(); + this.client.set(documentId, 0, value); + } + + /** + * Remove an object from Couchbase. + * + * @param key the Key of the object to delete. + */ + public void evict(Object key) { + String documentId = key.toString(); + this.client.delete(documentId); + } + + /** + * Clear the complete cache. + * + * Note that this action is very destructive, so only use it with care. + * Also note that "flush" may not be enabled on the bucket. + */ + public void clear() { + this.client.flush(); + } + +} diff --git a/src/main/java/com/couchbase/spring/cache/CouchbaseCacheManager.java b/src/main/java/com/couchbase/spring/cache/CouchbaseCacheManager.java new file mode 100644 index 00000000..42ff2f2e --- /dev/null +++ b/src/main/java/com/couchbase/spring/cache/CouchbaseCacheManager.java @@ -0,0 +1,76 @@ +/** + * Copyright (C) 2009-2012 Couchbase, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING + * IN THE SOFTWARE. + */ + +package com.couchbase.spring.cache; + +import com.couchbase.client.CouchbaseClient; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import org.springframework.cache.Cache; +import org.springframework.cache.support.AbstractCacheManager; + +/** + * The CouchbaseCacheManager handles CouchbaseClient connections and + * orchestrates them as needed. + */ +public class CouchbaseCacheManager extends AbstractCacheManager { + + /** + * Holds the reference to all stored CouchbaseClient cache connections. + */ + private final HashMap clients; + + /** + * Construct a new CouchabseCacheManager. + */ + public CouchbaseCacheManager(HashMap clients) { + this.clients = clients; + } + + /** + * Returns a Map of all CouchbaseClients with name. + * + * @return the actual CouchbaseClient instances. + */ + public HashMap getClients() { + return this.clients; + } + + /** + * Populates all caches. + * + * @return a collection of loaded caches. + */ + @Override + protected Collection loadCaches() { + Collection caches = new LinkedHashSet(); + + for(Map.Entry cache : this.clients.entrySet()) { + caches.add(new CouchbaseCache(cache.getKey(), cache.getValue())); + } + + return caches; + } + +} diff --git a/src/test/java/com/couchbase/spring/cache/CouchbaseCacheManagerTest.java b/src/test/java/com/couchbase/spring/cache/CouchbaseCacheManagerTest.java new file mode 100644 index 00000000..8f300f7f --- /dev/null +++ b/src/test/java/com/couchbase/spring/cache/CouchbaseCacheManagerTest.java @@ -0,0 +1,73 @@ +/** + * Copyright (C) 2009-2012 Couchbase, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING + * IN THE SOFTWARE. + */ + +package com.couchbase.spring.cache; + +import com.couchbase.client.CouchbaseClient; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import static org.junit.Assert.*; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.cache.Cache; + +/** + * Verifies the correct functionality of the CouchbaseCacheManager. + */ +public class CouchbaseCacheManagerTest { + + /** + * Contains a reference to the actual CouchbaseClient. + */ + private static CouchbaseClient client; + + /** + * Setup a CouchbaseClient before the tests run. + * + * @throws Exception + */ + @BeforeClass + public static void setupCouchbase() throws Exception { + ArrayList baseList = new ArrayList(); + baseList.add(URI.create("http://127.0.0.1:8091/pools")); + String bucketName = "default"; + String pwd = ""; + + client = new CouchbaseClient(baseList, bucketName, pwd); + } + + /** + * Tests the main functionality of the manager: loading the caches. + */ + @Test + public void testCacheInit() { + HashMap instances = + new HashMap(); + instances.put("test", client); + + CouchbaseCacheManager manager = new CouchbaseCacheManager(instances); + assertEquals(instances, manager.getClients()); + } + +} diff --git a/src/test/java/com/couchbase/spring/cache/CouchbaseCacheTest.java b/src/test/java/com/couchbase/spring/cache/CouchbaseCacheTest.java new file mode 100644 index 00000000..38d79c6c --- /dev/null +++ b/src/test/java/com/couchbase/spring/cache/CouchbaseCacheTest.java @@ -0,0 +1,113 @@ +/** + * Copyright (C) 2009-2012 Couchbase, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING + * IN THE SOFTWARE. + */ + +package com.couchbase.spring.cache; + +import com.couchbase.client.CouchbaseClient; +import java.net.URI; +import java.util.ArrayList; +import static org.junit.Assert.*; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.cache.Cache.ValueWrapper; + +/** + * Tests the CouchbaseCache class and verifies its functionality. + */ +public class CouchbaseCacheTest { + + /** + * Contains a reference to the actual CouchbaseClient. + */ + private static CouchbaseClient client; + + /** + * Simple name of the cache bucket to create. + */ + private String cacheName = "test"; + + /** + * Setup a CouchbaseClient before the tests run. + * + * @throws Exception + */ + @BeforeClass + public static void setupCouchbase() throws Exception { + ArrayList baseList = new ArrayList(); + baseList.add(URI.create("http://127.0.0.1:8091/pools")); + String bucketName = "default"; + String pwd = ""; + + client = new CouchbaseClient(baseList, bucketName, pwd); + } + + /** + * Tests the basic Cache construction functionality. + */ + @Test + public void testConstruction() { + CouchbaseCache cache = new CouchbaseCache(cacheName, client); + + assertEquals(cacheName, cache.getName()); + assertEquals(client, cache.getNativeCache()); + } + + /** + * Verifies set() and get() of cache objects. + */ + @Test + public void testGetSet() { + CouchbaseCache cache = new CouchbaseCache(cacheName, client); + + String key = "couchbase-cache-test"; + String value = "Hello World!"; + cache.put(key, value); + + String stored = (String) client.get(key); + assertNotNull(stored); + assertEquals(value, stored); + + ValueWrapper loaded = cache.get(key); + assertEquals(value, loaded.get()); + } + + /** + * Verifies the deletion of cache objects. + * + * @throws Exception + */ + @Test + public void testEvict() throws Exception { + CouchbaseCache cache = new CouchbaseCache(cacheName, client); + + String key = "couchbase-cache-test"; + String value = "Hello World!"; + + Boolean success = client.set(key, 0, value).get(); + assertTrue(success); + + cache.evict(key); + Object result = client.get(key); + assertNull(result); + } + +}