DATACOUCH-135 - Migrate to Couchbase SDK 2.0 and add N1QL find method.

Adaptation were made to use SDK 2.0:
 - Reworked the configuration approach (more parts to be configured, like Environment, Cluster and Bucket)
 - Added a new xml schema for configuration of 2.0 version
 - Adapted the template
 - Added N1QL support in the template (findByN1QL)
 - Removed the cache package
 - Adapted the repository
 - Better separated Unit Tests from Integration Tests

All integration and unit tests pass, except one (SimpleCouchbaseRepositoryTests.shouldFindCustom).

Customisation of a ViewQuery will be addressed in another ticket.
This commit is contained in:
Simon Baslé
2015-07-02 18:50:08 +02:00
parent 28dcdee1db
commit b9f23f3fd5
126 changed files with 4203 additions and 3184 deletions

View File

@@ -1,74 +0,0 @@
package org.springframework.data.couchbase;
import com.couchbase.client.ClusterManager;
import com.couchbase.client.clustermanager.BucketType;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.util.Arrays;
public class BucketCreator implements InitializingBean {
private final Logger logger = LoggerFactory.getLogger(BucketCreator.class);
private final String hostUri;
private final String adminUser;
private final String adminPass;
public BucketCreator(String host, String user, String pass) {
hostUri = host;
adminUser = user;
adminPass = pass;
}
@Override
public void afterPropertiesSet() throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(adminUser, adminPass));
client.setCredentialsProvider(credentialsProvider);
ClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory(client);
RestTemplate template = new RestTemplate(rf);
String fullUri = "http://" + hostUri + ":8091/pools/default/buckets/default";
ResponseEntity<String> entity = null;
try {
entity = template.getForEntity(fullUri, String.class);
} catch (HttpClientErrorException ex) {
logger.info("Got execpetion while looking for bucket: " + ex.getMessage());
if (ex.getMessage().equals("404 Object Not Found")) {
logger.info("Creating default bucket with admin credentials.");
createBucket();
return;
} else {
throw new RuntimeException("Could not see if bucket is already created.", ex);
}
}
logger.info("Checking for bucket returned status code " + entity.getStatusCode());
}
private void createBucket() throws Exception {
ClusterManager bucketManager =
new ClusterManager(Arrays.asList(URI.create("http://" + hostUri + ":8091")), adminUser, adminPass);
bucketManager.createDefaultBucket(BucketType.COUCHBASE, 128, 0, true);
logger.info("Finished creating bucket, sleeping for warmup.");
Thread.sleep(5000);
bucketManager.shutdown();
}
}

View File

@@ -1,94 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase;
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.CouchbaseConnectionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.env.Environment;
import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.springframework.data.couchbase.core.WriteResultChecking;
import java.util.Arrays;
import java.util.List;
/**
* @author Michael Nitschinger
*/
@Configuration
public class TestApplicationConfig extends AbstractCouchbaseConfiguration {
@Autowired
private Environment env;
@Bean
public String couchbaseAdminUser() {
return env.getProperty("couchbase.adminUser", "Administrator");
}
@Bean
public String couchbaseAdminPassword() {
return env.getProperty("couchbase.adminUser", "password");
}
@Override
protected List<String> bootstrapHosts() {
return Arrays.asList(env.getProperty("couchbase.host", "127.0.0.1"));
}
@Override
protected String getBucketName() {
return env.getProperty("couchbase.bucket", "default");
}
@Override
protected String getBucketPassword() {
return env.getProperty("couchbase.password", "");
}
@Bean
public BucketCreator bucketCreator() throws Exception {
return new BucketCreator(bootstrapHosts().get(0), couchbaseAdminUser(), couchbaseAdminPassword());
}
@Bean
@Override
@DependsOn("bucketCreator")
public CouchbaseClient couchbaseClient() throws Exception {
setLoggerProperty(couchbaseLogger());
CouchbaseConnectionFactoryBuilder builder = new CouchbaseConnectionFactoryBuilder();
builder.setOpTimeout(10000); // using a higher timeout for tests to reduce flakiness
return new CouchbaseClient(builder.buildCouchbaseConnection(
bootstrapUris(bootstrapHosts()),
getBucketName(),
getBucketPassword()
));
}
@Override
public CouchbaseTemplate couchbaseTemplate() throws Exception {
CouchbaseTemplate template = super.couchbaseTemplate();
template.setWriteResultChecking(WriteResultChecking.LOG);
return template;
}
}

View File

@@ -0,0 +1,67 @@
package org.springframework.data.couchbase;
import java.util.Collections;
import java.util.List;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseBucket;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.springframework.data.couchbase.core.WriteResultChecking;
@Configuration
public class UnitTestApplicationConfig extends AbstractCouchbaseConfiguration {
@Bean
public String couchbaseAdminUser() {
return "someLogin";
}
@Bean
public String couchbaseAdminPassword() {
return "somePassword";
}
@Override
protected List<String> getBootstrapHosts() {
return Collections.singletonList("192.1.2.3");
}
@Override
protected String getBucketName() {
return "someBucket";
}
@Override
protected String getBucketPassword() {
return "someBucketPassword";
}
@Override
public Cluster couchbaseCluster() throws Exception {
return Mockito.mock(CouchbaseCluster.class);
}
@Override
public Bucket couchbaseClient() throws Exception {
return Mockito.mock(CouchbaseBucket.class);
}
@Override
public CouchbaseTemplate couchbaseTemplate() throws Exception {
CouchbaseTemplate template = super.couchbaseTemplate();
template.setWriteResultChecking(WriteResultChecking.LOG);
return template;
}
}

View File

@@ -1,110 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.cache;
import com.couchbase.client.CouchbaseClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.data.couchbase.TestApplicationConfig;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Verifies the correct functionality of the CouchbaseCacheManager.
*
* @author Michael Nitschinger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplicationConfig.class)
public class CouchbaseCacheManagerTests {
/**
* Contains a reference to the actual CouchbaseClient.
*/
@Autowired
private CouchbaseClient client;
/**
* Tests the main functionality of the manager: loading the caches.
*/
@Test
public void testCacheInit() {
HashMap<String, CouchbaseClient> instances =
new HashMap<String, CouchbaseClient>();
instances.put("test", client);
CouchbaseCacheManager manager = new CouchbaseCacheManager(instances);
manager.afterPropertiesSet();
assertEquals(instances, manager.getClients());
Cache cache = manager.getCache("test");
assertNotNull(cache);
assertEquals(cache.getClass(), CouchbaseCache.class);
assertEquals(((CouchbaseCache) cache).getName(), "test");
assertEquals(((CouchbaseCache) cache).getTtl(), 0); // default TTL value
assertEquals(((CouchbaseCache) cache).getNativeCache(), client);
}
/**
* Test cache creation with custom TTL values.
*/
@Test
public void testCacheInitWithTtl() {
HashMap<String, CouchbaseClient> instances = new HashMap<String, CouchbaseClient>();
instances.put("cache1", client);
instances.put("cache2", client);
HashMap<String, Integer> ttlConfiguration = new HashMap<String, Integer>();
ttlConfiguration.put("cache1", 100);
ttlConfiguration.put("cache2", 200);
CouchbaseCacheManager manager = new CouchbaseCacheManager(instances, ttlConfiguration);
manager.afterPropertiesSet();
assertEquals(instances, manager.getClients());
Cache cache1 = manager.getCache("cache1");
Cache cache2 = manager.getCache("cache2");
assertNotNull(cache1);
assertNotNull(cache2);
assertEquals(cache1.getClass(), CouchbaseCache.class);
assertEquals(cache2.getClass(), CouchbaseCache.class);
assertEquals(((CouchbaseCache) cache1).getName(), "cache1");
assertEquals(((CouchbaseCache) cache2).getName(), "cache2");
assertEquals(((CouchbaseCache) cache1).getTtl(), 100);
assertEquals(((CouchbaseCache) cache2).getTtl(), 200);
assertEquals(((CouchbaseCache) cache1).getNativeCache(), client);
assertEquals(((CouchbaseCache) cache2).getNativeCache(), client);
}
}

View File

