Adding tests with embedded cassandra support

This commit is contained in:
sameira 2015-11-30 22:46:32 +05:30
parent 24094c838a
commit 51649533ee
11 changed files with 216 additions and 228 deletions

View File

@ -11,8 +11,8 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.data.version>1.1.0.RELEASE</org.springframework.data.version>
<org.springframework.version>4.0.7.RELEASE</org.springframework.version>
<org.springframework.data.version>1.3.1.RELEASE</org.springframework.data.version>
<org.springframework.version>4.2.2.RELEASE</org.springframework.version>
<junit.version>4.11</junit.version>
<org.slf4j.version>1.7.12</org.slf4j.version>
<logback.version>1.1.3</logback.version>
@ -49,9 +49,53 @@
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit-spring</artifactId>
<version>2.1.3.1</version>
<version>2.1.9.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit-shaded</artifactId>
<version>2.1.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hectorclient</groupId>
<artifactId>hector-core</artifactId>
<version>2.0-0</version>
<!--<exclusions>-->
<!--<exclusion>-->
<!--<groupId>org.slf4j</groupId>-->
<!--<artifactId>slf4j-log4j12</artifactId>-->
<!--</exclusion>-->
<!--<exclusion>-->
<!--<groupId>commons-lang</groupId>-->
<!--<artifactId>commons-lang</artifactId>-->
<!--</exclusion>-->
<!--<exclusion>-->
<!--<groupId>com.google.guava</groupId>-->
<!--<artifactId>guava</artifactId>-->
<!--</exclusion>-->
<!--</exclusions>-->
</dependency>
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>2.1.5</version>
<optional>true</optional>
<!--<exclusions>-->
<!--<exclusion>-->
<!--<groupId>com.google.guava</groupId>-->
<!--<artifactId>guava</artifactId>-->
<!--</exclusion>-->
<!--</exclusions>-->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
@ -84,8 +128,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>

View File

@ -1,8 +1,12 @@
package org.baeldung.spring.data.cassandra.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.java.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext;
@ -10,19 +14,26 @@ import org.springframework.data.cassandra.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
@Configuration
@PropertySource(value = { "classpath:cassandra.properties" })
@EnableCassandraRepositories(basePackages = "org.baeldung.spring.data.cassandra.repository")
public class CassandraConfig extends AbstractCassandraConfiguration {
private static final Log LOGGER = LogFactory.getLog(CassandraConfig.class);
@Autowired
private Environment environment;
@Override
protected String getKeyspaceName() {
return "event";
return environment.getProperty("cassandra.keyspace");
}
@Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints("127.0.0.1");
cluster.setPort(9142);
cluster.setContactPoints(environment.getProperty("cassandra.contactpoints"));
cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port")));
LOGGER.info("Cluster created with contact points ["+ environment.getProperty("cassandra.contactpoints") +"] " +
"& port [" + Integer.parseInt(environment.getProperty("cassandra.port")) + "].");
return cluster;
}

View File

