DATACASS-149: Add support for custom implementations in CDI repositories

This commit is contained in:
Mark Paluch
2014-08-08 20:35:07 +02:00
committed by Matthew Adams
parent a362d64d98
commit d069bca9cb
14 changed files with 545 additions and 24 deletions

View File

@@ -143,6 +143,19 @@
<version>2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.openwebbeans.test</groupId>
<artifactId>cditest-owb</artifactId>
<version>${webbeans}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,73 @@
/*
* 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.cassandra.repository.cdi;
import java.lang.annotation.Annotation;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.repository.support.CassandraRepositoryFactory;
import org.springframework.data.repository.cdi.CdiRepositoryBean;
import org.springframework.data.repository.config.CustomRepositoryImplementationDetector;
import org.springframework.util.Assert;
/**
* A bean which represents a Cassandra repository.
*
* @author Mark Paluch
*/
public class CassandraRepositoryBean<T> extends CdiRepositoryBean<T> {
private final Bean<CassandraOperations> cassandraOperationsBean;
/**
* Creates a new {@link CassandraRepositoryBean}.
*
* @param operations must not be {@literal null}.
* @param qualifiers must not be {@literal null}.
* @param repositoryType must not be {@literal null}.
* @param beanManager must not be {@literal null}.
* @param detector detector for the custom {@link org.springframework.data.repository.Repository} implementations
* {@link CustomRepositoryImplementationDetector}, can be {@literal null}.
*/
public CassandraRepositoryBean(Bean<CassandraOperations> operations, Set<Annotation> qualifiers,
Class<T> repositoryType, BeanManager beanManager, CustomRepositoryImplementationDetector detector) {
super(qualifiers, repositoryType, beanManager, detector);
Assert.notNull(operations, "Cannot create repository with 'null' for CassandraOperations.");
this.cassandraOperationsBean = operations;
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.cdi.CdiRepositoryBean#create(javax.enterprise.context.spi.CreationalContext, java.lang.Class, java.lang.Object)
*/
@Override
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType, Object customImplementation) {
CassandraOperations cassandraOperations = getDependencyInstance(cassandraOperationsBean, CassandraOperations.class);
return new CassandraRepositoryFactory(cassandraOperations).getRepository(repositoryType, customImplementation);
}
@Override
public Class<? extends Annotation> getScope() {
return cassandraOperationsBean.getScope();
}
}

View File

@@ -0,0 +1,103 @@
/*
* 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.cassandra.repository.cdi;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.UnsatisfiedResolutionException;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.ProcessBean;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.repository.cdi.CdiRepositoryBean;
import org.springframework.data.repository.cdi.CdiRepositoryExtensionSupport;
/**
* A portable CDI extension which registers beans for Spring Data Cassandra repositories.
*
* @author Mark Paluch
*/
public class CassandraRepositoryExtension extends CdiRepositoryExtensionSupport {
private final Map<String, Bean<CassandraOperations>> cassandraOperationsMap = new HashMap<String, Bean<CassandraOperations>>();
/**
* Implementation of a an observer which checks for CassandraOperations beans and stores them in
* {@link #cassandraOperationsMap} for later association with corresponding repository beans.
*
* @param <T> The type.
* @param processBean The annotated type as defined by CDI.
*/
@SuppressWarnings("unchecked")
<T> void processBean(@Observes ProcessBean<T> processBean) {
Bean<T> bean = processBean.getBean();
for (Type type : bean.getTypes()) {
if (type instanceof Class<?> && CassandraOperations.class.isAssignableFrom((Class<?>) type)) {
cassandraOperationsMap.put(bean.getQualifiers().toString(), ((Bean<CassandraOperations>) bean));
}
}
}
/**
* Implementation of a an observer which registers beans to the CDI container for the detected Spring Data
* repositories.
* <p>
* The repository beans are associated to the EntityManagers using their qualifiers.
*
* @param beanManager The BeanManager instance.
*/
void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) {
for (Map.Entry<Class<?>, Set<Annotation>> entry : getRepositoryTypes()) {
Class<?> repositoryType = entry.getKey();
Set<Annotation> qualifiers = entry.getValue();
CdiRepositoryBean<?> repositoryBean = createRepositoryBean(repositoryType, qualifiers, beanManager);
afterBeanDiscovery.addBean(repositoryBean);
registerBean(repositoryBean);
}
}
/**
* Creates a {@link Bean}.
*
* @param <T> The type of the repository.
* @param repositoryType The class representing the repository.
* @param beanManager The BeanManager instance.
* @return The bean.
*/
private <T> CdiRepositoryBean<T> createRepositoryBean(Class<T> repositoryType, Set<Annotation> qualifiers,
BeanManager beanManager) {
Bean<CassandraOperations> cassandraOperationsBean = this.cassandraOperationsMap.get(qualifiers.toString());
if (cassandraOperationsBean == null) {
throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.",
CassandraOperations.class.getName(), qualifiers));
}
return new CassandraRepositoryBean<T>(cassandraOperationsBean, qualifiers, repositoryType, beanManager,
getCustomImplementationDetector());
}
}