@@ -1,158 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.cache;
import com.couchbase.client.CouchbaseClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.data.couchbase.TestApplicationConfig;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.Serializable;
import static org.junit.Assert.*;
/**
* Tests the CouchbaseCache class and verifies its functionality.
*
* @author Michael Nitschinger
* @author Konrad Król
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplicationConfig.class)
public class CouchbaseCacheTests {
/**
* Contains a reference to the actual CouchbaseClient.
*/
@Autowired
private CouchbaseClient client;
/**
* Simple name of the cache bucket to create.
*/
private String cacheName = "test";
/**
* 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 set() with TTL value.
*/
@Test
public void testSetWithTtl() throws InterruptedException {
CouchbaseCache cache = new CouchbaseCache(cacheName, client, 1); // cache for 1 second
String key = "couchbase-cache-test";
String value = "Hello World!";
cache.put(key, value);
// wait for TTL to expire (double time of TTL)
Thread.sleep(2000);
String stored = (String) client.get(key);
assertNull(stored);
}
@Test
public void testGetSetWithCast() {
CouchbaseCache cache = new CouchbaseCache(cacheName, client);
String key = "couchbase-cache-user";
User user = new User();
user.firstname = "Michael";
cache.put(key, user);
User loaded = cache.get(key, User.class);
assertNotNull(loaded);
assertEquals(user.firstname, loaded.firstname);
}
/**
* 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);
}
/**
* Putting into cache on the same key not null value, and then null value,
* results in null object
*/
@Test
public void testSettingNullAndGetting() {
CouchbaseCache cache = new CouchbaseCache(cacheName, client);
String key = "couchbase-cache-test";
String value = "Hello World!";
cache.put(key, value);
cache.put(key, null);
assertNull(cache.get(key));
}
static class User implements Serializable {
public String firstname;
}
}

View File

@@ -1,86 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.config;
import com.couchbase.client.CouchbaseClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.data.couchbase.TestApplicationConfig;
import org.springframework.data.couchbase.core.mapping.Document;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Unit test for {@link AbstractCouchbaseConfiguration}
*
* @author Michael Nitschinger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplicationConfig.class)
public class AbstractCouchbaseConfigurationTests {
/**
* Contains a reference to the actual CouchbaseClient.
*/
@Autowired
private CouchbaseClient client;
@Test
public void usesConfigClassPackageAsBaseMappingPackage() throws Exception {
AbstractCouchbaseConfiguration config = new SampleCouchbaseConfiguration();
assertEquals(config.getMappingBasePackage(), SampleCouchbaseConfiguration.class.getPackage().getName());
assertEquals(config.getInitialEntitySet().size(), 1);
assertTrue(config.getInitialEntitySet().contains(Entity.class));
}
class SampleCouchbaseConfiguration extends AbstractCouchbaseConfiguration {
@Override
protected List<String> bootstrapHosts() {
return null;
}
@Override
protected String getBucketName() {
return null;
}
@Override
protected String getBucketPassword() {
return null;
}
@Bean
@Override
public CouchbaseClient couchbaseClient() throws Exception {
return client;
}
}
@Document
static class Entity {
}
}

View File

