DATAGRAPH-340 - Initial draft of CDI Implementation.

Original pull request: #133.
This commit is contained in:
Nicki Watt
2013-09-09 15:11:32 +01:00
committed by Oliver Gierke
parent a30fc18ed2
commit 62498f4b4d
14 changed files with 607 additions and 1 deletions

View File

@@ -106,7 +106,30 @@
<version>${cdi}</version>
<scope>test</scope>
</dependency>
<!-- CDI -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>${cdi}</version>
<scope>provided</scope>
<optional>true</optional>
</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>2.5</version>
<scope>test</scope>
</dependency>
<!-- JSR 303 Validation -->
<dependency>
<groupId>javax.validation</groupId>

View File

@@ -0,0 +1,79 @@
/*
* 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.neo4j.repository.cdi;
import org.springframework.data.neo4j.repository.GraphRepositoryFactory;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.data.neo4j.support.mapping.Neo4jMappingContext;
import org.springframework.data.repository.cdi.CdiRepositoryBean;
import org.springframework.util.Assert;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import java.lang.annotation.Annotation;
import java.util.Set;
/**
* {@link org.springframework.data.repository.cdi.CdiRepositoryBean} to create
* Neo4j repository instances via CDI.
*
* @author Nicki Watt
*/
public class Neo4jCdiRepositoryBean<T> extends CdiRepositoryBean<T> {
private final Bean<Neo4jMappingContext> neo4jMappingContext;
private final Bean<Neo4jTemplate> template;
/**
* Creates a new {@link Neo4jCdiRepositoryBean}.
*
* @param neo4jMappingContext must not be {@literal null}.
* @param template 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}.
*/
public Neo4jCdiRepositoryBean(Bean<Neo4jMappingContext> neo4jMappingContext,
Bean<Neo4jTemplate> template,
Set<Annotation> qualifiers,
Class<T> repositoryType,
BeanManager beanManager) {
super(qualifiers, repositoryType, beanManager);
Assert.notNull(neo4jMappingContext);
Assert.notNull(template);
this.neo4jMappingContext = neo4jMappingContext;
this.template = template;
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.cdi.CdiRepositoryBean#create(javax.enterprise.context.spi.CreationalContext, java.lang.Class)
*/
@Override
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType) {
Neo4jMappingContext neo4jMapCtx = getDependencyInstance(neo4jMappingContext, Neo4jMappingContext.class);
Neo4jTemplate neo4jTemplate = getDependencyInstance(template, Neo4jTemplate.class);
GraphRepositoryFactory factory = new GraphRepositoryFactory(neo4jTemplate,neo4jMapCtx);
return factory.getRepository(repositoryType);
}
}

View File

@@ -0,0 +1,126 @@
/*
* 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.neo4j.repository.cdi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.data.neo4j.support.mapping.Neo4jMappingContext;
import org.springframework.data.repository.cdi.CdiRepositoryExtensionSupport;
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.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* CDI extension to export Neo4j repositories.
*
* @author Nicki Watt
*/
public class Neo4jCdiRepositoryExtension extends CdiRepositoryExtensionSupport {
private static final Logger LOG = LoggerFactory.getLogger(Neo4jCdiRepositoryExtension.class);
private final Map<Set<Annotation>, Bean<Neo4jMappingContext>> neo4jMappingContexts = new HashMap<Set<Annotation>, Bean<Neo4jMappingContext>>();
private final Map<Set<Annotation>, Bean<Neo4jTemplate>> neo4jTemplates = new HashMap<Set<Annotation>, Bean<Neo4jTemplate>>();
public Neo4jCdiRepositoryExtension() {
LOG.info("Activating CDI extension for Spring Data Neo4j repositories.");
}
@SuppressWarnings("unchecked")
<X> void processBean(@Observes ProcessBean<X> processBean) {
Bean<X> bean = processBean.getBean();
for (Type type : bean.getTypes()) {
if (type instanceof Class<?> && Neo4jMappingContext.class.isAssignableFrom((Class<?>) type)) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Discovered %s with qualifiers %s.", Neo4jMappingContext.class.getName(),
bean.getQualifiers()));
}
// Store the EntityManager bean using its qualifiers.
neo4jMappingContexts.put(new HashSet<Annotation>(bean.getQualifiers()), (Bean<Neo4jMappingContext>) bean);
}
if (type instanceof Class<?> && Neo4jTemplate.class.isAssignableFrom((Class<?>) type)) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Discovered %s with qualifiers %s.", Neo4jTemplate.class.getName(),
bean.getQualifiers()));
}
// Store the EntityManager bean using its qualifiers.
neo4jTemplates.put(new HashSet<Annotation>(bean.getQualifiers()), (Bean<Neo4jTemplate>) bean);
}
}
}
void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) {
for (Entry<Class<?>, Set<Annotation>> entry : getRepositoryTypes()) {
Class<?> repositoryType = entry.getKey();
Set<Annotation> qualifiers = entry.getValue();
// Create the bean representing the repository.
Bean<?> repositoryBean = createRepositoryBean(repositoryType, qualifiers, beanManager);
if (LOG.isInfoEnabled()) {
LOG.info(String.format("Registering bean for %s with qualifiers %s.", repositoryType.getName(), qualifiers));
}
// Register the bean to the container.
afterBeanDiscovery.addBean(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> Bean<T> createRepositoryBean(Class<T> repositoryType, Set<Annotation> qualifiers, BeanManager beanManager) {
// Determine the Neo4jOperations bean which matches the qualifiers of the repository.
Bean<Neo4jMappingContext> neo4jMappingContextBean = this.neo4jMappingContexts.get(qualifiers);
Bean<Neo4jTemplate> neo4jTemplateBean = this.neo4jTemplates.get(qualifiers);
if (neo4jMappingContextBean == null) {
throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.",
Neo4jMappingContext.class.getName(), qualifiers));
}
if (neo4jTemplateBean == null) {
throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.",
Neo4jTemplate.class.getName(), qualifiers));
}
// Construct and return the repository bean.
return new Neo4jCdiRepositoryBean<T>(neo4jMappingContextBean, neo4jTemplateBean, qualifiers, repositoryType, beanManager);
}
}