View File

@@ -19,7 +19,7 @@ import java.io.Serializable;
import java.lang.reflect.Method;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.mapping.CassandraPersistentEntity;
import org.springframework.data.cassandra.repository.TypedIdCassandraRepository;
@@ -44,20 +44,20 @@ import org.springframework.util.Assert;
public class CassandraRepositoryFactory extends RepositoryFactorySupport {
private final CassandraTemplate cassandraTemplate;
private final CassandraOperations cassandraTemplate;
private final CassandraMappingContext mappingContext;
/**
* Creates a new {@link MongoRepositoryFactory} with the given {@link MongoOperations}.
* Creates a new {@link CassandraRepositoryFactory} with the given {@link CassandraOperations}.
*
* @param mongoOperations must not be {@literal null}
* @param cassandraOperations must not be {@literal null}
*/
public CassandraRepositoryFactory(CassandraTemplate cassandraTemplate) {
public CassandraRepositoryFactory(CassandraOperations cassandraOperations) {
Assert.notNull(cassandraTemplate);
Assert.notNull(cassandraOperations);
this.cassandraTemplate = cassandraTemplate;
this.mappingContext = cassandraTemplate.getConverter().getMappingContext();
this.cassandraTemplate = cassandraOperations;
this.mappingContext = cassandraOperations.getConverter().getMappingContext();
// TODO: remove when supporting declarative query methods
setQueryLookupStrategyKey(QueryLookupStrategy.Key.USE_DECLARED_QUERY);

View File

@@ -35,7 +35,7 @@ import com.datastax.driver.core.querybuilder.Select;
*/
public class SimpleCassandraRepository<T, ID extends Serializable> implements TypedIdCassandraRepository<T, ID> {
protected CassandraOperations template;
protected CassandraOperations operations;
protected CassandraEntityInformation<T, ID> entityInformation;
/**
@@ -43,45 +43,45 @@ public class SimpleCassandraRepository<T, ID extends Serializable> implements Ty
* {@link CassandraTemplate}.
*
* @param metadata must not be {@literal null}.
* @param template must not be {@literal null}.
* @param operations must not be {@literal null}.
*/
public SimpleCassandraRepository(CassandraEntityInformation<T, ID> metadata, CassandraTemplate template) {
public SimpleCassandraRepository(CassandraEntityInformation<T, ID> metadata, CassandraOperations operations) {
Assert.notNull(template);
Assert.notNull(operations);
Assert.notNull(metadata);
this.entityInformation = metadata;
this.template = template;
this.operations = operations;
}
@Override
public <S extends T> S save(S entity) {
return template.insert(entity);
return operations.insert(entity);
}
@Override
public <S extends T> List<S> save(Iterable<S> entities) {
return template.insert(CollectionUtils.toList(entities));
return operations.insert(CollectionUtils.toList(entities));
}
@Override
public T findOne(ID id) {
return template.selectOneById(entityInformation.getJavaType(), id);
return operations.selectOneById(entityInformation.getJavaType(), id);
}
@Override
public boolean exists(ID id) {
return template.exists(entityInformation.getJavaType(), id);
return operations.exists(entityInformation.getJavaType(), id);
}
@Override
public long count() {
return template.count(entityInformation.getTableName());
return operations.count(entityInformation.getTableName());
}
@Override
public void delete(ID id) {
template.deleteById(entityInformation.getJavaType(), id);
operations.deleteById(entityInformation.getJavaType(), id);
}
@Override
@@ -91,25 +91,25 @@ public class SimpleCassandraRepository<T, ID extends Serializable> implements Ty
@Override
public void delete(Iterable<? extends T> entities) {
template.delete(CollectionUtils.toList(entities));
operations.delete(CollectionUtils.toList(entities));
}
@Override
public void deleteAll() {
template.truncate(entityInformation.getTableName());
operations.truncate(entityInformation.getTableName());
}
@Override
public List<T> findAll() {
return template.selectAll(entityInformation.getJavaType());
return operations.selectAll(entityInformation.getJavaType());
}
@Override
public Iterable<T> findAll(Iterable<ID> ids) {
return template.selectBySimpleIds(entityInformation.getJavaType(), ids);
return operations.selectBySimpleIds(entityInformation.getJavaType(), ids);
}
protected List<T> findAll(Select query) {
return template.select(query, entityInformation.getJavaType());
return operations.select(query, entityInformation.getJavaType());
}
}

View File

@@ -0,0 +1 @@
org.springframework.data.cassandra.repository.cdi.CassandraRepositoryExtension

View File

@@ -0,0 +1,73 @@
/*
* 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.cassandra.test.integration.repository.cdi;
import java.util.HashMap;
import java.util.Set;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Service;
import org.springframework.cassandra.core.cql.CqlIdentifier;
import org.springframework.cassandra.core.keyspace.CreateKeyspaceSpecification;
import org.springframework.cassandra.test.integration.AbstractEmbeddedCassandraIntegrationTest;
import org.springframework.data.cassandra.convert.MappingCassandraConverter;
import org.springframework.data.cassandra.core.CassandraAdminTemplate;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.mapping.CassandraPersistentEntity;
import org.springframework.data.cassandra.test.integration.repository.User;
/**
* @author Mark Paluch
*/
@ApplicationScoped
class CassandraOperationsProducer {
@Produces
public CassandraOperations createCassandraOperations() throws Exception {
String keySpace = AbstractEmbeddedCassandraIntegrationTest.randomKeyspaceName();
MappingCassandraConverter cassandraConverter = new MappingCassandraConverter();
CassandraAdminTemplate cassandraTemplate = new CassandraAdminTemplate(AbstractEmbeddedCassandraIntegrationTest
.cluster().connect(), cassandraConverter);
CreateKeyspaceSpecification createKeyspaceSpecification = new CreateKeyspaceSpecification(keySpace).ifNotExists();
cassandraTemplate.execute(createKeyspaceSpecification);
cassandraTemplate.execute("USE " + keySpace);
cassandraTemplate.createTable(true, CqlIdentifier.cqlId("users"), User.class, new HashMap<String, Object>());
for (CassandraPersistentEntity<?> entity : cassandraTemplate.getConverter().getMappingContext()
.getPersistentEntities()) {
cassandraTemplate.truncate(entity.getTableName());
}
return cassandraTemplate;
}
public void close(@Disposes CassandraOperations cassandraOperations) {
cassandraOperations.getSession().close();
}
@Produces
public Set<Service> producerToSatisfyGuavaDependenciesWhenTesting() {
return Sets.newHashSet();
}
}

View File

@@ -0,0 +1,46 @@
/*
* 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.cassandra.test.integration.repository.cdi;
import javax.inject.Inject;
/**
* @author Mohsin Husen
* @author Oliver Gierke
*/
class CdiRepositoryClient {
private CdiUserRepository repository;
private SamplePersonRepository samplePersonRepository;
public CdiUserRepository getRepository() {
return repository;
}
@Inject
public void setRepository(CdiUserRepository repository) {
this.repository = repository;
}
public SamplePersonRepository getSamplePersonRepository() {
return samplePersonRepository;
}
@Inject
public void setSamplePersonRepository(SamplePersonRepository samplePersonRepository) {
this.samplePersonRepository = samplePersonRepository;
}
}

View File

@@ -0,0 +1,100 @@
/*
* 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.cassandra.test.integration.repository.cdi;
import static org.hamcrest.CoreMatchers.*;
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 org.springframework.cassandra.test.integration.AbstractEmbeddedCassandraIntegrationTest;
import org.springframework.data.cassandra.test.integration.repository.User;
/**
* @author Mohsin Husen
* @author Mark Paluch
*/
public class CdiRepositoryTests extends AbstractEmbeddedCassandraIntegrationTest {
private static CdiTestContainer cdiContainer;
private CdiUserRepository repository;
private SamplePersonRepository personRepository;
@BeforeClass
public static void init() throws Exception {
startCassandra();
cdiContainer = CdiTestContainerLoader.getCdiContainer();
cdiContainer.startApplicationScope();
cdiContainer.bootContainer();
}
@AfterClass
public static void shutdown() throws Exception {
cdiContainer.stopContexts();
cdiContainer.shutdownContainer();
}
@Before
public void setUp() {
CdiRepositoryClient client = cdiContainer.getInstance(CdiRepositoryClient.class);
repository = client.getRepository();
personRepository = client.getSamplePersonRepository();
}
@Test
public void testCdiRepository() {
assertNotNull(repository);
User bean = new User();
bean.setUsername("username");
bean.setFirstName("first");
bean.setLastName("last");
repository.save(bean);
assertTrue(repository.exists(bean.getUsername()));
User retrieved = repository.findOne(bean.getUsername());
assertNotNull(retrieved);
assertEquals(bean.getUsername(), retrieved.getUsername());
assertEquals(bean.getFirstName(), retrieved.getFirstName());
assertEquals(bean.getLastName(), retrieved.getLastName());
assertEquals(1, repository.count());
assertTrue(repository.exists(bean.getUsername()));
repository.delete(bean);
assertEquals(0, repository.count());
retrieved = repository.findOne(bean.getUsername());
assertNull(retrieved);
}
/**
* @see DATACASS-149
*/
@Test
public void returnOneFromCustomImpl() {
assertThat(personRepository.returnOne(), is(1));
}
}

View File

@@ -0,0 +1,28 @@
/*
* 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.cassandra.test.integration.repository.cdi;
import org.springframework.data.cassandra.test.integration.repository.User;
import org.springframework.data.repository.CrudRepository;
/**
* @author Mohsin Husen
* @author Oliver Gierke
*/
public interface CdiUserRepository extends CrudRepository<User, String> {
User findOne(String id);
}

View File

@@ -0,0 +1,28 @@
/*
* 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.cassandra.test.integration.repository.cdi;
import org.springframework.data.cassandra.test.integration.querymethods.declared.Person;
import org.springframework.data.repository.Repository;
/**
* @author Mark Paluch
* @see DATACASS-149
*/
public interface SamplePersonRepository extends Repository<Person, Long>, SamplePersonRepositoryCustom {
}

View File

@@ -0,0 +1,26 @@
/*
* 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.cassandra.test.integration.repository.cdi;
/**
* @see DATACASS-149
* @author Mark Paluch
*/
interface SamplePersonRepositoryCustom {
int returnOne();
}

View File

@@ -0,0 +1,29 @@
/*
* 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.cassandra.test.integration.repository.cdi;
/**
* @see DATACASS-149
* @author Mark Paluch
*/
class SamplePersonRepositoryImpl implements SamplePersonRepositoryCustom {
@Override
public int returnOne() {
return 1;
}
}

View File

@@ -5,6 +5,7 @@ Bundle-ManifestVersion: 2
Import-Package:
sun.reflect;version="0";resolution:=optional
Import-Template:
javax.enterprise.*;version="${cdi:[=.=.=,+1.0.0)}";resolution:=optional,
org.springframework.beans.*;version="[3.1.0, 4.0.0)",
org.springframework.cache.*;version="[3.1.0, 4.0.0)",
org.springframework.context.*;version="[3.1.0, 4.0.0)",