@@ -0,0 +1,136 @@
/*
* Copyright 2012-2015 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.config;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import java.util.List;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
public class CouchbaseBucketParserTest {
private static DefaultListableBeanFactory factory;
@BeforeClass
public static void setUp() {
factory = new DefaultListableBeanFactory();
BeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
int n = reader.loadBeanDefinitions(new ClassPathResource("configurations/couchbaseBucket-bean.xml"));
System.out.println(n);
}
@AfterClass
public static void tearDown() {
}
@Test
public void testDefaultBucketNoCluster() {
BeanDefinition def = factory.getBeanDefinition("bucketDefaultNoCluster");
assertThat(def, is(notNullValue()));
assertThat(def.getConstructorArgumentValues().getArgumentCount(), is(equalTo(1)));
assertThat(def.getPropertyValues().size(), is(equalTo(0)));
ConstructorArgumentValues.ValueHolder holder = def.getConstructorArgumentValues()
.getArgumentValue(0, Object.class);
assertThat(holder.getValue(), is(instanceOf(RuntimeBeanReference.class)));
RuntimeBeanReference clusterRef = (RuntimeBeanReference) holder.getValue();
assertThat(clusterRef.getBeanName(), is(equalTo(BeanNames.COUCHBASE_CLUSTER)));
}
@Test
public void testDefaultBucket() throws Exception {
BeanDefinition def = factory.getBeanDefinition("bucketDefault");
assertThat(def, is(notNullValue()));
assertThat(def.getConstructorArgumentValues().getArgumentCount(), is(equalTo(1)));
assertThat(def.getPropertyValues().size(), is(equalTo(0)));
ConstructorArgumentValues.ValueHolder holder = def.getConstructorArgumentValues()
.getArgumentValue(0, Object.class);
assertThat(holder.getValue(), is(instanceOf(RuntimeBeanReference.class)));
RuntimeBeanReference clusterRef = (RuntimeBeanReference) holder.getValue();
assertThat(clusterRef.getBeanName(), is(equalTo("clusterDefault")));
}
@Test
public void testBucketWithName() throws Exception {
BeanDefinition def = factory.getBeanDefinition("bucketWithName");
assertThat(def, is(notNullValue()));
assertThat(def.getConstructorArgumentValues().getArgumentCount(), is(equalTo(2)));
assertThat(def.getPropertyValues().size(), is(equalTo(0)));
ConstructorArgumentValues.ValueHolder holder = def.getConstructorArgumentValues()
.getArgumentValue(0, Object.class);
assertThat(holder.getValue(), is(instanceOf(RuntimeBeanReference.class)));
RuntimeBeanReference clusterRef = (RuntimeBeanReference) holder.getValue();
assertThat(clusterRef.getBeanName(), is(equalTo("clusterDefault")));
ConstructorArgumentValues.ValueHolder nameHolder = def.getConstructorArgumentValues()
.getArgumentValue(1, Object.class);
assertThat(nameHolder.getValue(), is(instanceOf(String.class)));
assertThat(nameHolder.getValue().toString(), is((equalTo("toto"))));
}
@Test
public void testBucketWithNameAndPassword() throws Exception {
BeanDefinition def = factory.getBeanDefinition("bucketWithNameAndPassword");
assertThat(def, is(notNullValue()));
assertThat(def.getConstructorArgumentValues().getArgumentCount(), is(equalTo(3)));
assertThat(def.getPropertyValues().size(), is(equalTo(0)));
ConstructorArgumentValues.ValueHolder holder = def.getConstructorArgumentValues()
.getArgumentValue(0, Object.class);
assertThat(holder.getValue(), is(instanceOf(RuntimeBeanReference.class)));
RuntimeBeanReference clusterRef = (RuntimeBeanReference) holder.getValue();
assertThat(clusterRef.getBeanName(), is(equalTo("clusterDefault")));
ConstructorArgumentValues.ValueHolder nameHolder = def.getConstructorArgumentValues()
.getArgumentValue(1, Object.class);
assertThat(nameHolder.getValue(), is(instanceOf(String.class)));
assertThat(nameHolder.getValue().toString(), is((equalTo("test"))));
ConstructorArgumentValues.ValueHolder passwordHolder = def.getConstructorArgumentValues()
.getArgumentValue(2, Object.class);
assertThat(passwordHolder.getValue(), is(instanceOf(String.class)));
assertThat(passwordHolder.getValue().toString(), is((equalTo("123"))));
}
}

View File

@@ -0,0 +1,154 @@
/*
* Copyright 2012-2015 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.config;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import java.util.List;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
public class CouchbaseClusterParserTest {
private static DefaultListableBeanFactory factory;
@BeforeClass
public static void setUp() {
factory = new DefaultListableBeanFactory();
BeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
int n = reader.loadBeanDefinitions(new ClassPathResource("configurations/couchbaseCluster-bean.xml"));
System.out.println(n);
}
@AfterClass
public static void tearDown() {
}
@Test
public void testClusterWithoutSpecificEnv() {
BeanDefinition def = factory.getBeanDefinition("clusterDefault");
assertThat(def, is(notNullValue()));
assertThat(def.getConstructorArgumentValues().getArgumentCount(), is(equalTo(1)));
assertThat(def.getPropertyValues().size(), is(equalTo(0)));
assertThat(def.getFactoryMethodName(), is(equalTo("create")));
ConstructorArgumentValues.ValueHolder holder = def.getConstructorArgumentValues()
.getArgumentValue(0, CouchbaseEnvironment.class);
assertThat(holder.getValue(), instanceOf(RuntimeBeanReference.class));
RuntimeBeanReference envRef = (RuntimeBeanReference) holder.getValue();
assertThat(envRef.getBeanName(), is(equalTo("couchbaseEnv")));
}
@Test
public void testClusterWithNodes() {
BeanDefinition def = factory.getBeanDefinition("clusterWithNodes");
assertThat(def, is(notNullValue()));
assertThat(def.getConstructorArgumentValues().getArgumentCount(), is(equalTo(2)));
assertThat(def.getPropertyValues().size(), is(equalTo(0)));
assertThat(def.getFactoryMethodName(), is(equalTo("create")));
ConstructorArgumentValues.ValueHolder holder = def.getConstructorArgumentValues()
.getArgumentValue(1, List.class);
assertThat(holder.getValue(), is(instanceOf(List.class)));
List nodes = (List<String>) holder.getValue();
assertThat(nodes.size(), is(equalTo(2)));
assertThat((String) nodes.get(0), is(equalTo("192.1.2.3")));
assertThat((String) nodes.get(1), is(equalTo("192.4.5.6")));
}
@Test
public void testClusterWithEnvInline() {
BeanDefinition def = factory.getBeanDefinition("clusterWithEnvInline");
assertThat(def, is(notNullValue()));
assertThat(def.getConstructorArgumentValues().getArgumentCount(), is(equalTo(1)));
assertThat(def.getPropertyValues().size(), is(equalTo(0)));
ConstructorArgumentValues.ValueHolder holder = def.getConstructorArgumentValues()
.getArgumentValue(0, CouchbaseEnvironment.class);
GenericBeanDefinition envDef = (GenericBeanDefinition) holder.getValue();
assertThat(envDef.getBeanClassName(), is(equalTo(CouchbaseEnvironmentFactoryBean.class.getName())));
assertThat("unexpected attribute", envDef.getPropertyValues().contains("managementTimeout"));
}
@Test
public void testClusterWithEnvRef() {
BeanDefinition def = factory.getBeanDefinition("clusterWithEnvRef");
assertThat(def, is(notNullValue()));
assertThat(def.getConstructorArgumentValues().getArgumentCount(), is(equalTo(1)));
assertThat(def.getPropertyValues().size(), is(equalTo(0)));
ConstructorArgumentValues.ValueHolder holder = def.getConstructorArgumentValues()
.getArgumentValue(0, CouchbaseEnvironment.class);
assertThat(holder.getValue(), instanceOf(RuntimeBeanReference.class));
RuntimeBeanReference envRef = (RuntimeBeanReference) holder.getValue();
assertThat(envRef.getBeanName(), is(equalTo("someEnv")));
}
@Test
public void testClusterConfigurationPrecedence() {
BeanDefinition def = factory.getBeanDefinition("clusterWithAll");
assertThat(def, is(notNullValue()));
assertThat(def.getConstructorArgumentValues().getArgumentCount(), is(equalTo(2)));
assertThat(def.getPropertyValues().size(), is(equalTo(0)));
assertThat(def.getFactoryMethodName(), is(equalTo("create")));
assertThat(def.getConstructorArgumentValues().getIndexedArgumentValues().get(0).getValue(),
instanceOf(GenericBeanDefinition.class));
assertThat(def.getConstructorArgumentValues().getIndexedArgumentValues().get(1).getValue(),
instanceOf(List.class));
ConstructorArgumentValues.ValueHolder holderEnv = def.getConstructorArgumentValues()
.getArgumentValue(0, CouchbaseEnvironment.class);
GenericBeanDefinition envDef = (GenericBeanDefinition) holderEnv.getValue();
assertThat(envDef.getBeanClassName(), is(equalTo(CouchbaseEnvironmentFactoryBean.class.getName())));
assertThat("unexpected attribute", envDef.getPropertyValues().contains("autoreleaseAfter"));
ConstructorArgumentValues.ValueHolder holderNodes = def.getConstructorArgumentValues()
.getArgumentValue(1, List.class);
List nodes = (List<String>) holderNodes.getValue();
assertThat(nodes.size(), is(equalTo(2)));
assertThat((String) nodes.get(0), is(equalTo("2.2.2.2")));
assertThat((String) nodes.get(1), is(equalTo("4.4.4.4")));
}
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright 2012-2015 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.config;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import com.couchbase.client.core.retry.BestEffortRetryStrategy;
import com.couchbase.client.core.retry.FailFastRetryStrategy;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.ClassPathResource;
public class CouchbaseEnvironmentParserTest {
private static GenericApplicationContext context;
@BeforeClass
public static void setUp() {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(new ClassPathResource("configurations/couchbaseEnv-bean.xml"));
context = new GenericApplicationContext(factory);
context.refresh();
}
@Test
public void testParsingRetryStrategyFailFast() throws Exception {
CouchbaseEnvironment env = context.getBean("envWithFailFast", CouchbaseEnvironment.class);
assertThat(env.retryStrategy(), is(instanceOf(FailFastRetryStrategy.class)));
}
@Test
public void testParsingRetryStrategyBestEffort() throws Exception {
CouchbaseEnvironment env = context.getBean("envWithBestEffort", CouchbaseEnvironment.class);
assertThat(env.retryStrategy(), is(instanceOf(BestEffortRetryStrategy.class)));
}
@Test
public void testAllDefaultsOverridden() {
CouchbaseEnvironment env = context.getBean("envWithNoDefault", CouchbaseEnvironment.class);
CouchbaseEnvironment defaultEnv = DefaultCouchbaseEnvironment.create();
assertThat(env, is(instanceOf(DefaultCouchbaseEnvironment.class)));
assertThat(env.managementTimeout(), is(equalTo(1L)));
assertThat(env.queryTimeout(), is(equalTo(2L)));
assertThat(env.viewTimeout(), is(equalTo(3L)));
assertThat(env.kvTimeout(), is(equalTo(4L)));
assertThat(env.connectTimeout(), is(equalTo(5L)));
assertThat(env.disconnectTimeout(), is(equalTo(6L)));
assertThat(env.dnsSrvEnabled(), allOf(equalTo(true), not(defaultEnv.dnsSrvEnabled())));
//TODO activate test when dcp can be enabled on the environment (add it in the xml)
// assertThat(env.dcpEnabled(), allOf(equalTo(true), not(defaultEnv.dcpEnabled())));
assertThat(env.sslEnabled(), allOf(equalTo(true), not(defaultEnv.sslEnabled())));
assertThat(env.sslKeystoreFile(), is(equalTo("test")));
assertThat(env.sslKeystorePassword(), is(equalTo("test")));
assertThat(env.queryEnabled(), allOf(equalTo(true), not(defaultEnv.queryEnabled())));
assertThat(env.queryPort(), is(equalTo(7)));
assertThat(env.bootstrapHttpEnabled(), allOf(equalTo(false), not(defaultEnv.bootstrapHttpEnabled())));
assertThat(env.bootstrapCarrierEnabled(), allOf(equalTo(false), not(defaultEnv.bootstrapCarrierEnabled())));
assertThat(env.bootstrapHttpDirectPort(), is(equalTo(8)));
assertThat(env.bootstrapHttpSslPort(), is(equalTo(9)));
assertThat(env.bootstrapCarrierDirectPort(), is(equalTo(10)));
assertThat(env.bootstrapCarrierSslPort(), is(equalTo(11)));
assertThat(env.ioPoolSize(), is(equalTo(12)));
assertThat(env.computationPoolSize(), is(equalTo(13)));
assertThat(env.responseBufferSize(), is(equalTo(14)));
assertThat(env.requestBufferSize(), is(equalTo(15)));
assertThat(env.kvEndpoints(), is(equalTo(16)));
assertThat(env.viewEndpoints(), is(equalTo(17)));
assertThat(env.queryEndpoints(), is(equalTo(18)));
assertThat(env.retryStrategy(), is(instanceOf(FailFastRetryStrategy.class)));
assertThat(env.maxRequestLifetime(), is(equalTo(19L)));
assertThat(env.keepAliveInterval(), is(equalTo(20L)));
assertThat(env.autoreleaseAfter(), is(equalTo(21L)));
assertThat(env.bufferPoolingEnabled(), allOf(equalTo(false), not(defaultEnv.bufferPoolingEnabled())));
}
@AfterClass
public static void tearDown() {
context.close();
}
}

View File

@@ -1,43 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.config;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
/**
* @author Michael Nitschinger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:namespace/couchbase-bean.xml")
public class CouchbaseParserIntegrationTests {
@Autowired
ApplicationContext ctx;
@Test
public void readsCouchbaseAttributesCorrectly() {
assertTrue(ctx.containsBean("couchbase"));
assertTrue(ctx.containsBean("couchbase2"));
assertTrue(ctx.containsBean("couchbase3"));
}
}

View File

@@ -1,74 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.config;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import static org.junit.Assert.assertEquals;
/**
* @author Michael Nitschinger
*/
public class CouchbaseTemplateParserIntegrationTests {
DefaultListableBeanFactory factory;
BeanDefinitionReader reader;
@Before
public void setUp() {
factory = new DefaultListableBeanFactory();
reader = new XmlBeanDefinitionReader(factory);
}
@Test
public void readsCouchbaseTemplateAttributesCorrectly() {
reader.loadBeanDefinitions(new ClassPathResource("namespace/couchbase-template-bean.xml"));
BeanDefinition definition = factory.getBeanDefinition("couchbaseTemplate");
assertEquals(1, definition.getConstructorArgumentValues().getArgumentCount());
factory.getBean("couchbaseTemplate");
}
@Test
public void readsCouchbaseTemplateWithTranslationServiceAttributesCorrectly() {
reader.loadBeanDefinitions(new ClassPathResource("namespace/couchbase-template-with-translation-service-bean.xml"));
BeanDefinition definition = factory.getBeanDefinition("couchbaseTemplate");
assertEquals(2, definition.getConstructorArgumentValues().getArgumentCount());
factory.getBean("couchbaseTemplate");
}
/**
* Test case for DATACOUCH-47.
*/
@Test
public void allowsMultipleBuckets() {
reader.loadBeanDefinitions(new ClassPathResource("namespace/couchbase-multi-bucket-bean.xml"));
factory.getBean("cb-template-first");
factory.getBean("cb-template-second");
}
}