@ -0,0 +1,46 @@
package org.baeldung.spring.data.cassandra.model;
import org.springframework.cassandra.core.Ordering;
import org.springframework.cassandra.core.PrimaryKeyType;
import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.PrimaryKeyColumn;
import org.springframework.data.cassandra.mapping.Table;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@Table
public class Book {
@PrimaryKeyColumn(name = "isbn", ordinal = 2, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING)
private UUID id;
@PrimaryKeyColumn(name = "title", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
private String title;
@PrimaryKeyColumn(name = "publisher", ordinal = 1, type = PrimaryKeyType.PARTITIONED)
private String publisher;
@Column
private Set<String> tags = new HashSet<>();
public Book(UUID id, String title, String publisher, Set<String> tags) {
this.id = id;
this.title = title;
this.publisher = publisher;
this.tags.addAll(tags);
}
public UUID getId() {
return id;
}
public String getTitle() {
return title;
}
public String getPublisher() {
return publisher;
}
public Set getTags() {
return tags;
}
}

View File

@ -1,46 +0,0 @@
package org.baeldung.spring.data.cassandra.model;
import org.springframework.cassandra.core.Ordering;
import org.springframework.cassandra.core.PrimaryKeyType;
import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.PrimaryKeyColumn;
import org.springframework.data.cassandra.mapping.Table;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@Table
public class Event {
@PrimaryKeyColumn(name = "id", ordinal = 2, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING)
private UUID id;
@PrimaryKeyColumn(name = "type", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
private String type;
@PrimaryKeyColumn(name = "bucket", ordinal = 1, type = PrimaryKeyType.PARTITIONED)
private String bucket;
@Column
private Set tags = new HashSet();
public Event(UUID id, String type, String bucket, Set tags) {
this.id = id;
this.type = type;
this.bucket = bucket;
this.tags.addAll(tags);
}
public UUID getId() {
return id;
}
public String getType() {
return type;
}
public String getBucket() {
return bucket;
}
public Set getTags() {
return tags;
}
}

View File

@ -0,0 +1,14 @@
package org.baeldung.spring.data.cassandra.repository;
import org.baeldung.spring.data.cassandra.model.Book;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface BookRepository extends CassandraRepository<Book> {
@Query("select * from book where title = ?0 and publisher=?1")
Iterable<Book> findByTitleAndPublisher(String title, String publisher);
}

View File

@ -1,14 +0,0 @@
package org.baeldung.spring.data.cassandra.repository;
import org.baeldung.spring.data.cassandra.model.Event;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface EventRepository extends CassandraRepository<Event> {
@Query("select * from event where type = ?0 and bucket=?1")
Iterable<Event> findByTypeAndBucket(String type, String bucket);
}

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cassandra="http://www.springframework.org/schema/data/cassandra"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<cassandra:session keyspace-name="testKeySpace" />
<!-- REQUIRED: The Default Cassandra Mapping Context used by CassandraConverter -->
<cassandra:mapping />
<!-- REQUIRED: The Default Cassandra Converter used by CassandraTemplate -->
<cassandra:converter />
<!-- REQUIRED: The Cassandra Template is the building block of all Spring
Data Cassandra -->
<cassandra:template id="cassandraTemplate" />
</beans>

View File

@ -0,0 +1,3 @@
cassandra.contactpoints=127.0.0.1
cassandra.port=9142
cassandra.keyspace=testKeySpace

View File

@ -1,66 +0,0 @@
package org.baeldung.spring.data.cassandra.config;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.thrift.transport.TTransportException;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.CassandraSessionFactoryBean;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.convert.CassandraConverter;
import org.springframework.data.cassandra.convert.MappingCassandraConverter;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext;
import org.springframework.data.cassandra.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
import java.io.IOException;
@Configuration
@EnableCassandraRepositories(basePackages = "org.baeldung.spring.data.cassandra.repository")
public class CassandraTestConfig{
@Bean(destroyMethod = "close")
public Cluster cluster() throws ConfigurationException, TTransportException, IOException, InterruptedException{
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
Session session = cluster.connect();
session.execute("CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = {"
+ " 'class': 'SimpleStrategy', "
+ " 'replication_factor': '3' "
+ "};" );
// session.execute("CREATE KEYSPACE testKeySpace WITH replication={'class' : 'SimpleStrategy', 'replication_factor':1}");
// session.execute("USE testKeySpace");
return cluster;
}
@Bean
public CassandraMappingContext mappingContext() {
return new BasicCassandraMappingContext();
}
@Bean
public CassandraConverter converter() {
return new MappingCassandraConverter(mappingContext());
}
@Bean
public CassandraSessionFactoryBean session() throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(cluster());
session.setKeyspaceName("testKeySpace");
session.setConverter(converter());
session.setSchemaAction(SchemaAction.NONE);
return session;
}
@Bean
public CassandraOperations cassandraTemplate() throws Exception {
return new CassandraTemplate(session().getObject());
}
}

View File

@ -0,0 +1,89 @@
package org.baeldung.spring.data.cassandra.repository;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.utils.UUIDs;
import com.google.common.collect.ImmutableSet;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.thrift.transport.TTransportException;
import org.baeldung.spring.data.cassandra.config.CassandraConfig;
import org.baeldung.spring.data.cassandra.model.Book;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cassandra.core.cql.CqlIdentifier;
import org.springframework.data.cassandra.core.CassandraAdminOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CassandraConfig.class)
public class BookRepositoryIntegrationTest {
private static final Log LOGGER = LogFactory.getLog(BookRepositoryIntegrationTest.class);
public static final String KEYSPACE_CREATION_QUERY =
"CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };";
public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;";
public static final String DATA_TABLE_NAME = "book";
@Autowired private BookRepository bookRepository;
@Autowired private CassandraAdminOperations adminTemplate;
@BeforeClass
public static void startCassandraEmbedded()
throws InterruptedException, TTransportException, ConfigurationException, IOException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
LOGGER.info("Server Started at 127.0.0.1:9142... ");
Session session = cluster.connect();
session.execute(KEYSPACE_CREATION_QUERY);
session.execute(KEYSPACE_ACTIVATE_QUERY);
LOGGER.info("KeySpace created and activated.");
}
@Before
public void resetKeySpace()
throws InterruptedException, TTransportException, ConfigurationException, IOException {
adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<String, Object>());
}
@Test
public void whenSavingBooks_thenAvailableOnRetrieval() {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
bookRepository.save(ImmutableSet.of(javaBook));
Iterable<Book> books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media");
assertEquals(javaBook.getId(), books.iterator().next().getId());
}
@Test(expected = java.util.NoSuchElementException.class)
public void whenDeletingExistingBooks_thenNotAvailableOnRetrieval() {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
bookRepository.save(ImmutableSet.of(javaBook));
bookRepository.delete(javaBook);
Iterable<Book> books = bookRepository.findByTitleAndPublisher("type1", "O'Reilly Media");
assertNotEquals(javaBook.getId(), books.iterator().next().getId());
}
@After
public void cleanTable() {
adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME));
}
@AfterClass
public static void stopCassandraEmbedded() {
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
}
}