View File

@@ -0,0 +1,5 @@
/**
* CDI support for Neo4j specific repository implementation.
*/
package org.springframework.data.neo4j.repository.cdi;

View File

@@ -87,6 +87,12 @@ public class Neo4jTemplate implements Neo4jOperations, ApplicationContextAware {
private final Infrastructure infrastructure;
private ApplicationContext applicationContext;
// required purely for CDI purposes ???
// check if there is a better way
protected Neo4jTemplate() {
this.infrastructure = null;
}
/**
* @param graphDatabase the neo4j graph database
* @param transactionManager if passed in, will be used to create implicit transactions whenever needed

View File

@@ -0,0 +1 @@
org.springframework.data.neo4j.repository.cdi.Neo4jCdiRepositoryExtension

View File

@@ -0,0 +1,147 @@
/*
* 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.neo4j.repository.cdi;
import org.apache.webbeans.cditest.CdiTestContainer;
import org.apache.webbeans.cditest.CdiTestContainerLoader;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.neo4j.graphdb.Transaction;
import org.springframework.data.neo4j.model.Person;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* Integration tests for {@link Neo4jCdiRepositoryExtension}.
*
* @author Nicki Watt
*/
public class CdiExtensionIntegrationTests {
static CdiTestContainer container;
@BeforeClass
public static void setUp() throws Exception {
container = CdiTestContainerLoader.getCdiContainer();
container.bootContainer();
}
@AfterClass
public static void tearDown() throws Exception {
container.shutdownContainer();
}
@Test
public void testRepositoryStyle1IsCreatedCorrectly() {
Neo4jTemplate template = container.getInstance(Neo4jTemplate.class);
RepositoryClient client = container.getInstance(RepositoryClient.class);
CdiPersonRepository repository = client.getRepository();
assertThat(repository, is(notNullValue()));
Person person = null;
Person result = null;
Transaction tx = template.getGraphDatabaseService().beginTx();
try {
repository.deleteAll();
person = new Person("Simon", 28);
result = repository.save(person);
tx.success();
} catch (Exception e) {
tx.failure();
} finally {
tx.finish();
}
assertThat(result, is(notNullValue()));
Long resultId = result.getId();
Person lookedUpPerson = repository.findOne(person.getId());
assertThat(lookedUpPerson.getId(), is(resultId));
}
@Test
public void testRepositoryStyle2IsCreatedCorrectly() {
Neo4jTemplate template = container.getInstance(Neo4jTemplate.class);
RepositoryClient client = container.getInstance(RepositoryClient.class);
CdiPersonRepository2 repository = client.getRepository2();
assertThat(repository, is(notNullValue()));
Person person = null;
Person result = null;
Transaction tx = template.getGraphDatabaseService().beginTx();
try {
repository.deleteAll();
person = new Person("Simon", 28);
result = repository.save(person);
tx.success();
} catch (Exception e) {
tx.failure();
} finally {
tx.finish();
}
assertThat(result, is(notNullValue()));
Long resultId = result.getId();
Person lookedUpPerson = repository.findOne(person.getId());
assertThat(lookedUpPerson.getId(), is(resultId));
}
@Test
@Ignore // uncomment me to see issue (Note also need to uncomment
// @Inject in RepositoryClient
public void demoNonWorkingRepository() {
Neo4jTemplate template = container.getInstance(Neo4jTemplate.class);
RepositoryClient client = container.getInstance(RepositoryClient.class);
NonWorkingCdiPersonRepository repository = client.getNonWorkingRepository();
assertThat(repository, is(notNullValue()));
Person person = null;
Person result = null;
Transaction tx = template.getGraphDatabaseService().beginTx();
try {
repository.deleteAll();
person = new Person("Simon", 28);
result = repository.save(person);
tx.success();
} catch (Exception e) {
tx.failure();
} finally {
tx.finish();
}
assertThat(result, is(notNullValue()));
Long resultId = result.getId();
Person lookedUpPerson = repository.findOne(person.getId());
assertThat(lookedUpPerson.getId(), is(resultId));
}
}

View File

@@ -0,0 +1,29 @@
/*
* 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.neo4j.repository.cdi;
import org.springframework.data.neo4j.model.Person;
import org.springframework.data.repository.Repository;
public interface CdiPersonRepository extends Repository<Person, Long> {
void deleteAll();
Person save(Person person);
Person findOne(Long id);
}

View File

@@ -0,0 +1,24 @@
/*
* 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.neo4j.repository.cdi;
import org.springframework.data.neo4j.model.Person;
import org.springframework.data.repository.CrudRepository;
public interface CdiPersonRepository2 extends CrudRepository<Person, Long> {
}

View File

@@ -0,0 +1,81 @@
/*
* 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.neo4j.repository.cdi;
import org.springframework.data.neo4j.core.GraphDatabase;
import org.springframework.data.neo4j.support.DelegatingGraphDatabase;
import org.springframework.data.neo4j.support.GraphDatabaseFactory;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.data.neo4j.support.mapping.Neo4jMappingContext;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
/**
* Simple component exposing {@link Neo4jTemplate} and {@link Neo4jMappingContext}
* instances as CDI bean.
*
* @author Nicki Watt
*/
class Neo4jCDIProducer {
@Produces
@ApplicationScoped
public Neo4jTemplate createNeo4jTemplate() {
return new Neo4jTemplate(createGraphDatabase());
}
//@Produces
//@ApplicationScoped
private GraphDatabase createGraphDatabase() {
GraphDatabaseFactory factory = new GraphDatabaseFactory();
GraphDatabase graphDatabase = null;
try {
factory.setStoreLocation("target/cdi-test-db");
graphDatabase = factory.getObject();
registerShutdownHook(graphDatabase);
} catch (Exception e) {
throw new IllegalStateException("Unable to start up factory");
}
return graphDatabase;
}
private static void registerShutdownHook( final GraphDatabase graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook( new Thread()
{
@Override
public void run()
{
((DelegatingGraphDatabase)graphDb).getGraphDatabaseService().shutdown();
}
} );
}
@Produces
@ApplicationScoped
public Neo4jMappingContext createNeo4jMappingContext() {
return new Neo4jMappingContext();
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.neo4j.repository.cdi;
import org.springframework.data.neo4j.model.Person;
import org.springframework.data.neo4j.repository.CRUDRepository;
public interface NonWorkingCdiPersonRepository extends CRUDRepository<Person> {
}

View File

@@ -0,0 +1,53 @@
/*
* 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.neo4j.repository.cdi;
import javax.inject.Inject;
/**
* @author Nicki Watt
*/
class RepositoryClient {
@Inject
CdiPersonRepository repository;
@Inject
CdiPersonRepository2 repository2;
// @Inject
//- Uncomment me, but I have problems
// (javassist.bytecode.DuplicateMemberException: duplicate method)
NonWorkingCdiPersonRepository nonWorkingCdiPersonRepository;
/**
* @return the repository
*/
public CdiPersonRepository getRepository() {
return repository;
}
/**
* @return the repository
*/
public CdiPersonRepository2 getRepository2() {
return repository2;
}
public NonWorkingCdiPersonRepository getNonWorkingRepository() {
return nonWorkingCdiPersonRepository;
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

View File

@@ -33,6 +33,7 @@ Import-Template:
javax.persistence.*;version="[1.0.0, 3.0.0)";resolution:=optional,
javax.persistence.spi.*;version="[1.0.0, 3.0.0)";resolution:=optional,
javax.transaction.*;version="[1.0.1, 2.0.0)";resolution:=optional,
javax.enterprise.*;version="${cdi:[=.=.=,+1.0.0)}";resolution:=optional,
com.mysema.query.annotations.*;version="0";resolution:=optional,
com.mysema.query.apt.*;version="0";resolution:=optional,
com.mysema.query.types.*;version="0";resolution:=optional,