View File

@@ -61,9 +61,9 @@ public class Beer {
public boolean getActive() {
return active;
}
public String getId() {
return id;
return id;
}
}

View File

@@ -1,536 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.core;
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.protocol.views.Query;
import com.couchbase.client.protocol.views.Stale;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.spy.memcached.CASValue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.couchbase.TestApplicationConfig;
import org.springframework.data.couchbase.core.mapping.Document;
import org.springframework.data.couchbase.core.mapping.Field;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* @author Michael Nitschinger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplicationConfig.class)
@TestExecutionListeners(CouchbaseTemplateViewListener.class)
public class CouchbaseTemplateTests {
@Autowired
private CouchbaseClient client;
@Autowired
private CouchbaseTemplate template;
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
public void saveSimpleEntityCorrectly() throws Exception {
String id = "beers:awesome-stout";
String name = "The Awesome Stout";
boolean active = false;
Beer beer = new Beer(id).setName(name).setActive(active);
template.save(beer);
String result = (String) client.get(id);
assertNotNull(result);
Map<String, Object> resultConv = MAPPER.readValue(result, new TypeReference<Map<String, Object>>() {});
assertEquals("org.springframework.data.couchbase.core.Beer", resultConv.get("_class"));
assertEquals(false, resultConv.get("is_active"));
assertEquals("The Awesome Stout", resultConv.get("name"));
}
@Test
public void saveDocumentWithExpiry() throws Exception {
String id = "simple-doc-with-expiry";
DocumentWithExpiry doc = new DocumentWithExpiry(id);
template.save(doc);
assertNotNull(client.get(id));
Thread.sleep(3000);
assertNull(client.get(id));
}
@Test
public void insertDoesNotOverride() throws Exception {
String id = "double-insert-test";
client.delete(id).get();
SimplePerson doc = new SimplePerson(id, "Mr. A");
template.insert(doc);
String result = (String) client.get(id);
Map<String, String> resultConv = MAPPER.readValue(result, new TypeReference<Map<String, String>>() {});
assertEquals("Mr. A", resultConv.get("name"));
doc = new SimplePerson(id, "Mr. B");
template.insert(doc);
result = (String) client.get(id);
resultConv = MAPPER.readValue(result, new TypeReference<Map<String, String>>() {});
assertEquals("Mr. A", resultConv.get("name"));
}
@Test
public void updateDoesNotInsert() {
String id = "update-does-not-insert";
SimplePerson doc = new SimplePerson(id, "Nice Guy");
template.update(doc);
assertNull(client.get(id));
}
@Test
public void removeDocument() {
String id = "beers:to-delete-stout";
Beer beer = new Beer(id);
template.save(beer);
Object result = client.get(id);
assertNotNull(result);
template.remove(beer);
result = client.get(id);
assertNull(result);
}
@Test
public void storeListsAndMaps() {
String id = "persons:lots-of-names";
List<String> names = new ArrayList<String>();
names.add("Michael");
names.add("Thomas");
names.add(null);
List<Integer> votes = new LinkedList<Integer>();
Map<String, Boolean> info1 = new HashMap<String, Boolean>();
info1.put("foo", true);
info1.put("bar", false);
info1.put("nullValue", null);
Map<String, Integer> info2 = new HashMap<String, Integer>();
ComplexPerson complex = new ComplexPerson(id, names, votes, info1, info2);
template.save(complex);
assertNotNull(client.get(id));
ComplexPerson response = template.findById(id, ComplexPerson.class);
assertEquals(names, response.getFirstnames());
assertEquals(votes, response.getVotes());
assertEquals(id, response.getId());
assertEquals(info1, response.getInfo1());
assertEquals(info2, response.getInfo2());
}
@Test
public void validFindById() {
String id = "beers:findme-stout";
String name = "The Findme Stout";
boolean active = true;
Beer beer = new Beer(id).setName(name).setActive(active);
template.save(beer);
Beer found = template.findById(id, Beer.class);
assertNotNull(found);
assertEquals(id, found.getId());
assertEquals(name, found.getName());
assertEquals(active, found.getActive());
}
@Test
public void shouldLoadAndMapViewDocs() {
Query query = new Query();
query.setStale(Stale.FALSE);
final List<Beer> beers = template.findByView("test_beers", "by_name", query, Beer.class);
assertTrue(beers.size() > 0);
for (Beer beer : beers) {
assertNotNull(beer.getId());
assertNotNull(beer.getName());
assertNotNull(beer.getActive());
}
}
@Test
public void shouldDeserialiseLongs() {
final long time = new Date().getTime();
SimpleWithLong simpleWithLong = new SimpleWithLong("simpleWithLong:simple", time);
template.save(simpleWithLong);
simpleWithLong = template.findById("simpleWithLong:simple", SimpleWithLong.class);
assertNotNull(simpleWithLong);
assertEquals(time, simpleWithLong.getValue());
}
@Test
public void shouldDeserialiseEnums() {
SimpleWithEnum simpleWithEnum = new SimpleWithEnum("simpleWithEnum:enum", SimpleWithEnum.Type.BIG);
template.save(simpleWithEnum);
simpleWithEnum = template.findById("simpleWithEnum:enum", SimpleWithEnum.class);
assertNotNull(simpleWithEnum);
assertEquals(simpleWithEnum.getType(), SimpleWithEnum.Type.BIG);
}
@Test
public void shouldDeserialiseClass() {
SimpleWithClass simpleWithClass = new SimpleWithClass("simpleWithClass:class", Integer.class);
simpleWithClass.setValue("The dish ran away with the spoon.");
template.save(simpleWithClass);
simpleWithClass = template.findById("simpleWithClass:class", SimpleWithClass.class);
assertNotNull(simpleWithClass);
assertThat(simpleWithClass.getValue(), equalTo("The dish ran away with the spoon."));
}
@Test
public void shouldHandleCASVersionOnInsert() throws Exception {
client.delete("versionedClass:1").get();
VersionedClass versionedClass = new VersionedClass("versionedClass:1", "foobar");
assertEquals(0, versionedClass.getVersion());
template.insert(versionedClass);
CASValue<Object> rawStored = client.gets("versionedClass:1");
assertEquals(rawStored.getCas(), versionedClass.getVersion());
}
@Test
public void versionShouldNotUpdateOnSecondInsert() throws Exception {
client.delete("versionedClass:2").get();
VersionedClass versionedClass = new VersionedClass("versionedClass:2", "foobar");
template.insert(versionedClass);
long version1 = versionedClass.getVersion();
template.insert(versionedClass);
long version2 = versionedClass.getVersion();
assertTrue(version1 > 0);
assertTrue(version2 > 0);
assertEquals(version1, version2);
}
@Test
public void shouldSaveDocumentOnMatchingVersion() throws Exception {
client.delete("versionedClass:3").get();
VersionedClass versionedClass = new VersionedClass("versionedClass:3", "foobar");
template.insert(versionedClass);
long version1 = versionedClass.getVersion();
versionedClass.setField("foobar2");
template.save(versionedClass);
long version2 = versionedClass.getVersion();
assertTrue(version1 > 0);
assertTrue(version2 > 0);
assertNotEquals(version1, version2);
assertEquals("foobar2", template.findById("versionedClass:3", VersionedClass.class).getField());
}
@Test(expected = OptimisticLockingFailureException.class)
public void shouldNotSaveDocumentOnNotMatchingVersion() throws Exception {
client.delete("versionedClass:4").get();
VersionedClass versionedClass = new VersionedClass("versionedClass:4", "foobar");
template.insert(versionedClass);
assertTrue(client.set("versionedClass:4", "different").get());
versionedClass.setField("foobar2");
template.save(versionedClass);
}
@Test
public void shouldUpdateDocumentOnMatchingVersion() throws Exception {
client.delete("versionedClass:5").get();
VersionedClass versionedClass = new VersionedClass("versionedClass:5", "foobar");
template.insert(versionedClass);
long version1 = versionedClass.getVersion();
versionedClass.setField("foobar2");
template.update(versionedClass);
long version2 = versionedClass.getVersion();
assertTrue(version1 > 0);
assertTrue(version2 > 0);
assertNotEquals(version1, version2);
assertEquals("foobar2", template.findById("versionedClass:5", VersionedClass.class).getField());
}
@Test(expected = OptimisticLockingFailureException.class)
public void shouldNotUpdateDocumentOnNotMatchingVersion() throws Exception {
client.delete("versionedClass:6").get();
VersionedClass versionedClass = new VersionedClass("versionedClass:6", "foobar");
template.insert(versionedClass);
assertTrue(client.set("versionedClass:6", "different").get());
versionedClass.setField("foobar2");
template.update(versionedClass);
}
@Test
public void shouldLoadVersionPropertyOnFind() throws Exception {
client.delete("versionedClass:7").get();
VersionedClass versionedClass = new VersionedClass("versionedClass:7", "foobar");
template.insert(versionedClass);
assertTrue(versionedClass.getVersion() > 0);
VersionedClass foundClass = template.findById("versionedClass:7", VersionedClass.class);
assertEquals(versionedClass.getVersion(), foundClass.getVersion());
}
/**
* A sample document with just an id and property.
*/
@Document
static class SimplePerson {
@Id
private final String id;
@Field
private final String name;
public SimplePerson(String id, String name) {
this.id = id;
this.name = name;
}
}
/**
* A sample document that expires in 2 seconds.
*/
@Document(expiry = 2)
static class DocumentWithExpiry {
@Id
private final String id;
public DocumentWithExpiry(String id) {
this.id = id;
}
}
@Document
static class ComplexPerson {
@Id
private final String id;
@Field
private final List<String> firstnames;
@Field
private final List<Integer> votes;
@Field
private final Map<String, Boolean> info1;
@Field
private final Map<String, Integer> info2;
public ComplexPerson(String id, List<String> firstnames,
List<Integer> votes, Map<String, Boolean> info1,
Map<String, Integer> info2) {
this.id = id;
this.firstnames = firstnames;
this.votes = votes;
this.info1 = info1;
this.info2 = info2;
}
List<String> getFirstnames() {
return firstnames;
}
List<Integer> getVotes() {
return votes;
}
Map<String, Boolean> getInfo1() {
return info1;
}
Map<String, Integer> getInfo2() {
return info2;
}
String getId() {
return id;
}
}
@Document
static class SimpleWithLong {
@Id
private String id;
private long value;
SimpleWithLong(final String id, final long value) {
this.id = id;
this.value = value;
}
String getId() {
return id;
}
long getValue() {
return value;
}
void setValue(final long value) {
this.value = value;
}
}
static class SimpleWithEnum {
@Id
private String id;
private enum Type {
BIG
}
private Type type;
SimpleWithEnum(final String id, final Type type) {
this.id = id;
this.type = type;
}
String getId() {
return id;
}
void setId(final String id) {
this.id = id;
}
Type getType() {
return type;
}
void setType(final Type type) {
this.type = type;
}
}
static class SimpleWithClass {
@Id
private String id;
private Class<Integer> integerClass;
private String value;
SimpleWithClass(final String id, final Class<Integer> integerClass) {
this.id = id;
this.integerClass = integerClass;
}
String getId() {
return id;
}
void setId(final String id) {
this.id = id;
}
Class<Integer> getIntegerClass() {
return integerClass;
}
void setIntegerClass(final Class<Integer> integerClass) {
this.integerClass = integerClass;
}
String getValue() { return value; }
void setValue(final String value) {
this.value = value;
}
}
static class VersionedClass {
@Id
private String id;
@Version
private long version;
private String field;
VersionedClass(String id, String field) {
this.id = id;
this.field = field;
}
public String getId() {
return id;
}
public long getVersion() {
return version;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
}
}

View File

@@ -1,54 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.core;
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.protocol.views.DesignDocument;
import com.couchbase.client.protocol.views.ViewDesign;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
/**
* @author Michael Nitschinger
*/
public class CouchbaseTemplateViewListener extends DependencyInjectionTestExecutionListener {
@Override
public void beforeTestClass(final TestContext testContext) throws Exception {
CouchbaseClient client = (CouchbaseClient) testContext.getApplicationContext().getBean("couchbaseClient");
populateTestData(client);
createAndWaitForDesignDocs(client);
}
private void populateTestData(CouchbaseClient client) {
CouchbaseTemplate template = new CouchbaseTemplate(client);
for(int i=0;i < 100; i++) {
Beer b = new Beer("testbeer-" + i).setName("MyBeer " + i).setActive(true);
template.save(b);
}
}
private void createAndWaitForDesignDocs(CouchbaseClient client) {
DesignDocument designDoc = new DesignDocument("test_beers");
String mapFunction = "function (doc, meta) { if(doc._class == "
+ "\"org.springframework.data.couchbase.core.Beer\") { emit(doc.name, null); } }";
designDoc.setView(new ViewDesign("by_name", mapFunction));
client.createDesignDoc(designDoc);
}
}

View File

@@ -16,11 +16,13 @@
package org.springframework.data.couchbase.core.convert.translation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.couchbase.core.mapping.CouchbaseDocument;
import static org.junit.Assert.assertEquals;
import org.springframework.data.couchbase.core.mapping.CouchbaseDocument;
/**
* Verifies the functionality of a {@link JacksonTranslationService}.
@@ -29,26 +31,39 @@ import static org.junit.Assert.assertEquals;
*/
public class JacksonTranslationServiceTests {
private TranslationService service;
private TranslationService service;
@Before
public void setup() {
service = new JacksonTranslationService();
}
@Before
public void setup() {
service = new JacksonTranslationService();
((JacksonTranslationService) service).afterPropertiesSet();
}
@Test
public void shouldEncodeNonASCII() {
CouchbaseDocument doc = new CouchbaseDocument("key");
doc.put("language", "русский");
String expected = "{\"language\":\"русский\"}";
assertEquals(expected, service.encode(doc));
}
@Test
public void shouldEncodeNonASCII() {
CouchbaseDocument doc = new CouchbaseDocument("key");
doc.put("language", "русский");
String expected = "{\"language\":\"русский\"}";
assertEquals(expected, service.encode(doc));
}
@Test
public void shouldDecodeNonASCII() {
String source = "{\"language\":\"русский\"}";
CouchbaseDocument target = new CouchbaseDocument();
service.decode(source, target);
assertEquals("русский", target.get("language"));
}
@Test
public void shouldDecodeNonASCII() {
String source = "{\"language\":\"русский\"}";
CouchbaseDocument target = new CouchbaseDocument();
service.decode(source, target);
assertEquals("русский", target.get("language"));
}
@Test
public void shouldDecodeAdHocFragment() {
String source = "{\"language\":\"french\"}";
LanguageFragment f = service.decodeFragment(source, LanguageFragment.class);
assertNotNull(f);
assertEquals("french", f.language);
}
private static class LanguageFragment {
public String language;
}
}

View File

@@ -16,18 +16,19 @@
package org.springframework.data.couchbase.core.mapping;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.Field;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.annotation.Id;
import org.springframework.data.mapping.model.PropertyNameFieldNamingStrategy;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.util.ClassTypeInformation;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import static org.junit.Assert.assertEquals;
/**
* Verifies the correct behavior of properties on persistable objects.
*
@@ -46,7 +47,7 @@ public class BasicCouchbasePersistentPropertyTests {
@Before
public void setUp() {
entity = new BasicCouchbasePersistentEntity<Beer>(
ClassTypeInformation.from(Beer.class));
ClassTypeInformation.from(Beer.class));
}
/**
@@ -75,7 +76,7 @@ public class BasicCouchbasePersistentPropertyTests {
*/
private CouchbasePersistentProperty getPropertyFor(Field field) {
return new BasicCouchbasePersistentProperty(field, null, entity,
new SimpleTypeHolder(), PropertyNameFieldNamingStrategy.INSTANCE);
new SimpleTypeHolder(), PropertyNameFieldNamingStrategy.INSTANCE);
}
/**

View File

@@ -16,34 +16,37 @@
package org.springframework.data.couchbase.core.mapping;
import static org.junit.Assert.assertEquals;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.annotation.Id;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.couchbase.TestApplicationConfig;
import org.springframework.data.couchbase.UnitTestApplicationConfig;
import org.springframework.data.couchbase.core.convert.CustomConversions;
import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import static org.junit.Assert.assertEquals;
/**
* Tests to verify custom mapping logic.
*
* @author Michael Nitschinger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplicationConfig.class)
@ContextConfiguration(classes = UnitTestApplicationConfig.class)
public class CustomConvertersTests {
@Autowired
@@ -161,9 +164,9 @@ public class CustomConvertersTests {
@Override
public CouchbaseDocument convert(BlogPost source) {
return new CouchbaseDocument()
.setId(source.id)
.put("title", source.title)
.put("slug", source.title.toLowerCase().replaceAll(" ", "_"));
.setId(source.id)
.put("title", source.title)
.put("slug", source.title.toLowerCase().replaceAll(" ", "_"));
}
}

View File

@@ -16,20 +16,7 @@
package org.springframework.data.couchbase.core.mapping;
import org.joda.time.LocalDateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.annotation.Id;
import org.springframework.data.couchbase.TestApplicationConfig;
import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter;
import org.springframework.data.mapping.model.MappingException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.data.couchbase.core.convert.CustomConversions;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.util.ArrayList;
@@ -46,15 +33,27 @@ import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.joda.time.LocalDateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.annotation.Id;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.couchbase.UnitTestApplicationConfig;
import org.springframework.data.couchbase.core.convert.CustomConversions;
import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter;
import org.springframework.data.mapping.model.MappingException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Michael Nitschinger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplicationConfig.class)
@ContextConfiguration(classes = UnitTestApplicationConfig.class)
public class MappingCouchbaseConverterTests {
@Autowired
@@ -86,7 +85,7 @@ public class MappingCouchbaseConverterTests {
@Test(expected = MappingException.class)
public void needsIDOnEntity() {
converter.write(new EntityWithoutID("foo"),
new CouchbaseDocument());
new CouchbaseDocument());
}
@Test
@@ -226,7 +225,7 @@ public class MappingCouchbaseConverterTests {
Map<String, Boolean> attr1 = new TreeMap<String, Boolean>();
Map<Integer, String> attr2 = new LinkedHashMap<Integer, String>();
Map<String, Map<String, String>> attr3 =
new HashMap<String, Map<String, String>>();
new HashMap<String, Map<String, String>>();
attr0.put("foo", "bar");
attr1.put("bar", true);
@@ -374,7 +373,7 @@ public class MappingCouchbaseConverterTests {
ValueEntity readConverted = converter.read(ValueEntity.class, source);
assertEquals(addy.emailAddr, readConverted.email.emailAddr);
assertEquals(listOfEmails.get(0).emailAddr,
readConverted.listOfEmails.get(0).emailAddr);
readConverted.listOfEmails.get(0).emailAddr);
}
@Test
@@ -486,6 +485,7 @@ public class MappingCouchbaseConverterTests {
static class EntityWithoutID {
private String attr0;
public EntityWithoutID(String a0) {
attr0 = a0;
}
@@ -499,6 +499,7 @@ public class MappingCouchbaseConverterTests {
static class StringEntity extends BaseEntity {
private String attr0;
public StringEntity(String attr0) {
this.attr0 = attr0;
}
@@ -506,6 +507,7 @@ public class MappingCouchbaseConverterTests {
static class NumberEntity extends BaseEntity {
private long attr0;
public NumberEntity(long attr0) {
this.attr0 = attr0;
}
@@ -513,6 +515,7 @@ public class MappingCouchbaseConverterTests {
static class BooleanEntity extends BaseEntity {
private boolean attr0;
public BooleanEntity(boolean attr0) {
this.attr0 = attr0;
}
@@ -523,6 +526,7 @@ public class MappingCouchbaseConverterTests {
private int attr1;
private double attr2;
private boolean attr3;
public MixedSimpleEntity(String attr0, int attr1, double attr2, boolean attr3) {
this.attr0 = attr0;
this.attr1 = attr1;
@@ -542,6 +546,7 @@ public class MappingCouchbaseConverterTests {
private Map<String, Boolean> attr1;
private Map<Integer, String> attr2;
private Map<String, Map<String, String>> attr3;
public MapEntity(Map<String, String> attr0, Map<String, Boolean> attr1, Map<Integer, String> attr2, Map<String, Map<String, String>> attr3) {
this.attr0 = attr0;
this.attr1 = attr1;
@@ -554,6 +559,7 @@ public class MappingCouchbaseConverterTests {
private List<String> attr0;
private List<Integer> attr1;
private List<List<String>> attr2;
ListEntity(List<String> attr0, List<Integer> attr1, List<List<String>> attr2) {
this.attr0 = attr0;
this.attr1 = attr1;
@@ -565,6 +571,7 @@ public class MappingCouchbaseConverterTests {
private Set<String> attr0;
private Set<Integer> attr1;
private Set<Set<String>> attr2;
SetEntity(Set<String> attr0, Set<Integer> attr1, Set<Set<String>> attr2) {
this.attr0 = attr0;
this.attr1 = attr1;
@@ -584,6 +591,7 @@ public class MappingCouchbaseConverterTests {
static class Email {
private String emailAddr;
public Email(String emailAddr) {
this.emailAddr = emailAddr;
}
@@ -615,6 +623,7 @@ public class MappingCouchbaseConverterTests {
static class CustomObject {
private BigDecimal weight;
public CustomObject(BigDecimal weight) {
this.weight = weight;
}

View File

@@ -16,8 +16,11 @@
package org.springframework.data.couchbase.core.mapping.event;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.springframework.test.context.ContextConfiguration;
@@ -25,8 +28,6 @@ import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import static org.junit.Assert.assertEquals;
/**
* @author Michael Nitschinger
*/
@@ -49,9 +50,9 @@ public class AbstractCouchbaseEventListenerTests {
couchbaseTemplate.save(new User("john smith", 18));
assertEquals(beforeSave+1, eventListener.onBeforeSaveEvents.size());
assertEquals(afterSave+1, eventListener.onAfterSaveEvents.size());
assertEquals(beforeConvert+1, eventListener.onBeforeConvertEvents.size());
assertEquals(beforeSave + 1, eventListener.onBeforeSaveEvents.size());
assertEquals(afterSave + 1, eventListener.onAfterSaveEvents.size());
assertEquals(beforeConvert + 1, eventListener.onBeforeConvertEvents.size());
}
}