View File

@ -1,73 +0,0 @@
package org.baeldung.spring.data.cassandra.repository;
import com.datastax.driver.core.utils.UUIDs;
import com.google.common.collect.ImmutableSet;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.thrift.transport.TTransportException;
import org.baeldung.spring.data.cassandra.config.CassandraConfig;
import org.baeldung.spring.data.cassandra.model.Event;
import org.cassandraunit.spring.CassandraUnitTestExecutionListener;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cassandra.core.cql.CqlIdentifier;
import org.springframework.data.cassandra.core.CassandraAdminOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import java.io.IOException;
import java.util.HashMap;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {CassandraConfig.class})
@TestExecutionListeners({CassandraUnitTestExecutionListener.class, DependencyInjectionTestExecutionListener.class})
public class EventRepositoryIntegrationTest {
public static final String TIME_BUCKET = "2014-01-01";
@Autowired
private EventRepository eventRepository;
@Autowired
private CassandraAdminOperations adminTemplate;
@Test
public void repositoryStoresAndRetrievesEvents() throws InterruptedException, TTransportException, ConfigurationException, IOException {
adminTemplate.execute("CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = {"
+ " 'class': 'SimpleStrategy', "
+ " 'replication_factor': '3' "
+ "};" );
adminTemplate.dropTable(CqlIdentifier.cqlId("event"));
adminTemplate.createTable(true, CqlIdentifier.cqlId("event"), Event.class, new HashMap<String, Object>());
Event event1 = new Event(UUIDs.timeBased(), "type1", TIME_BUCKET, ImmutableSet.of("tag1", "tag2"));
Event event2 = new Event(UUIDs.timeBased(), "type1", TIME_BUCKET, ImmutableSet.of("tag3"));
eventRepository.save(ImmutableSet.of(event1, event2));
Iterable<Event> events = eventRepository.findByTypeAndBucket("type1", TIME_BUCKET);
assertThat(events, hasItem(event1));
assertThat(events, hasItem(event2));
}
// @Test
public void repositoryDeletesStoredEvents() {
Event event1 = new Event(UUIDs.timeBased(), "type1", TIME_BUCKET, ImmutableSet.of("tag1", "tag2"));
Event event2 = new Event(UUIDs.timeBased(), "type1", TIME_BUCKET, ImmutableSet.of("tag3"));
eventRepository.save(ImmutableSet.of(event1, event2));
eventRepository.delete(event1);
eventRepository.delete(event2);
Iterable<Event> events = eventRepository.findByTypeAndBucket("type1", TIME_BUCKET);
assertThat(events, not(hasItem(event1)));
assertThat(events, not(hasItem(event2)));
}
}