View File

@@ -18,14 +18,14 @@ package org.springframework.data.couchbase.core.mapping.event;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.couchbase.TestApplicationConfig;
import org.springframework.data.couchbase.UnitTestApplicationConfig;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
/**
* @author Michael Nitschinger
*/
@Configuration
public class EventContextConfiguration extends TestApplicationConfig {
public class EventContextConfiguration extends UnitTestApplicationConfig {
@Bean
public LocalValidatorFactoryBean validator() {

View File

@@ -16,10 +16,10 @@
package org.springframework.data.couchbase.core.mapping.event;
import org.springframework.data.couchbase.core.mapping.CouchbaseDocument;
import java.util.ArrayList;
import org.springframework.data.couchbase.core.mapping.CouchbaseDocument;
/**
* @author Michael Nitschinger
*/

View File

@@ -16,11 +16,11 @@
package org.springframework.data.couchbase.core.mapping.event;
import org.springframework.data.annotation.Id;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
import org.springframework.data.annotation.Id;
/**
* @author Michael Nitschinger
*/

View File

@@ -16,19 +16,20 @@
package org.springframework.data.couchbase.core.mapping.event;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import javax.validation.ConstraintViolationException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.validation.ConstraintViolationException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* @author Michael Nitschinger
*/
@@ -46,7 +47,8 @@ public class ValidatingCouchbaseEventListenerTests {
try {
template.save(user);
fail();
} catch (ConstraintViolationException e) {
}
catch (ConstraintViolationException e) {
assertThat(e.getConstraintViolations().size(), equalTo(2));
}
}

View File

@@ -1,60 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.monitor;
import com.couchbase.client.CouchbaseClient;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.couchbase.TestApplicationConfig;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertFalse;
/**
* @author Michael Nitschinger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplicationConfig.class)
public class ClientInfoTests {
/**
* Contains a reference to the actual CouchbaseClient.
*/
@Autowired
private CouchbaseClient client;
private ClientInfo ci;
@Before
public void setup() throws Exception {
ci = new ClientInfo(client);
}
@Test
public void hostNames() {
String hostnames = ci.getHostNames();
assertThat(hostnames, not(isEmptyString()));
}
}

View File

@@ -1,61 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.monitor;
import com.couchbase.client.CouchbaseClient;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.couchbase.TestApplicationConfig;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
/**
* @author Michael Nitschinger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplicationConfig.class)
public class ClusterInfoTests {
/**
* Contains a reference to the actual CouchbaseClient.
*/
@Autowired
private CouchbaseClient client;
private ClusterInfo ci;
@Before
public void setup() throws Exception {
ci = new ClusterInfo(client);
}
@Test
public void totalDiskAssigned() {
assertThat(ci.getTotalDiskAssigned(), greaterThan(0L));
}
@Test
public void totalRAMUsed() {
assertThat(ci.getTotalRAMUsed(), greaterThan(0L));
}
}

View File

@@ -1,60 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository;
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.protocol.views.DesignDocument;
import com.couchbase.client.protocol.views.ViewDesign;
import net.spy.memcached.PersistTo;
import net.spy.memcached.ReplicateTo;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
/**
* @author Michael Nitschinger
*/
public class CouchbaseRepositoryViewListener extends DependencyInjectionTestExecutionListener {
@Override
public void beforeTestClass(final TestContext testContext) throws Exception {
CouchbaseClient client = (CouchbaseClient) testContext.getApplicationContext().getBean("couchbaseClient");
populateTestData(client);
createAndWaitForDesignDocs(client);
}
private void populateTestData(final CouchbaseClient client) {
CouchbaseTemplate template = new CouchbaseTemplate(client);
for (int i = 0; i < 100; i++) {
template.save(new User("testuser-" + i, "uname-" + i), PersistTo.MASTER, ReplicateTo.ZERO);
}
}
private void createAndWaitForDesignDocs(final CouchbaseClient client) {
DesignDocument designDoc = new DesignDocument("user");
String mapFunction = "function (doc, meta) { if(doc._class == \"org.springframework.data.couchbase.repository.User\") { emit(null, null); } }";
designDoc.setView(new ViewDesign("customFindAllView", mapFunction, "_count"));
client.createDesignDoc(designDoc);
designDoc = new DesignDocument("userCustom");
designDoc.setView(new ViewDesign("customCountView", mapFunction, "_count"));
client.createDesignDoc(designDoc);
}
}

View File

@@ -1,81 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository;
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.protocol.views.Query;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.data.couchbase.TestApplicationConfig;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.springframework.data.couchbase.repository.support.CouchbaseRepositoryFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static com.couchbase.client.protocol.views.Stale.FALSE;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author David Harrigan
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplicationConfig.class)
@TestExecutionListeners(CouchbaseRepositoryViewListener.class)
public class CouchbaseRepositoryViewTests {
@Autowired
private CouchbaseClient client;
@Autowired
private CouchbaseTemplate template;
private CustomUserRepository repository;
@Before
public void setup() throws Exception {
repository = new CouchbaseRepositoryFactory(template).getRepository(CustomUserRepository.class);
}
@Test
public void shouldFindAllWithCustomView() {
client.query(client.getView("user", "customFindAllView"), new Query().setStale(FALSE));
Iterable<User> allUsers = repository.findAll();
int i = 0;
for (final User allUser : allUsers) {
i++;
}
assertThat(i, is(100));
}
@Test
public void shouldCountWithCustomView() {
client.query(client.getView("userCustom", "customCountView"), new Query().setStale(FALSE));
final long value = repository.count();
assertThat(value, is(100L));
}
@Test(expected = InvalidDataAccessResourceUsageException.class)
public void shouldTrimOffFindOnCustomFinder() {
repository.findAllSomething();
}
}

View File

@@ -1,36 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository;
import org.springframework.data.couchbase.core.view.View;
/**
* @author David Harrigan
*/
public interface CustomUserRepository extends CouchbaseRepository<User, String> {
@Override
@View(designDocument = "user", viewName = "customFindAllView")
Iterable<User> findAll();
@Override
@View(designDocument = "userCustom", viewName = "customCountView")
long count();
Iterable<User> findAllSomething();
}

View File

@@ -1,58 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository;
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.protocol.views.DesignDocument;
import com.couchbase.client.protocol.views.ViewDesign;
import net.spy.memcached.PersistTo;
import net.spy.memcached.ReplicateTo;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
/**
* @author Michael Nitschinger
*/
public class SimpleCouchbaseRepositoryListener extends DependencyInjectionTestExecutionListener {
@Override
public void beforeTestClass(final TestContext testContext) throws Exception {
CouchbaseClient client = (CouchbaseClient) testContext.getApplicationContext().getBean("couchbaseClient");
populateTestData(client);
createAndWaitForDesignDocs(client);
}
private void populateTestData(CouchbaseClient client) {
CouchbaseTemplate template = new CouchbaseTemplate(client);
for (int i = 0; i < 100; i++) {
User u = new User("testuser-" + i, "uname-" + i);
template.save(u, PersistTo.MASTER, ReplicateTo.ZERO);
}
}
private void createAndWaitForDesignDocs(CouchbaseClient client) {
DesignDocument designDoc = new DesignDocument("user");
String mapFunction = "function (doc, meta) { if(doc._class == \"org.springframework.data.couchbase.repository." +
"User\") { emit(null, null); } }";
designDoc.setView(new ViewDesign("all", mapFunction, "_count"));
client.createDesignDoc(designDoc);
}
}

View File

@@ -1,114 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository;
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.protocol.views.Query;
import com.couchbase.client.protocol.views.Stale;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.couchbase.TestApplicationConfig;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.springframework.data.couchbase.repository.support.CouchbaseRepositoryFactory;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
/**
* @author Michael Nitschinger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplicationConfig.class)
@TestExecutionListeners(SimpleCouchbaseRepositoryListener.class)
public class SimpleCouchbaseRepositoryTests {
@Autowired
private CouchbaseClient client;
@Autowired
private CouchbaseTemplate template;
private UserRepository repository;
@Before
public void setup() throws Exception {
RepositoryFactorySupport factory = new CouchbaseRepositoryFactory(template);
repository = factory.getRepository(UserRepository.class);
}
@Test
public void simpleCrud() {
String key = "my_unique_user_key";
User instance = new User(key, "foobar");
repository.save(instance);
User found = repository.findOne(key);
assertEquals(instance.getKey(), found.getKey());
assertEquals(instance.getUsername(), found.getUsername());
assertTrue(repository.exists(key));
repository.delete(found);
assertNull(repository.findOne(key));
assertFalse(repository.exists(key));
}
@Test
/**
* This test uses/assumes a default viewName called "all" that is configured on Couchbase.
*/
public void shouldFindAll() {
// do a non-stale query to populate data for testing.
client.query(client.getView("user", "all"), new Query().setStale(Stale.FALSE));
Iterable<User> allUsers = repository.findAll();
int size = 0;
for (User u : allUsers) {
size++;
assertNotNull(u.getKey());
assertNotNull(u.getUsername());
}
assertEquals(100, size);
}
@Test
public void shouldCount() {
// do a non-stale query to populate data for testing.
client.query(client.getView("user", "all"), new Query().setStale(Stale.FALSE));
assertEquals(100, repository.count());
}
@Test
public void shouldFindCustom() {
Iterable<User> users = repository.customViewQuery(new Query().setLimit(2).setStale(Stale.FALSE));
int size = 0;
for (User u : users) {
size++;
assertNotNull(u.getKey());
assertNotNull(u.getUsername());
}
assertEquals(2, size);
}
}

View File

@@ -1,44 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository;
import org.springframework.data.annotation.Id;
/**
* @author Michael Nitschinger
*/
public class User {
@Id
private final String key;
private final String username;
public User(String key, String username) {
this.key = key;
this.username = username;
}
public String getUsername() {
return username;
}
public String getKey() {
return key;
}
}

View File

@@ -1,30 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository;
import com.couchbase.client.protocol.views.Query;
import org.springframework.data.couchbase.core.view.View;
/**
* @author Michael Nitschinger
*/
public interface UserRepository extends CouchbaseRepository<User, String> {
@View(designDocument = "user", viewName = "all")
Iterable<User> customViewQuery(Query query);
}

View File

@@ -1,27 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository.cdi;
import org.springframework.data.couchbase.repository.CouchbaseRepository;
import org.springframework.data.couchbase.repository.User;
/**
* @author Mark Paluch
*/
public interface CdiPersonRepository extends CouchbaseRepository<Person, String>, CdiPersonRepositoryCustom {
}

View File

@@ -1,26 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository.cdi;
/**
* @author Mark Paluch
*/
public interface CdiPersonRepositoryCustom {
int returnTwo();
}

View File

@@ -1,28 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository.cdi;
/**
* @author Mark Paluch
*/
public class CdiPersonRepositoryImpl implements CdiPersonRepositoryCustom {
@Override
public int returnTwo() {
return 2;
}
}

View File

@@ -1,42 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository.cdi;
import javax.inject.Inject;
import com.couchbase.client.CouchbaseClient;
import org.springframework.data.couchbase.repository.UserRepository;
/**
* @author Mark Paluch
*/
class CdiRepositoryClient {
@Inject
private CdiPersonRepository cdiPersonRepository;
@Inject
private CouchbaseClient couchbaseClient;
public CdiPersonRepository getCdiPersonRepository() {
return cdiPersonRepository;
}
public CouchbaseClient getCouchbaseClient() {
return couchbaseClient;
}
}

View File

@@ -1,102 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository.cdi;
import static org.junit.Assert.*;
import org.apache.webbeans.cditest.CdiTestContainer;
import org.apache.webbeans.cditest.CdiTestContainerLoader;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.protocol.views.DesignDocument;
import com.couchbase.client.protocol.views.ViewDesign;
/**
* @author Mark Paluch
*/
public class CdiRepositoryTests {
private static CdiTestContainer cdiContainer;
private CdiPersonRepository repository;
private CouchbaseClient couchbaseClient;
@BeforeClass
public static void init() throws Exception {
cdiContainer = CdiTestContainerLoader.getCdiContainer();
cdiContainer.startApplicationScope();
cdiContainer.bootContainer();
}
@AfterClass
public static void shutdown() throws Exception {
cdiContainer.stopContexts();
cdiContainer.shutdownContainer();
}
@Before
public void setUp() {
CdiRepositoryClient repositoryClient = cdiContainer.getInstance(CdiRepositoryClient.class);
repository = repositoryClient.getCdiPersonRepository();
couchbaseClient = repositoryClient.getCouchbaseClient();
createAndWaitForDesignDocs(couchbaseClient);
}
private void createAndWaitForDesignDocs(CouchbaseClient client) {
DesignDocument designDoc = new DesignDocument("person");
String mapFunction = "function (doc, meta) { if(doc._class == \"" + Person.class.getName()
+ "\") { emit(null, null); } }";
designDoc.setView(new ViewDesign("all", mapFunction, "_count"));
client.createDesignDoc(designDoc);
}
/**
* @see DATACOUCH-109
*/
@Test
public void testCdiRepository() {
assertNotNull(repository);
repository.deleteAll();
Person bean = new Person("key", "username");
repository.save(bean);
assertTrue(repository.exists(bean.getId()));
Person retrieved = repository.findOne(bean.getId());
assertNotNull(retrieved);
assertEquals(bean.getName(), retrieved.getName());
assertEquals(bean.getId(), retrieved.getId());
}
/**
* @see DATACOUCH-109
*/
@Test
public void testCustomRepository() {
assertEquals(2, repository.returnTwo());
}
}

View File

@@ -1,45 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository.cdi;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import org.springframework.data.couchbase.core.CouchbaseFactoryBean;
import com.couchbase.client.CouchbaseClient;
/**
* Producer for {@link CouchbaseClient}. Defaults from {@link CouchbaseFactoryBean} are sufficient for our test.
*
* @author Mark Paluch
*/
class CouchbaseClientProducer {
@Produces
public CouchbaseClient createCouchbaseClient() throws Exception {
CouchbaseFactoryBean couchbaseFactoryBean = new CouchbaseFactoryBean();
couchbaseFactoryBean.setBucket("default");
couchbaseFactoryBean.afterPropertiesSet();
return couchbaseFactoryBean.getObject();
}
public void close(@Disposes CouchbaseClient couchbaseClient) {
couchbaseClient.shutdown();
}
}

View File

@@ -1,40 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository.cdi;
import javax.enterprise.inject.Produces;
import org.springframework.data.couchbase.core.CouchbaseOperations;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import com.couchbase.client.CouchbaseClient;
/**
* Produces a {@link CouchbaseOperations} instance for test usage.
* @author Mark Paluch
*/
class CouchbaseOperationsProducer {
@Produces
public CouchbaseOperations createCouchbaseOperations(CouchbaseClient couchbaseClient) throws Exception {
CouchbaseTemplate couchbaseTemplate = new CouchbaseTemplate(couchbaseClient);
return couchbaseTemplate;
}
}

View File

@@ -1,53 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.couchbase.repository.cdi;
import org.springframework.data.annotation.Id;
import org.springframework.data.couchbase.core.mapping.Field;
/**
* @author Mark Paluch
*/
public class Person {
@Id private String id;
@Field private String name;
public Person() {}
public Person(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}