diff --git a/pom.xml b/pom.xml index 46d2a11a9..74a7c771f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,214 +1,215 @@ - + - 4.0.0 + 4.0.0 - org.springframework.data - spring-data-neo4j-parent - 4.2.14.BUILD-SNAPSHOT - pom + org.springframework.data + spring-data-neo4j-parent + 4.2.14.BUILD-SNAPSHOT + pom - Spring Data Neo4j - Neo4j support for Spring Data - http://projects.spring.io/spring-data-neo4j + Spring Data Neo4j + Neo4j support for Spring Data + http://projects.spring.io/spring-data-neo4j - - org.springframework.data.build - spring-data-parent - 1.9.14.BUILD-SNAPSHOT - + + org.springframework.data.build + spring-data-parent + 1.9.14.BUILD-SNAPSHOT + - - spring-data-neo4j - spring-data-neo4j-distribution - + + spring-data-neo4j + spring-data-neo4j-distribution + - - multi - spring-data-neo4j - 1.13.14.BUILD-SNAPSHOT - 1.8 - + + multi + spring-data-neo4j + 1.13.14.BUILD-SNAPSHOT + 1.8 + - - - vbickers - Vince Bickers - vince at graphaware.com - GraphAware - http://www.graphaware.com - - Developer - - GMT - - - atg - Adam George - adam at graphaware.com - GraphAware - http://www.graphaware.com - - Developer - - GMT - - - bachmanm - Michal Bachman - michal at graphaware.com - GraphAware - http://www.graphaware.com - - Developer - - GMT - - - lmisquitta - Luanne Misquitta - luanne at graphaware.com - GraphAware - http://www.graphaware.com - - Developer - - +5:30 - - - mangrish - Mark Angrish - mark at graphaware.com - GraphAware - http://www.graphaware.com - - Developer - - +11 - - - jasperblues - Jasper Blues - jasper at graphaware.com - GraphAware - http://www.graphaware.com - - Developer - - +8 - - - mhunger - Michael Hunger - michael.hunger at neotechnology.com - Neo Technology - http://www.neotechnology.com - - Project Lead - - +1 - - - ogierke - Oliver Gierke - ogierke at gopivotal.com - Pivotal - http://www.spring.io - - Developer - - +1 - - - trisberg - Thomas Risberg - trisberg at gopivotal.com - Pivotal - http://www.spring.io - - Developer - - -5 - - - mpollack - Mark Pollack - mpollack at gopivotal.com - Pivotal - http://www.spring.io - - Developer - - -5 - - + + + vbickers + Vince Bickers + vince at graphaware.com + GraphAware + http://www.graphaware.com + + Developer + + GMT + + + atg + Adam George + adam at graphaware.com + GraphAware + http://www.graphaware.com + + Developer + + GMT + + + bachmanm + Michal Bachman + michal at graphaware.com + GraphAware + http://www.graphaware.com + + Developer + + GMT + + + lmisquitta + Luanne Misquitta + luanne at graphaware.com + GraphAware + http://www.graphaware.com + + Developer + + +5:30 + + + mangrish + Mark Angrish + mark at graphaware.com + GraphAware + http://www.graphaware.com + + Developer + + +11 + + + jasperblues + Jasper Blues + jasper at graphaware.com + GraphAware + http://www.graphaware.com + + Developer + + +8 + + + mhunger + Michael Hunger + michael.hunger at neotechnology.com + Neo Technology + http://www.neotechnology.com + + Project Lead + + +1 + + + ogierke + Oliver Gierke + ogierke at gopivotal.com + Pivotal + http://www.spring.io + + Developer + + +1 + + + trisberg + Thomas Risberg + trisberg at gopivotal.com + Pivotal + http://www.spring.io + + Developer + + -5 + + + mpollack + Mark Pollack + mpollack at gopivotal.com + Pivotal + http://www.spring.io + + Developer + + -5 + + - + - + - - org.hibernate - hibernate-validator - 5.1.2.Final - test - + + org.hibernate + hibernate-validator + 5.1.2.Final + test + - - org.glassfish - javax.el - 3.0.0 - test - + + org.glassfish + javax.el + 3.0.0 + test + - + - + - - - release - - - - org.jfrog.buildinfo - artifactory-maven-plugin - false - - - - - + + + release + + + + org.jfrog.buildinfo + artifactory-maven-plugin + false + + + + + - - - neo4j - http://m2.neo4j.org/content/repositories/releases - - true - always - - - - neo4j-snapshots - http://m2.neo4j.org/content/repositories/snapshots - - true - always - - - - spring-libs-snapshot - https://repo.spring.io/libs-snapshot - - + + + neo4j + http://m2.neo4j.org/content/repositories/releases + + true + always + + + + neo4j-snapshots + http://m2.neo4j.org/content/repositories/snapshots + + true + always + + + + spring-libs-snapshot + https://repo.spring.io/libs-snapshot + + - - - spring-plugins-release - https://repo.spring.io/plugins-release - - + + + spring-plugins-release + https://repo.spring.io/plugins-release + + diff --git a/spring-data-neo4j/pom.xml b/spring-data-neo4j/pom.xml index 9c611b251..7a46d4273 100644 --- a/spring-data-neo4j/pom.xml +++ b/spring-data-neo4j/pom.xml @@ -12,188 +12,189 @@ ~ --> - + - 4.0.0 + 4.0.0 - spring-data-neo4j + spring-data-neo4j - Spring Data Neo4J - Core - Neo4J support for Spring Data + Spring Data Neo4J - Core + Neo4J support for Spring Data - - org.springframework.data - spring-data-neo4j-parent - 4.2.14.BUILD-SNAPSHOT - ../pom.xml - + + org.springframework.data + spring-data-neo4j-parent + 4.2.14.BUILD-SNAPSHOT + ../pom.xml + - - 2.1.6 - ogm-http.properties - ${basedir}/.. - + + 2.1.6 + ogm-http.properties + ${basedir}/.. + - + - - - org.springframework - spring-tx - - - org.springframework - spring-context - - - org.springframework - spring-beans - - - org.springframework - spring-core - - - commons-logging - commons-logging - - - - - org.slf4j - jcl-over-slf4j - ${slf4j} - compile - - - org.springframework - spring-web - compile - true - + + + org.springframework + spring-tx + + + org.springframework + spring-context + + + org.springframework + spring-beans + + + org.springframework + spring-core + + + commons-logging + commons-logging + + + + + org.slf4j + jcl-over-slf4j + ${slf4j} + compile + + + org.springframework + spring-web + compile + true + - - - ${project.groupId} - spring-data-commons - ${springdata.commons} - + + + ${project.groupId} + spring-data-commons + ${springdata.commons} + - - - javax.enterprise - cdi-api - ${cdi} - provided - true - + + + javax.enterprise + cdi-api + ${cdi} + provided + true + - - javax.el - el-api - ${cdi} - test - + + javax.el + el-api + ${cdi} + test + - - org.glassfish - javax.el - test - + + org.glassfish + javax.el + test + - - org.apache.openwebbeans.test - cditest-owb - ${webbeans} - test - + + org.apache.openwebbeans.test + cditest-owb + ${webbeans} + test + - - javax.servlet - javax.servlet-api - 3.1.0 - compile - true - + + javax.servlet + javax.servlet-api + 3.1.0 + compile + true + - - - javax.validation - validation-api - ${validation} - true - + + + javax.validation + validation-api + ${validation} + true + - - org.hibernate - hibernate-validator + + org.hibernate + hibernate-validator 4.2.0.Final - test - + test + - - - org.neo4j - neo4j-ogm-core - ${neo4j.ogm.version} - + + + org.neo4j + neo4j-ogm-core + ${neo4j.ogm.version} + - - org.neo4j - neo4j-ogm-http-driver - ${neo4j.ogm.version} - + + org.neo4j + neo4j-ogm-http-driver + ${neo4j.ogm.version} + - - org.neo4j - neo4j-ogm-test - ${neo4j.ogm.version} - test - - - org.neo4j - neo4j-security-enterprise - - - + + org.neo4j + neo4j-ogm-test + ${neo4j.ogm.version} + test + + + org.neo4j + neo4j-security-enterprise + + + - - org.springframework - spring-webmvc - test - + + org.springframework + spring-webmvc + test + - + - - + + - - org.apache.maven.plugins - maven-surefire-plugin - + + org.apache.maven.plugins + maven-surefire-plugin + - - org.apache.maven.plugins - maven-failsafe-plugin - 2.19.1 - - - integration-test - - integration-test - verify - - - once - - ${ogm.properties} - - - - - - - + + org.apache.maven.plugins + maven-failsafe-plugin + 2.19.1 + + + integration-test + + integration-test + verify + + + once + + ${ogm.properties} + + + + + + + diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/Depth.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/Depth.java index d1a24598a..2c8cb1716 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/Depth.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/Depth.java @@ -23,10 +23,11 @@ import org.springframework.data.annotation.QueryAnnotation; /** * Specifies the depth of the query. Used with derived finders. + * * @author Luanne Misquitta */ @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.PARAMETER, ElementType.METHOD}) +@Target({ ElementType.PARAMETER, ElementType.METHOD }) @QueryAnnotation @Documented public @interface Depth { diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/Query.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/Query.java index cdfcd8b38..dc928bd03 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/Query.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/Query.java @@ -13,9 +13,13 @@ package org.springframework.data.neo4j.annotation; -import org.springframework.data.annotation.QueryAnnotation; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; -import java.lang.annotation.*; +import org.springframework.data.annotation.QueryAnnotation; /** * Annotation to declare finder queries directly on repository methods. @@ -29,16 +33,16 @@ import java.lang.annotation.*; @Documented public @interface Query { - static final String CLASS = "org.springframework.data.neo4j.annotation.Query"; - static final String VALUE = "value"; + static final String CLASS = "org.springframework.data.neo4j.annotation.Query"; + static final String VALUE = "value"; - /** - * Defines the Cypher query to be executed when the annotated method is called. - */ - String value() default ""; + /** + * Defines the Cypher query to be executed when the annotated method is called. + */ + String value() default ""; - /** - * @return simpler count-query to be executed for @{see Pageable}-support - */ - String countQuery() default ""; + /** + * @return simpler count-query to be executed for @{see Pageable}-support + */ + String countQuery() default ""; } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/QueryResult.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/QueryResult.java index 6ceaef64e..5bd09f427 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/QueryResult.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/QueryResult.java @@ -13,7 +13,11 @@ package org.springframework.data.neo4j.annotation; -import java.lang.annotation.*; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; /** * Annotation to be applied to interfaces and classes onto which arbitrary Cypher query results are to be mapped. @@ -25,6 +29,6 @@ import java.lang.annotation.*; @Documented public @interface QueryResult { - // no annotation properties needed + // no annotation properties needed } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/conversion/MetaDataDrivenConversionService.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/conversion/MetaDataDrivenConversionService.java index 0bbdd7cec..08ae5abde 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/conversion/MetaDataDrivenConversionService.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/conversion/MetaDataDrivenConversionService.java @@ -13,6 +13,8 @@ package org.springframework.data.neo4j.conversion; +import java.lang.reflect.ParameterizedType; + import org.neo4j.ogm.MetaData; import org.neo4j.ogm.metadata.ClassInfo; import org.neo4j.ogm.metadata.FieldInfo; @@ -22,14 +24,12 @@ import org.neo4j.ogm.typeconversion.ConversionCallback; import org.neo4j.ogm.typeconversion.ProxyAttributeConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.core.convert.support.GenericConversionService; import org.springframework.core.convert.converter.Converter; - -import java.lang.reflect.ParameterizedType; +import org.springframework.core.convert.support.GenericConversionService; /** - * Specialisation of {@link GenericConversionService} that creates Spring-compatible converters from those known by the mapping - * {@link MetaData}, allowing the OGM type converters to be reused throughout a Spring application. + * Specialisation of {@link GenericConversionService} that creates Spring-compatible converters from those known by the + * mapping {@link MetaData}, allowing the OGM type converters to be reused throughout a Spring application. * * @author Adam George * @author Luanne Misquitta @@ -37,86 +37,83 @@ import java.lang.reflect.ParameterizedType; */ public class MetaDataDrivenConversionService extends GenericConversionService implements ConversionCallback { - private static final Logger logger = LoggerFactory.getLogger(MetaDataDrivenConversionService.class); + private static final Logger logger = LoggerFactory.getLogger(MetaDataDrivenConversionService.class); - /** - * Constructs a new {@link MetaDataDrivenConversionService} based on the given {@link MetaData}. - * - * @param metaData The OGM {@link MetaData} from which to elicit type converters configured in the underlying object-graph - * mapping layer - */ - public MetaDataDrivenConversionService(MetaData metaData) { - metaData.registerConversionCallback(this); + /** + * Constructs a new {@link MetaDataDrivenConversionService} based on the given {@link MetaData}. + * + * @param metaData The OGM {@link MetaData} from which to elicit type converters configured in the underlying + * object-graph mapping layer + */ + public MetaDataDrivenConversionService(MetaData metaData) { + metaData.registerConversionCallback(this); - for (ClassInfo classInfo : metaData.persistentEntities()) { - for (FieldInfo fieldInfo : classInfo.propertyFields()) { - if (fieldInfo.hasPropertyConverter()) { - addWrappedConverter(fieldInfo.getPropertyConverter()); - } - } - // TODO: do we need to check the setters too or are programmers obliged to annotate both? - for (MethodInfo methodInfo : classInfo.propertyGetters()) { - if (methodInfo.hasPropertyConverter()) { - addWrappedConverter(methodInfo.getPropertyConverter()); - } - } - } - } + for (ClassInfo classInfo : metaData.persistentEntities()) { + for (FieldInfo fieldInfo : classInfo.propertyFields()) { + if (fieldInfo.hasPropertyConverter()) { + addWrappedConverter(fieldInfo.getPropertyConverter()); + } + } + // TODO: do we need to check the setters too or are programmers obliged to annotate both? + for (MethodInfo methodInfo : classInfo.propertyGetters()) { + if (methodInfo.hasPropertyConverter()) { + addWrappedConverter(methodInfo.getPropertyConverter()); + } + } + } + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - private void addWrappedConverter(final AttributeConverter attributeConverter) { - if (attributeConverter instanceof ProxyAttributeConverter) { - return; - } + @SuppressWarnings({ "unchecked", "rawtypes" }) + private void addWrappedConverter(final AttributeConverter attributeConverter) { + if (attributeConverter instanceof ProxyAttributeConverter) { + return; + } - Converter toGraphConverter = new Converter() { - @Override - public Object convert(Object source) { - return attributeConverter.toGraphProperty(source); - } - }; - Converter toEntityConverter = new Converter() { - @Override - public Object convert(Object source) { - return attributeConverter.toEntityAttribute(source); - } - }; + Converter toGraphConverter = new Converter() { + @Override + public Object convert(Object source) { + return attributeConverter.toGraphProperty(source); + } + }; + Converter toEntityConverter = new Converter() { + @Override + public Object convert(Object source) { + return attributeConverter.toEntityAttribute(source); + } + }; + ParameterizedType pt = (ParameterizedType) attributeConverter.getClass().getGenericInterfaces()[0]; + Class sourceType, targetType; + if (pt.getActualTypeArguments()[0] instanceof Class) { + sourceType = (Class) pt.getActualTypeArguments()[0]; + } else { // the argument may be a Collection for example + sourceType = (Class) ((ParameterizedType) pt.getActualTypeArguments()[0]).getActualTypeArguments()[0]; + } - ParameterizedType pt = (ParameterizedType) attributeConverter.getClass().getGenericInterfaces()[0]; - Class sourceType, targetType; - if (pt.getActualTypeArguments()[0] instanceof Class) { - sourceType = (Class) pt.getActualTypeArguments()[0]; - } - else { //the argument may be a Collection for example - sourceType = (Class)((ParameterizedType) pt.getActualTypeArguments()[0]).getActualTypeArguments()[0]; - } + if (pt.getActualTypeArguments()[1] instanceof Class) { + targetType = (Class) pt.getActualTypeArguments()[1]; + } else { + targetType = (Class) ((ParameterizedType) pt.getActualTypeArguments()[1]).getActualTypeArguments()[1]; - if (pt.getActualTypeArguments()[1] instanceof Class) { - targetType = (Class) pt.getActualTypeArguments()[1]; - } - else { - targetType = (Class)((ParameterizedType) pt.getActualTypeArguments()[1]).getActualTypeArguments()[1]; + } - } + if (canConvert(sourceType, targetType) && canConvert(targetType, sourceType)) { + logger.info("Not adding Spring-compatible converter for " + attributeConverter.getClass() + + " because one that does the same job has already been registered with the ConversionService."); + } else { + // It could be argued that this is wrong as it potentially overrides a registered converted that doesn't handle + // both directions, but I've decided that it's better to ensure the same converter is used for load and save. + addConverter(sourceType, targetType, toGraphConverter); + addConverter(targetType, sourceType, toEntityConverter); + } + } - if (canConvert(sourceType, targetType) && canConvert(targetType, sourceType)) { - logger.info("Not adding Spring-compatible converter for " + attributeConverter.getClass() - + " because one that does the same job has already been registered with the ConversionService."); - } else { - // It could be argued that this is wrong as it potentially overrides a registered converted that doesn't handle - // both directions, but I've decided that it's better to ensure the same converter is used for load and save. - addConverter(sourceType, targetType, toGraphConverter); - addConverter(targetType, sourceType, toEntityConverter); - } - } - - @Override - public T convert(Class targetType, Object value) { - if (value == null) { - return null; - } - return convert(value, targetType); - } + @Override + public T convert(Class targetType, Object value) { + if (value == null) { + return null; + } + return convert(value, targetType); + } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/conversion/PointConverter.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/conversion/PointConverter.java index f434e5236..e2be97b50 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/conversion/PointConverter.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/conversion/PointConverter.java @@ -11,15 +11,14 @@ * */ - package org.springframework.data.neo4j.conversion; -import org.neo4j.ogm.typeconversion.CompositeAttributeConverter; -import org.springframework.data.geo.Point; - import java.util.HashMap; import java.util.Map; +import org.neo4j.ogm.typeconversion.CompositeAttributeConverter; +import org.springframework.data.geo.Point; + /** * Converts latitude and longitude properties on a node entity to an instance of Point and vice-versa. * @@ -28,24 +27,24 @@ import java.util.Map; */ public class PointConverter implements CompositeAttributeConverter { - @Override - public Map toGraphProperties(Point point) { - Map properties = new HashMap<>(); - if (point != null) { - properties.put("latitude", point.getX()); - properties.put("longitude", point.getY()); - } - return properties; - } + @Override + public Map toGraphProperties(Point point) { + Map properties = new HashMap<>(); + if (point != null) { + properties.put("latitude", point.getX()); + properties.put("longitude", point.getY()); + } + return properties; + } - @Override - public Point toEntityAttribute(Map map) { - Double latitude = (Double) map.get("latitude"); - Double longitude = (Double) map.get("longitude"); - if (latitude != null && longitude != null) { - return new Point(latitude, longitude); - } - return null; - } + @Override + public Point toEntityAttribute(Map map) { + Double latitude = (Double) map.get("latitude"); + Double longitude = (Double) map.get("longitude"); + if (latitude != null && longitude != null) { + return new Point(latitude, longitude); + } + return null; + } -} \ No newline at end of file +} diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/exception/Neo4jErrorStatusCodes.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/exception/Neo4jErrorStatusCodes.java index f58de89d8..92f7021ea 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/exception/Neo4jErrorStatusCodes.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/exception/Neo4jErrorStatusCodes.java @@ -60,14 +60,18 @@ public class Neo4jErrorStatusCodes { errors.put("Neo.ClientError.Statement.SemanticError", NonTransientDataAccessException.class); errors.put("Neo.ClientError.Statement.SyntaxError", InvalidDataAccessResourceUsageException.class); errors.put("Neo.ClientError.Statement.TypeError", InvalidDataAccessResourceUsageException.class); - errors.put("Neo.ClientError.Transaction.ForbiddenDueToTransactionType", InvalidDataAccessResourceUsageException.class); - errors.put("Neo.ClientError.Transaction.TransactionAccessedConcurrently", InvalidDataAccessResourceUsageException.class); - errors.put("Neo.ClientError.Transaction.TransactionEventHandlerFailed", InvalidDataAccessResourceUsageException.class); + errors.put("Neo.ClientError.Transaction.ForbiddenDueToTransactionType", + InvalidDataAccessResourceUsageException.class); + errors.put("Neo.ClientError.Transaction.TransactionAccessedConcurrently", + InvalidDataAccessResourceUsageException.class); + errors.put("Neo.ClientError.Transaction.TransactionEventHandlerFailed", + InvalidDataAccessResourceUsageException.class); errors.put("Neo.ClientError.Transaction.TransactionHookFailed", InvalidDataAccessResourceUsageException.class); errors.put("Neo.ClientError.Transaction.TransactionMarkedAsFailed", ConcurrencyFailureException.class); errors.put("Neo.ClientError.Transaction.TransactionNotFound", InvalidDataAccessResourceUsageException.class); errors.put("Neo.ClientError.Transaction.TransactionTerminated", InvalidDataAccessResourceUsageException.class); - errors.put("Neo.ClientError.Transaction.TransactionValidationFailed", InvalidDataAccessResourceUsageException.class); + errors.put("Neo.ClientError.Transaction.TransactionValidationFailed", + InvalidDataAccessResourceUsageException.class); errors.put("Neo.DatabaseError.General.IndexCorruptionDetected", DataAccessResourceFailureException.class); errors.put("Neo.DatabaseError.General.SchemaCorruptionDetected", DataAccessResourceFailureException.class); errors.put("Neo.DatabaseError.General.UnknownError", UncategorizedDataAccessException.class); diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jMappingContext.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jMappingContext.java index 25cd414d1..1a766552e 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jMappingContext.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jMappingContext.java @@ -12,8 +12,13 @@ */ package org.springframework.data.neo4j.mapping; -import org.neo4j.ogm.annotation.typeconversion.Convert; +import static java.util.Collections.*; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Field; + import org.neo4j.ogm.MetaData; +import org.neo4j.ogm.annotation.typeconversion.Convert; import org.neo4j.ogm.classloader.MetaDataClassLoader; import org.neo4j.ogm.metadata.ClassInfo; import org.neo4j.ogm.metadata.FieldInfo; @@ -23,17 +28,10 @@ import org.springframework.data.mapping.context.AbstractMappingContext; import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.util.TypeInformation; -import java.beans.PropertyDescriptor; -import java.lang.reflect.Field; - -import static java.util.Collections.singleton; - /** - * This class implements Spring Data's MappingContext interface, scavenging the required data from the OGM's metadata in order - * to for SDN to play nicely with Spring Data REST. - * - * The main thing to note is that this class is effectively a container shim for {@code ClassInfo} objects. We don't reload all - * the mapping information again. + * This class implements Spring Data's MappingContext interface, scavenging the required data from the OGM's metadata in + * order to for SDN to play nicely with Spring Data REST. The main thing to note is that this class is effectively a + * container shim for {@code ClassInfo} objects. We don't reload all the mapping information again. * * @author Vince Bickers * @author Adam George @@ -41,88 +39,90 @@ import static java.util.Collections.singleton; */ public class Neo4jMappingContext extends AbstractMappingContext, Neo4jPersistentProperty> { - private static final Logger logger = LoggerFactory.getLogger(Neo4jMappingContext.class); + private static final Logger logger = LoggerFactory.getLogger(Neo4jMappingContext.class); - private final MetaData metaData; + private final MetaData metaData; - /** - * Constructs a new {@link Neo4jMappingContext} based on the persistent entities in the given {@link MetaData}. - * - * @param metaData The OGM {@link MetaData} from which to extract the persistent entities - */ - public Neo4jMappingContext(MetaData metaData) { - this.metaData = metaData; + /** + * Constructs a new {@link Neo4jMappingContext} based on the persistent entities in the given {@link MetaData}. + * + * @param metaData The OGM {@link MetaData} from which to extract the persistent entities + */ + public Neo4jMappingContext(MetaData metaData) { + this.metaData = metaData; - for (ClassInfo classInfo : metaData.persistentEntities()) { - try { - addPersistentEntity( MetaDataClassLoader.loadClass( classInfo.name() )); - } catch (ClassNotFoundException e) { - logger.error("Failed to load class: " + classInfo.name() + " named in ClassInfo due to exception", e); - } - } + for (ClassInfo classInfo : metaData.persistentEntities()) { + try { + addPersistentEntity(MetaDataClassLoader.loadClass(classInfo.name())); + } catch (ClassNotFoundException e) { + logger.error("Failed to load class: " + classInfo.name() + " named in ClassInfo due to exception", e); + } + } - logger.info("Neo4jMappingContext initialisation completed"); - } + logger.info("Neo4jMappingContext initialisation completed"); + } - @Override - protected Neo4jPersistentEntity createPersistentEntity(TypeInformation typeInformation) { - logger.debug("Creating Neo4jPersistentEntity from type information: {}", typeInformation); - return new Neo4jPersistentEntity<>(typeInformation); - } + @Override + protected Neo4jPersistentEntity createPersistentEntity(TypeInformation typeInformation) { + logger.debug("Creating Neo4jPersistentEntity from type information: {}", typeInformation); + return new Neo4jPersistentEntity<>(typeInformation); + } - @Override - protected Neo4jPersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor, Neo4jPersistentEntity owner, - SimpleTypeHolder simpleTypeHolder) { + @Override + protected Neo4jPersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor, + Neo4jPersistentEntity owner, SimpleTypeHolder simpleTypeHolder) { - ClassInfo owningClassInfo = this.metaData.classInfo(owner.getType().getName()); + ClassInfo owningClassInfo = this.metaData.classInfo(owner.getType().getName()); - Field propertyField = field; - if (propertyField == null && owningClassInfo != null && descriptor != null) { - FieldInfo fieldInfo = owningClassInfo.propertyFieldByName(descriptor.getName()); - if (fieldInfo == null) { - fieldInfo = owningClassInfo.relationshipFieldByName(descriptor.getName()); - } - if (fieldInfo != null) { - propertyField = owningClassInfo.getField(fieldInfo); - } else { - // there is no field, probably because descriptor gave us a field name derived from a getter - logger.debug("Couldn't resolve a concrete field corresponding to property {} on {} ", - descriptor.getName(), owningClassInfo.name()); - } - } + Field propertyField = field; + if (propertyField == null && owningClassInfo != null && descriptor != null) { + FieldInfo fieldInfo = owningClassInfo.propertyFieldByName(descriptor.getName()); + if (fieldInfo == null) { + fieldInfo = owningClassInfo.relationshipFieldByName(descriptor.getName()); + } + if (fieldInfo != null) { + propertyField = owningClassInfo.getField(fieldInfo); + } else { + // there is no field, probably because descriptor gave us a field name derived from a getter + logger.debug("Couldn't resolve a concrete field corresponding to property {} on {} ", descriptor.getName(), + owningClassInfo.name()); + } + } - return new Neo4jPersistentProperty(owningClassInfo, propertyField, descriptor, owner, - updateSimpleTypeHolder(simpleTypeHolder, propertyField)); - } + return new Neo4jPersistentProperty(owningClassInfo, propertyField, descriptor, owner, + updateSimpleTypeHolder(simpleTypeHolder, propertyField)); + } - private SimpleTypeHolder updateSimpleTypeHolder(SimpleTypeHolder currentSimpleTypeHolder, Field field) { - if (field == null) { - return currentSimpleTypeHolder; - } + private SimpleTypeHolder updateSimpleTypeHolder(SimpleTypeHolder currentSimpleTypeHolder, Field field) { + if (field == null) { + return currentSimpleTypeHolder; + } - final Class fieldType = field.getType().isArray() ? field.getType().getComponentType() : field.getType(); + final Class fieldType = field.getType().isArray() ? field.getType().getComponentType() : field.getType(); - if (shouldUpdateSimpleTypes(currentSimpleTypeHolder, field, fieldType)) { - SimpleTypeHolder updatedSimpleTypeHolder = new SimpleTypeHolder(singleton(fieldType), currentSimpleTypeHolder); - setSimpleTypeHolder(updatedSimpleTypeHolder); - return updatedSimpleTypeHolder; - } - return currentSimpleTypeHolder; - } + if (shouldUpdateSimpleTypes(currentSimpleTypeHolder, field, fieldType)) { + SimpleTypeHolder updatedSimpleTypeHolder = new SimpleTypeHolder(singleton(fieldType), currentSimpleTypeHolder); + setSimpleTypeHolder(updatedSimpleTypeHolder); + return updatedSimpleTypeHolder; + } + return currentSimpleTypeHolder; + } - private boolean shouldUpdateSimpleTypes(SimpleTypeHolder currentSimpleTypeHolder, Field field, Class rawFieldType) { - if (field.isAnnotationPresent(Convert.class)) { - return true; - } + private boolean shouldUpdateSimpleTypes(SimpleTypeHolder currentSimpleTypeHolder, Field field, + Class rawFieldType) { + if (field.isAnnotationPresent(Convert.class)) { + return true; + } - if (currentSimpleTypeHolder.isSimpleType(rawFieldType) || rawFieldType.isInterface()) { - return false; - } - if (this.metaData.classInfo(rawFieldType.getName()) == null) { - logger.info("No class information found in OGM meta-data for {} so treating as simple type for SD Commons", rawFieldType); - return true; - } - return false; - } + if (currentSimpleTypeHolder.isSimpleType(rawFieldType) || rawFieldType.isInterface()) { + return false; + } + if (this.metaData.classInfo(rawFieldType.getName()) == null) { + logger.info("No class information found in OGM meta-data for {} so treating as simple type for SD Commons", + rawFieldType); + return true; + } + return false; + } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jPersistentEntity.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jPersistentEntity.java index 617eb6126..ff0d63971 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jPersistentEntity.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jPersistentEntity.java @@ -19,22 +19,20 @@ import org.springframework.data.mapping.model.BasicPersistentEntity; import org.springframework.data.util.TypeInformation; /** - * This class implements Spring Data's PersistentEntity interface, scavenging the required data from the OGM's mapping classes - * in order to for SDN to play nicely with Spring Data REST. - * - * The main thing to note is that this class is effectively a shim for ClassInfo. We don't reload all the mapping information - * again. + * This class implements Spring Data's PersistentEntity interface, scavenging the required data from the OGM's mapping + * classes in order to for SDN to play nicely with Spring Data REST. The main thing to note is that this class is + * effectively a shim for ClassInfo. We don't reload all the mapping information again. *

* These attributes do not appear to be used/needed for SDN 4 to inter-operate correctly with SD-REST: *

*
    - *
  • typeAlias
  • - *
  • typeInformation
  • - *
  • preferredConstructor (we always use the default constructor)
  • - *
  • versionProperty
  • + *
  • typeAlias
  • + *
  • typeInformation
  • + *
  • preferredConstructor (we always use the default constructor)
  • + *
  • versionProperty
  • *
- * Consequently their associated getter methods always return default values of null or [true|false] However, because these - * method calls are not expected, we also log a warning message if they get invoked + * Consequently their associated getter methods always return default values of null or [true|false] However, because + * these method calls are not expected, we also log a warning message if they get invoked * * @author Vince Bickers * @author Adam George @@ -42,33 +40,33 @@ import org.springframework.data.util.TypeInformation; */ public class Neo4jPersistentEntity extends BasicPersistentEntity { - private static final Logger logger = LoggerFactory.getLogger(Neo4jPersistentEntity.class); + private static final Logger logger = LoggerFactory.getLogger(Neo4jPersistentEntity.class); - /** - * Constructs a new {@link Neo4jPersistentEntity} based on the given type information. - * - * @param information The {@link TypeInformation} upon which to base this persistent entity. - */ - public Neo4jPersistentEntity(TypeInformation information) { - super(information); - } + /** + * Constructs a new {@link Neo4jPersistentEntity} based on the given type information. + * + * @param information The {@link TypeInformation} upon which to base this persistent entity. + */ + public Neo4jPersistentEntity(TypeInformation information) { + super(information); + } - @Override - public boolean hasVersionProperty() { - logger.debug("[entity].hasVersionProperty() returns false"); // by design - return false; - } + @Override + public boolean hasVersionProperty() { + logger.debug("[entity].hasVersionProperty() returns false"); // by design + return false; + } - @Override - public Neo4jPersistentProperty getVersionProperty() { - logger.debug("[entity].getVersionProperty() returns null"); // by design - return null; - } + @Override + public Neo4jPersistentProperty getVersionProperty() { + logger.debug("[entity].getVersionProperty() returns null"); // by design + return null; + } - @Override - public boolean isVersionProperty(PersistentProperty property) { - logger.debug("[entity].isIdProperty({}) returns false", property); // again, by design - return false; - } + @Override + public boolean isVersionProperty(PersistentProperty property) { + logger.debug("[entity].isIdProperty({}) returns false", property); // again, by design + return false; + } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jPersistentProperty.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jPersistentProperty.java index 4df857a35..6ad966c8b 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jPersistentProperty.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/mapping/Neo4jPersistentProperty.java @@ -29,11 +29,10 @@ import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.neo4j.annotation.QueryResult; /** - * This class implements Spring Data's PersistentProperty interface, scavenging the required data from the - * OGM's mapping classes in order to for SDN to play nicely with Spring Data REST. - * The main thing to note is that this class is effectively a shim for FieldInfo. We don't reload - * all the mapping information again. - * We do not yet support getter/setter access to entity properties. + * This class implements Spring Data's PersistentProperty interface, scavenging the required data from the OGM's mapping + * classes in order to for SDN to play nicely with Spring Data REST. The main thing to note is that this class is + * effectively a shim for FieldInfo. We don't reload all the mapping information again. We do not yet support + * getter/setter access to entity properties. *

* These attributes do not appear to be used/needed for SDN 4 to inter-operate correctly with SD-REST: *

@@ -44,8 +43,8 @@ import org.springframework.data.neo4j.annotation.QueryResult; *
  • isTransient (we never supply transient classes to the Spring mapping context)
  • *
  • isWritable (we don't currently support read-only fields)
  • * - * Consequently their associated getter methods always return default values of null or [true|false] - * However, because these method calls are not expected, we also log a warning message if they get invoked + * Consequently their associated getter methods always return default values of null or [true|false] However, because + * these method calls are not expected, we also log a warning message if they get invoked * * @author Vince Bickers * @author Adam George @@ -66,17 +65,22 @@ public class Neo4jPersistentProperty extends AnnotationBasedPersistentProperty owner, SimpleTypeHolder simpleTypeHolder) { + PersistentEntity owner, SimpleTypeHolder simpleTypeHolder) { super(field, descriptor, owner, simpleTypeHolder); if (owningClassInfo == null) { logger.warn("Owning ClassInfo is null for field: {} and propertyDescriptor: {}", field, descriptor); } - if ((owningClassInfo != null && owningClassInfo.getUnderlyingClass() != null && simpleTypeHolder.isSimpleType(owningClassInfo.getUnderlyingClass())) - || owner.getType().isEnum()) { //TODO refactor all these null checks + if ((owningClassInfo != null && owningClassInfo.getUnderlyingClass() != null + && simpleTypeHolder.isSimpleType(owningClassInfo.getUnderlyingClass())) || owner.getType().isEnum()) { // TODO + // refactor + // all + // these + // null + // checks this.isIdProperty = false; } else { this.isIdProperty = resolveWhetherIdProperty(owningClassInfo, field); @@ -84,7 +88,8 @@ public class Neo4jPersistentProperty extends AnnotationBasedPersistentProperty * This implementation works by looking for non-transient members annotated with @Relationship. *

    @@ -132,10 +137,8 @@ public class Neo4jPersistentProperty extends AnnotationBasedPersistentProperty extends Neo4jRepository { Iterable findAll(Sort sort, int depth); - Iterable findAll(Iterable ids); Iterable findAll(Iterable ids, int depth); @@ -51,7 +49,8 @@ public interface GraphRepository extends Neo4jRepository { /** * Returns a {@link Page} of entities meeting the paging restriction provided in the {@code Pageable} object. - * {@link Page#getTotalPages()} returns an estimation of the total number of pages and should not be relied upon for accuracy. + * {@link Page#getTotalPages()} returns an estimation of the total number of pages and should not be relied upon for + * accuracy. * * @param pageable * @return a page of entities @@ -60,7 +59,8 @@ public interface GraphRepository extends Neo4jRepository { /** * Returns a {@link Page} of entities meeting the paging restriction provided in the {@code Pageable} object. - * {@link Page#getTotalPages()} returns an estimation of the total number of pages and should not be relied upon for accuracy. + * {@link Page#getTotalPages()} returns an estimation of the total number of pages and should not be relied upon for + * accuracy. * * @param pageable * @param depth diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/Neo4jRepository.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/Neo4jRepository.java index bdc87fc4f..016452ed2 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/Neo4jRepository.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/Neo4jRepository.java @@ -54,7 +54,8 @@ public interface Neo4jRepository extends PagingAndSo /** * Returns a {@link Page} of entities meeting the paging restriction provided in the {@code Pageable} object. - * {@link Page#getTotalPages()} returns an estimation of the total number of pages and should not be relied upon for accuracy. + * {@link Page#getTotalPages()} returns an estimation of the total number of pages and should not be relied upon for + * accuracy. * * @param pageable * @return a page of entities @@ -63,7 +64,8 @@ public interface Neo4jRepository extends PagingAndSo /** * Returns a {@link Page} of entities meeting the paging restriction provided in the {@code Pageable} object. - * {@link Page#getTotalPages()} returns an estimation of the total number of pages and should not be relied upon for accuracy. + * {@link Page#getTotalPages()} returns an estimation of the total number of pages and should not be relied upon for + * accuracy. * * @param pageable * @param depth diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiRepositoryBean.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiRepositoryBean.java index fc9851c20..1cfe47b8e 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiRepositoryBean.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiRepositoryBean.java @@ -16,16 +16,17 @@ package org.springframework.data.neo4j.repository.cdi; -import org.neo4j.ogm.session.Session; -import org.springframework.data.neo4j.repository.support.Neo4jRepositoryFactory; -import org.springframework.data.repository.cdi.CdiRepositoryBean; -import org.springframework.data.repository.config.CustomRepositoryImplementationDetector; +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 java.lang.annotation.Annotation; -import java.util.Set; + +import org.neo4j.ogm.session.Session; +import org.springframework.data.neo4j.repository.support.Neo4jRepositoryFactory; +import org.springframework.data.repository.cdi.CdiRepositoryBean; +import org.springframework.data.repository.config.CustomRepositoryImplementationDetector; /** * {@link org.springframework.data.repository.cdi.CdiRepositoryBean} to create Neo4j repository instances via CDI. @@ -34,30 +35,30 @@ import java.util.Set; * @since 4.2 */ public class Neo4jCdiRepositoryBean extends CdiRepositoryBean { - private final Bean sessionBean; + private final Bean sessionBean; - /** - * Creates a new {@link Neo4jCdiRepositoryBean}. - * - * @param sessionBean 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 Neo4jCdiRepositoryBean(Bean sessionBean, Set qualifiers, Class repositoryType, - BeanManager beanManager, CustomRepositoryImplementationDetector detector) { - super(qualifiers, repositoryType, beanManager, detector); - this.sessionBean = sessionBean; - } + /** + * Creates a new {@link Neo4jCdiRepositoryBean}. + * + * @param sessionBean 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 Neo4jCdiRepositoryBean(Bean sessionBean, Set qualifiers, Class repositoryType, + BeanManager beanManager, CustomRepositoryImplementationDetector detector) { + super(qualifiers, repositoryType, beanManager, detector); + this.sessionBean = sessionBean; + } - @Override - protected T create(CreationalContext creationalContext, Class repositoryType, Object customImplementation) { + @Override + protected T create(CreationalContext creationalContext, Class repositoryType, Object customImplementation) { - Session session = getDependencyInstance(sessionBean, Session.class); + Session session = getDependencyInstance(sessionBean, Session.class); - Neo4jRepositoryFactory factory = new Neo4jRepositoryFactory(session); - return factory.getRepository(repositoryType, customImplementation); - } + Neo4jRepositoryFactory factory = new Neo4jRepositoryFactory(session); + return factory.getRepository(repositoryType, customImplementation); + } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiRepositoryExtension.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiRepositoryExtension.java index 60b40dfef..fba1091df 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiRepositoryExtension.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiRepositoryExtension.java @@ -16,18 +16,6 @@ package org.springframework.data.neo4j.repository.cdi; -import org.neo4j.ogm.session.Session; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.repository.cdi.CdiRepositoryBean; -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; @@ -36,6 +24,19 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; +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 org.neo4j.ogm.session.Session; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.repository.cdi.CdiRepositoryBean; +import org.springframework.data.repository.cdi.CdiRepositoryExtensionSupport; + /** * CDI extension to export Neo4j repositories. * @@ -44,68 +45,66 @@ import java.util.Set; */ public class Neo4jCdiRepositoryExtension extends CdiRepositoryExtensionSupport { - private static final Logger LOG = LoggerFactory.getLogger(Neo4jCdiRepositoryExtension.class); - private final Map, Bean> sessions = new HashMap, Bean>(); + private static final Logger LOG = LoggerFactory.getLogger(Neo4jCdiRepositoryExtension.class); + private final Map, Bean> sessions = new HashMap, Bean>(); - public Neo4jCdiRepositoryExtension() { - LOG.info("Activating CDI extension for Spring Data Neo4j repositories."); - } + public Neo4jCdiRepositoryExtension() { + LOG.info("Activating CDI extension for Spring Data Neo4j repositories."); + } - @SuppressWarnings("unchecked") - void processBean(@Observes ProcessBean processBean) { - Bean bean = processBean.getBean(); + @SuppressWarnings("unchecked") + void processBean(@Observes ProcessBean processBean) { + Bean bean = processBean.getBean(); - for (Type type : bean.getTypes()) { - if (type instanceof Class && Session.class.isAssignableFrom((Class) type)) { + for (Type type : bean.getTypes()) { + if (type instanceof Class && Session.class.isAssignableFrom((Class) type)) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Discovered %s with qualifiers %s.", Session.class.getName(), - bean.getQualifiers())); - } + if (LOG.isDebugEnabled()) { + LOG.debug(String.format("Discovered %s with qualifiers %s.", Session.class.getName(), bean.getQualifiers())); + } - sessions.put(new HashSet(bean.getQualifiers()), (Bean) bean); - } - } - } + sessions.put(new HashSet(bean.getQualifiers()), (Bean) bean); + } + } + } - void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) { + void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) { - for (Entry, Set> entry : getRepositoryTypes()) { + for (Entry, Set> entry : getRepositoryTypes()) { - Class repositoryType = entry.getKey(); - Set qualifiers = entry.getValue(); + Class repositoryType = entry.getKey(); + Set qualifiers = entry.getValue(); - // Create the bean representing the repository. - CdiRepositoryBean repositoryBean = createRepositoryBean(repositoryType, qualifiers, beanManager); - if (LOG.isInfoEnabled()) { - LOG.info(String.format("Registering bean for %s with qualifiers %s.", repositoryType.getName(), - qualifiers)); - } + // Create the bean representing the repository. + CdiRepositoryBean 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. - registerBean(repositoryBean); - afterBeanDiscovery.addBean(repositoryBean); - } - } + // Register the bean to the container. + registerBean(repositoryBean); + afterBeanDiscovery.addBean(repositoryBean); + } + } - /** - * Creates a {@link Bean}. - * - * @param The type of the repository. - * @param repositoryType The class representing the repository. - * @param beanManager The BeanManager instance. - * @return The bean. - */ - private CdiRepositoryBean createRepositoryBean(Class repositoryType, Set qualifiers, - BeanManager beanManager) { - Bean sessionBean = this.sessions.get(qualifiers); + /** + * Creates a {@link Bean}. + * + * @param The type of the repository. + * @param repositoryType The class representing the repository. + * @param beanManager The BeanManager instance. + * @return The bean. + */ + private CdiRepositoryBean createRepositoryBean(Class repositoryType, Set qualifiers, + BeanManager beanManager) { + Bean sessionBean = this.sessions.get(qualifiers); - if (sessionBean == null) { - throw new UnsatisfiedResolutionException(String.format( - "Unable to resolve a bean for '%s' with qualifiers %s.", Session.class.getName(), qualifiers)); - } + if (sessionBean == null) { + throw new UnsatisfiedResolutionException( + String.format("Unable to resolve a bean for '%s' with qualifiers %s.", Session.class.getName(), qualifiers)); + } - return new Neo4jCdiRepositoryBean(sessionBean, qualifiers, repositoryType, beanManager, - getCustomImplementationDetector()); - } + return new Neo4jCdiRepositoryBean(sessionBean, qualifiers, repositoryType, beanManager, + getCustomImplementationDetector()); + } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/config/EnableNeo4jRepositories.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/config/EnableNeo4jRepositories.java index 2daef0cb2..14c67dfb0 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/config/EnableNeo4jRepositories.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/config/EnableNeo4jRepositories.java @@ -13,7 +13,12 @@ package org.springframework.data.neo4j.repository.config; -import java.lang.annotation.*; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import org.neo4j.ogm.session.SessionFactory; import org.springframework.context.annotation.ComponentScan; @@ -37,93 +42,93 @@ import org.springframework.transaction.PlatformTransactionManager; @Import(Neo4jRepositoriesRegistrar.class) public @interface EnableNeo4jRepositories { - /** - * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.: - * {@code @EnableExperimentalNeo4jRepositories("org.my.pkg")} instead of - * {@code @EnableExperimentalNeo4jRepositories(basePackages="org.my.pkg")}. - */ - String[] value() default {}; + /** + * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.: + * {@code @EnableExperimentalNeo4jRepositories("org.my.pkg")} instead of + * {@code @EnableExperimentalNeo4jRepositories(basePackages="org.my.pkg")}. + */ + String[] value() default {}; - /** - * Base packages to scan for annotated components. {@link #value()} is an alias for (and mutually exclusive with) this - * attribute. Use {@link #basePackageClasses()} for a type-safe alternative to String-based package names. - */ - String[] basePackages() default {}; + /** + * Base packages to scan for annotated components. {@link #value()} is an alias for (and mutually exclusive with) this + * attribute. Use {@link #basePackageClasses()} for a type-safe alternative to String-based package names. + */ + String[] basePackages() default {}; - /** - * Type-safe alternative to {@link #basePackages()} for specifying the packages to scan for annotated components. The - * package of each class specified will be scanned. Consider creating a special no-op marker class or interface in - * each package that serves no purpose other than being referenced by this attribute. - */ - Class[] basePackageClasses() default {}; + /** + * Type-safe alternative to {@link #basePackages()} for specifying the packages to scan for annotated components. The + * package of each class specified will be scanned. Consider creating a special no-op marker class or interface in + * each package that serves no purpose other than being referenced by this attribute. + */ + Class[] basePackageClasses() default {}; - /** - * Specifies which types are eligible for component scanning. Further narrows the set of candidate components from - * everything in {@link #basePackages()} to everything in the base packages that matches the given filter or filters. - */ - ComponentScan.Filter[] includeFilters() default {}; + /** + * Specifies which types are eligible for component scanning. Further narrows the set of candidate components from + * everything in {@link #basePackages()} to everything in the base packages that matches the given filter or filters. + */ + ComponentScan.Filter[] includeFilters() default {}; - /** - * Specifies which types are not eligible for component scanning. - */ - ComponentScan.Filter[] excludeFilters() default {}; + /** + * Specifies which types are not eligible for component scanning. + */ + ComponentScan.Filter[] excludeFilters() default {}; - /** - * Returns the postfix to be used when looking up custom repository implementations. Defaults to {@literal Impl}. So - * for a repository named {@code PersonRepository} the corresponding implementation class will be looked up scanning - * for {@code PersonRepositoryImpl}. - */ - String repositoryImplementationPostfix() default "Impl"; + /** + * Returns the postfix to be used when looking up custom repository implementations. Defaults to {@literal Impl}. So + * for a repository named {@code PersonRepository} the corresponding implementation class will be looked up scanning + * for {@code PersonRepositoryImpl}. + */ + String repositoryImplementationPostfix() default "Impl"; - /** - * Configures the location of where to find the Spring Data named queries properties file. Will default to - * {@code META-INFO/neo4j-named-queries.properties}. - */ - String namedQueriesLocation() default ""; + /** + * Configures the location of where to find the Spring Data named queries properties file. Will default to + * {@code META-INFO/neo4j-named-queries.properties}. + */ + String namedQueriesLocation() default ""; - /** - * Returns the key of the {@link QueryLookupStrategy} to be used for lookup queries for query methods. Defaults to - * {@link org.springframework.data.repository.query.QueryLookupStrategy.Key#CREATE_IF_NOT_FOUND}. - */ - QueryLookupStrategy.Key queryLookupStrategy() default QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND; + /** + * Returns the key of the {@link QueryLookupStrategy} to be used for lookup queries for query methods. Defaults to + * {@link org.springframework.data.repository.query.QueryLookupStrategy.Key#CREATE_IF_NOT_FOUND}. + */ + QueryLookupStrategy.Key queryLookupStrategy() default QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND; - /** - * Returns the {@link org.springframework.beans.factory.FactoryBean} class to be used for each repository instance. Defaults to - * {@link Neo4jRepositoryFactoryBean}. - */ - Class repositoryFactoryBeanClass() default Neo4jRepositoryFactoryBean.class; + /** + * Returns the {@link org.springframework.beans.factory.FactoryBean} class to be used for each repository instance. + * Defaults to {@link Neo4jRepositoryFactoryBean}. + */ + Class repositoryFactoryBeanClass() default Neo4jRepositoryFactoryBean.class; - /** - * Configure the repository base class to be used to create repository proxies for this particular configuration. - * - * @return - */ - Class repositoryBaseClass() default DefaultRepositoryBaseClass.class; + /** + * Configure the repository base class to be used to create repository proxies for this particular configuration. + * + * @return + */ + Class repositoryBaseClass() default DefaultRepositoryBaseClass.class; - /** - * Configures the name of the {@link SessionFactory} bean definition to be used to create repositories - * discovered through this annotation. Defaults to {@code sessionFactory}. - */ - String sessionFactoryRef() default "sessionFactory"; + /** + * Configures the name of the {@link SessionFactory} bean definition to be used to create repositories discovered + * through this annotation. Defaults to {@code sessionFactory}. + */ + String sessionFactoryRef() default "sessionFactory"; - /** - * Configures the name of the {@link PlatformTransactionManager} bean definition to be used to create repositories - * discovered through this annotation. Defaults to {@code transactionManager}. - */ - String transactionManagerRef() default "transactionManager"; + /** + * Configures the name of the {@link PlatformTransactionManager} bean definition to be used to create repositories + * discovered through this annotation. Defaults to {@code transactionManager}. + */ + String transactionManagerRef() default "transactionManager"; - /** - * Configures whether nested repository-interfaces (e.g. defined as inner classes) should be discovered by the - * repositories infrastructure. - */ - boolean considerNestedRepositories() default false; + /** + * Configures whether nested repository-interfaces (e.g. defined as inner classes) should be discovered by the + * repositories infrastructure. + */ + boolean considerNestedRepositories() default false; - /** - * Configures whether to enable default transactions for Spring Data Neo4j repositories. Defaults to {@literal true}. If - * disabled, repositories must be used behind a facade that's configuring transactions (e.g. using Spring's annotation - * driven transaction facilities) or repository methods have to be used to demarcate transactions. - * - * @return whether to enable default transactions, defaults to {@literal true}. - */ - boolean enableDefaultTransactions() default true; + /** + * Configures whether to enable default transactions for Spring Data Neo4j repositories. Defaults to {@literal true}. + * If disabled, repositories must be used behind a facade that's configuring transactions (e.g. using Spring's + * annotation driven transaction facilities) or repository methods have to be used to demarcate transactions. + * + * @return whether to enable default transactions, defaults to {@literal true}. + */ + boolean enableDefaultTransactions() default true; } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/config/Neo4jMappingContextFactoryBean.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/config/Neo4jMappingContextFactoryBean.java index fe22b316d..236368c5d 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/config/Neo4jMappingContextFactoryBean.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/config/Neo4jMappingContextFactoryBean.java @@ -13,7 +13,6 @@ package org.springframework.data.neo4j.repository.config; - import org.neo4j.ogm.session.SessionFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.FactoryBean; @@ -28,8 +27,8 @@ import org.springframework.data.neo4j.mapping.Neo4jMappingContext; * * @author Mark Angrish */ -class Neo4jMappingContextFactoryBean extends AbstractFactoryBean implements - ApplicationContextAware { +class Neo4jMappingContextFactoryBean extends AbstractFactoryBean + implements ApplicationContextAware { private ListableBeanFactory beanFactory; @@ -52,9 +51,9 @@ class Neo4jMappingContextFactoryBean extends AbstractFactoryBean resolveConcreteReturnType() { - Class type = this.method.getReturnType(); - Type genericType = this.method.getGenericReturnType(); + /** + * @return The concrete, non-generic return type of this query method - i.e., the type to which graph database query + * results should be mapped + */ + public Class resolveConcreteReturnType() { + Class type = this.method.getReturnType(); + Type genericType = this.method.getGenericReturnType(); - if (Iterable.class.isAssignableFrom(type)) { - if (genericType instanceof ParameterizedType) { - ParameterizedType returnType = (ParameterizedType) genericType; - Type componentType = returnType.getActualTypeArguments()[0]; + if (Iterable.class.isAssignableFrom(type)) { + if (genericType instanceof ParameterizedType) { + ParameterizedType returnType = (ParameterizedType) genericType; + Type componentType = returnType.getActualTypeArguments()[0]; - if (componentType instanceof TypeVariable) { - return this.getDomainClass(); - } - return componentType instanceof ParameterizedType ? - (Class) ((ParameterizedType) componentType).getRawType() : - (Class) componentType; - } else { - return Object.class; - } - } + if (componentType instanceof TypeVariable) { + return this.getDomainClass(); + } + return componentType instanceof ParameterizedType ? (Class) ((ParameterizedType) componentType).getRawType() + : (Class) componentType; + } else { + return Object.class; + } + } - return type; - } + return type; + } - public RepositoryQuery createQuery() { - if (method.getAnnotation(Query.class) != null) { - if (resolveConcreteReturnType().isAnnotationPresent(QueryResult.class)) { - return new QueryResultGraphRepositoryQuery(this, session); - } - return new GraphRepositoryQuery(this, session); - } - return new DerivedGraphRepositoryQuery(this, session); + public RepositoryQuery createQuery() { + if (method.getAnnotation(Query.class) != null) { + if (resolveConcreteReturnType().isAnnotationPresent(QueryResult.class)) { + return new QueryResultGraphRepositoryQuery(this, session); + } + return new GraphRepositoryQuery(this, session); + } + return new DerivedGraphRepositoryQuery(this, session); - } + } - public Integer getQueryDepthParamIndex() { - return queryDepthParamIndex; - } + public Integer getQueryDepthParamIndex() { + return queryDepthParamIndex; + } - public Integer getQueryDepth() { - return queryDepth; - } + public Integer getQueryDepth() { + return queryDepth; + } - public boolean hasStaticDepth() { - return staticDepth; - } + public boolean hasStaticDepth() { + return staticDepth; + } - private Integer getQueryDepthParamIndex(Method method) { - Annotation[][] annotations = method.getParameterAnnotations(); - for (int i = 0; i < annotations.length; i++) { - if (annotations[i].length > 0) { - for (Annotation annotation : annotations[i]) { - if (annotation.annotationType() == Depth.class) { - if (method.getParameterTypes()[i] == Integer.class || method.getParameterTypes()[i] == int.class) { - return i; - } - else { - throw new IllegalArgumentException("Depth parameter in " + method.getName() + " must be an integer"); - } - } - } - } - } - /* - //Java 8 only - Parameter[] parameters = method.getParameters(); - for (int i = 0; i < method.getParameterCount(); i++) { - if (parameters[i].isAnnotationPresent(Depth.class)) { - if (parameters[i].getType() == Integer.class || parameters[i].getType() == int.class) { - return i; - } - else { - throw new IllegalArgumentException("Depth parameter in " + method.getName() + " must be an integer"); - } - } - }*/ - return null; - } + private Integer getQueryDepthParamIndex(Method method) { + Annotation[][] annotations = method.getParameterAnnotations(); + for (int i = 0; i < annotations.length; i++) { + if (annotations[i].length > 0) { + for (Annotation annotation : annotations[i]) { + if (annotation.annotationType() == Depth.class) { + if (method.getParameterTypes()[i] == Integer.class || method.getParameterTypes()[i] == int.class) { + return i; + } else { + throw new IllegalArgumentException("Depth parameter in " + method.getName() + " must be an integer"); + } + } + } + } + } + /* + //Java 8 only + Parameter[] parameters = method.getParameters(); + for (int i = 0; i < method.getParameterCount(); i++) { + if (parameters[i].isAnnotationPresent(Depth.class)) { + if (parameters[i].getType() == Integer.class || parameters[i].getType() == int.class) { + return i; + } + else { + throw new IllegalArgumentException("Depth parameter in " + method.getName() + " must be an integer"); + } + } + }*/ + return null; + } - private Integer getStaticQueryDepth(Method method) { - if (method.isAnnotationPresent(Depth.class)) { - staticDepth = true; - return method.getAnnotation(Depth.class).value(); - } - return null; - } + private Integer getStaticQueryDepth(Method method) { + if (method.isAnnotationPresent(Depth.class)) { + staticDepth = true; + return method.getAnnotation(Depth.class).value(); + } + return null; + } - - public String getCountQueryString() { - return queryAnnotation != null ? queryAnnotation.countQuery() : null; - } + public String getCountQueryString() { + return queryAnnotation != null ? queryAnnotation.countQuery() : null; + } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/GraphRepositoryQuery.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/GraphRepositoryQuery.java index a07757e24..081629d14 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/GraphRepositoryQuery.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/GraphRepositoryQuery.java @@ -13,7 +13,6 @@ package org.springframework.data.neo4j.repository.query; - import java.util.HashMap; import java.util.List; import java.util.Map; @@ -21,7 +20,10 @@ import java.util.Map; import org.neo4j.ogm.model.QueryStatistics; import org.neo4j.ogm.model.Result; import org.neo4j.ogm.session.Session; -import org.springframework.data.domain.*; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.SliceImpl; +import org.springframework.data.domain.Sort; import org.springframework.data.repository.query.Parameter; import org.springframework.data.repository.query.ParameterAccessor; import org.springframework.data.repository.query.Parameters; @@ -30,7 +32,6 @@ import org.springframework.data.repository.query.RepositoryQuery; import org.springframework.data.repository.query.ResultProcessor; import org.springframework.util.StringUtils; - /** * Specialisation of {@link RepositoryQuery} that handles mapping to object annotated with @Query. * @@ -64,12 +65,11 @@ public class GraphRepositoryQuery implements RepositoryQuery { ResultProcessor processor = graphQueryMethod.getResultProcessor(); Object result = execute(returnType, concreteType, getQueryString(), params, accessor); - return Result.class.equals(returnType) ? result : - processor.withDynamicProjection(accessor).processResult(result); + return Result.class.equals(returnType) ? result : processor.withDynamicProjection(accessor).processResult(result); } protected Object execute(Class returnType, Class concreteType, String cypherQuery, - Map queryParams, ParameterAccessor parameterAccessor) { + Map queryParams, ParameterAccessor parameterAccessor) { Pageable pageable = parameterAccessor.getPageable(); Sort sort = parameterAccessor.getSort(); @@ -77,7 +77,7 @@ public class GraphRepositoryQuery implements RepositoryQuery { sort = pageable.getSort(); } if (sort != null) { - //Custom queries in the OGM do not support pageable + // Custom queries in the OGM do not support pageable cypherQuery = addSorting(cypherQuery, sort); } @@ -106,7 +106,6 @@ public class GraphRepositoryQuery implements RepositoryQuery { return getQueryMethod().getQuery(); } - protected Object createPage(GraphQueryMethod graphQueryMethod, List resultList, Pageable pageable, Long count) { if (pageable == null) { return graphQueryMethod.isPageQuery() ? new PageImpl(resultList) : new SliceImpl(resultList); @@ -116,15 +115,15 @@ public class GraphRepositoryQuery implements RepositoryQuery { currentTotal = count.intValue(); } else { int pageOffset = pageable.getOffset(); - currentTotal = pageOffset + resultList.size() + (resultList.size() == pageable.getPageSize() ? pageable.getPageSize() : 0); + currentTotal = pageOffset + resultList.size() + + (resultList.size() == pageable.getPageSize() ? pageable.getPageSize() : 0); } int resultWindowSize = Math.min(resultList.size(), pageable.getPageSize()); boolean hasNext = resultWindowSize < resultList.size(); List resultListPage = resultList.subList(0, resultWindowSize); - return graphQueryMethod.isPageQuery() ? - new PageImpl(resultListPage, pageable, currentTotal) : - new SliceImpl(resultListPage, pageable, hasNext); + return graphQueryMethod.isPageQuery() ? new PageImpl(resultListPage, pageable, currentTotal) + : new SliceImpl(resultListPage, pageable, hasNext); } protected String addSorting(String baseQuery, Sort sort) { @@ -140,7 +139,7 @@ public class GraphRepositoryQuery implements RepositoryQuery { } protected String addPaging(String cypherQuery, Map queryParams, int pageNumber, int pageSize) { - //Custom queries in the OGM do not support pageable + // Custom queries in the OGM do not support pageable cypherQuery = formatBaseQuery(cypherQuery); cypherQuery = cypherQuery + SKIP_LIMIT; queryParams.put(SKIP, pageNumber * pageSize); @@ -177,9 +176,9 @@ public class GraphRepositoryQuery implements RepositoryQuery { for (int i = 0; i < parameters.length; i++) { Parameter parameter = methodParameters.getParameter(i); - //The parameter might be an entity, try to resolve its id + // The parameter might be an entity, try to resolve its id Object parameterValue = session.resolveGraphIdFor(parameters[i]); - if (parameterValue == null) { //Either not an entity or not persisted + if (parameterValue == null) { // Either not an entity or not persisted parameterValue = parameters[i]; } @@ -192,7 +191,8 @@ public class GraphRepositoryQuery implements RepositoryQuery { return params; } - private Object mappedCollection(Class concreteType, String cypherQuery, Map queryParams, Pageable pageable) {// Special method to handle SDN Iterable> behaviour. + private Object mappedCollection(Class concreteType, String cypherQuery, Map queryParams, + Pageable pageable) {// Special method to handle SDN Iterable> behaviour. // TODO: Do we really want this method in an OGM? It's a little too low level and/or doesn't really fit. if (Map.class.isAssignableFrom(concreteType)) { return session.query(cypherQuery, queryParams).queryResults(); diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/QueryResultGraphRepositoryQuery.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/QueryResultGraphRepositoryQuery.java index 3207f682a..6913019aa 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/QueryResultGraphRepositoryQuery.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/QueryResultGraphRepositoryQuery.java @@ -13,8 +13,7 @@ package org.springframework.data.neo4j.repository.query; - -import static java.lang.reflect.Proxy.newProxyInstance; +import static java.lang.reflect.Proxy.*; import java.util.ArrayList; import java.util.Collection; @@ -33,7 +32,8 @@ import org.springframework.data.domain.Sort; import org.springframework.data.repository.query.ParameterAccessor; /** - * Specialisation of {@link GraphRepositoryQuery} that handles mapping to objects annotated with @QueryResult. + * Specialisation of {@link GraphRepositoryQuery} that handles mapping to objects annotated with + * @QueryResult. * * @author Adam George * @author Luanne Misquitta @@ -53,7 +53,7 @@ public class QueryResultGraphRepositoryQuery extends GraphRepositoryQuery { @Override protected Object execute(Class returnType, final Class concreteReturnType, String cypherQuery, - Map queryParams, ParameterAccessor parameterAccessor) { + Map queryParams, ParameterAccessor parameterAccessor) { Pageable pageable = parameterAccessor.getPageable(); Sort sort = parameterAccessor.getSort(); @@ -61,7 +61,7 @@ public class QueryResultGraphRepositoryQuery extends GraphRepositoryQuery { sort = pageable.getSort(); } if (sort != null) { - //Custom queries in the OGM do not support pageable + // Custom queries in the OGM do not support pageable cypherQuery = addSorting(cypherQuery, sort); } @@ -78,7 +78,7 @@ public class QueryResultGraphRepositoryQuery extends GraphRepositoryQuery { } private Object mapToConcreteType(final Class targetType, final String cypherQuery, - final Map queryParams, Pageable pageable) { + final Map queryParams, Pageable pageable) { if (graphQueryMethod.isPageQuery() || graphQueryMethod.isSliceQuery()) { final String query = addPaging(cypherQuery, queryParams, pageable.getPageNumber(), pageable.getPageSize()); @@ -90,7 +90,7 @@ public class QueryResultGraphRepositoryQuery extends GraphRepositoryQuery { } private Object mapToProxy(Class targetType, String cypherQuery, Map queryParams, - Pageable pageable) { + Pageable pageable) { if (graphQueryMethod.isPageQuery() || graphQueryMethod.isSliceQuery()) { final String query = addPaging(cypherQuery, queryParams, pageable.getPageNumber(), pageable.getPageSize()); List objects = mappedProxyResults(targetType, this.session.query(query, queryParams)); @@ -100,7 +100,8 @@ public class QueryResultGraphRepositoryQuery extends GraphRepositoryQuery { } } - private List mappedConcreteResults(final Class targetType, final String query, final Map queryParams) { + private List mappedConcreteResults(final Class targetType, final String query, + final Map queryParams) { return (List) this.session.doInTransaction(new GraphCallback>() { @Override public Collection apply(Request requestHandler, Transaction transaction, MetaData metaData) { @@ -117,7 +118,7 @@ public class QueryResultGraphRepositoryQuery extends GraphRepositoryQuery { private List mappedProxyResults(Class targetType, Iterable> queryResults) { List resultObjects = new ArrayList<>(); - Class[] interfaces = new Class[]{targetType}; + Class[] interfaces = new Class[] { targetType }; for (Map map : queryResults) { resultObjects.add(newProxyInstance(targetType.getClassLoader(), interfaces, new QueryResultProxy(map))); } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/QueryResultProxy.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/QueryResultProxy.java index b5f593027..eead8f1c8 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/QueryResultProxy.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/QueryResultProxy.java @@ -13,17 +13,17 @@ package org.springframework.data.neo4j.repository.query; -import org.neo4j.ogm.annotation.Property; -import org.neo4j.ogm.session.Utils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.neo4j.ogm.annotation.Property; +import org.neo4j.ogm.session.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Method {@link InvocationHandler} used for proxy objects that implement arbitrary interfaces annotated with * @QueryResult. @@ -32,41 +32,41 @@ import java.util.regex.Pattern; */ class QueryResultProxy implements InvocationHandler { - private static final Logger log = LoggerFactory.getLogger(QueryResultProxy.class); + private static final Logger log = LoggerFactory.getLogger(QueryResultProxy.class); - private static final Pattern beanGetterPattern = Pattern.compile("^(is|get)(\\w+)"); + private static final Pattern beanGetterPattern = Pattern.compile("^(is|get)(\\w+)"); - private final Map data; + private final Map data; - QueryResultProxy(Map queryResults) { - this.data = queryResults; - } + QueryResultProxy(Map queryResults) { + this.data = queryResults; + } - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - if (isNotTraditionalGetter(method)) { - log.warn("QueryResult interface method " + method.getName() - + " doesn't appear to be a getter and therefore may not return the correct result."); - } + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (isNotTraditionalGetter(method)) { + log.warn("QueryResult interface method " + method.getName() + + " doesn't appear to be a getter and therefore may not return the correct result."); + } - if (method.isAnnotationPresent(Property.class)) { - Property annotation = method.getAnnotation(Property.class); - return Utils.coerceTypes(method.getReturnType(), data.get(annotation.name())); - } + if (method.isAnnotationPresent(Property.class)) { + Property annotation = method.getAnnotation(Property.class); + return Utils.coerceTypes(method.getReturnType(), data.get(annotation.name())); + } - Matcher matcher = beanGetterPattern.matcher(method.getName()); - if (matcher.matches()) { - String propertyKey = matcher.group(2); - propertyKey = propertyKey.substring(0, 1).toLowerCase().concat(propertyKey.substring(1)); - return Utils.coerceTypes(method.getReturnType(),data.get(propertyKey)); - } + Matcher matcher = beanGetterPattern.matcher(method.getName()); + if (matcher.matches()) { + String propertyKey = matcher.group(2); + propertyKey = propertyKey.substring(0, 1).toLowerCase().concat(propertyKey.substring(1)); + return Utils.coerceTypes(method.getReturnType(), data.get(propertyKey)); + } - return Utils.coerceTypes(method.getReturnType(), data.get(method.getName())); - } + return Utils.coerceTypes(method.getReturnType(), data.get(method.getName())); + } - private boolean isNotTraditionalGetter(Method method) { - return method.getParameterTypes().length != 0 || Void.class.equals(method.getReturnType()) - || (!method.getName().startsWith("get") && !method.getName().startsWith("is")); - } + private boolean isNotTraditionalGetter(Method method) { + return method.getParameterTypes().length != 0 || Void.class.equals(method.getReturnType()) + || (!method.getName().startsWith("get") && !method.getName().startsWith("is")); + } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/CypherFinderQuery.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/CypherFinderQuery.java index 75108542d..cb079c144 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/CypherFinderQuery.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/CypherFinderQuery.java @@ -12,11 +12,21 @@ */ package org.springframework.data.neo4j.repository.query.derived; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Stack; import org.neo4j.ogm.cypher.BooleanOperator; import org.neo4j.ogm.cypher.Filter; -import org.springframework.data.neo4j.repository.query.derived.builder.*; +import org.springframework.data.neo4j.repository.query.derived.builder.BetweenComparisonBuilder; +import org.springframework.data.neo4j.repository.query.derived.builder.BooleanComparisonBuilder; +import org.springframework.data.neo4j.repository.query.derived.builder.DistanceComparisonBuilder; +import org.springframework.data.neo4j.repository.query.derived.builder.ExistsFilterBuilder; +import org.springframework.data.neo4j.repository.query.derived.builder.FilterBuilder; +import org.springframework.data.neo4j.repository.query.derived.builder.IsNullFilterBuilder; +import org.springframework.data.neo4j.repository.query.derived.builder.PropertyComparisonBuilder; import org.springframework.data.repository.query.parser.Part; /** @@ -28,64 +38,64 @@ import org.springframework.data.repository.query.parser.Part; */ public class CypherFinderQuery implements DerivedQueryDefinition { - private Class entityType; - private Part basePart; - private List filterBuilders = new ArrayList<>(); + private Class entityType; + private Part basePart; + private List filterBuilders = new ArrayList<>(); - CypherFinderQuery(Class entityType, Part basePart) { - this.entityType = entityType; - this.basePart = basePart; - } + CypherFinderQuery(Class entityType, Part basePart) { + this.entityType = entityType; + this.basePart = basePart; + } - @Override - public Part getBasePart() { //because the OR is handled in a weird way. Luanne, explain better - return basePart; - } + @Override + public Part getBasePart() { // because the OR is handled in a weird way. Luanne, explain better + return basePart; + } - @Override - public List getFilters(Map params) { + @Override + public List getFilters(Map params) { - // buiding a stack of parameter values, so that the builders can pull them - // according to their needs (zero, one or more parameters) - // avoids to manage a current parameter index state here. - Stack parametersStack = new Stack<>(); - if (!params.isEmpty()) { - Integer maxParameterIndex = Collections.max(params.keySet()); - for (int i = 0; i <= maxParameterIndex; i++) { - parametersStack.add(0, params.get(i)); - } - } + // buiding a stack of parameter values, so that the builders can pull them + // according to their needs (zero, one or more parameters) + // avoids to manage a current parameter index state here. + Stack parametersStack = new Stack<>(); + if (!params.isEmpty()) { + Integer maxParameterIndex = Collections.max(params.keySet()); + for (int i = 0; i <= maxParameterIndex; i++) { + parametersStack.add(0, params.get(i)); + } + } - List filters = new ArrayList<>(); - for (FilterBuilder filterBuilder : filterBuilders) { - filters.addAll(filterBuilder.build(parametersStack)); - } - return filters; - } + List filters = new ArrayList<>(); + for (FilterBuilder filterBuilder : filterBuilders) { + filters.addAll(filterBuilder.build(parametersStack)); + } + return filters; + } - @Override - public void addPart(Part part, BooleanOperator booleanOperator) { + @Override + public void addPart(Part part, BooleanOperator booleanOperator) { - FilterBuilder builder = builderForPart(part, booleanOperator); - filterBuilders.add(builder); - } + FilterBuilder builder = builderForPart(part, booleanOperator); + filterBuilders.add(builder); + } - private FilterBuilder builderForPart(Part part, BooleanOperator booleanOperator) { - switch (part.getType()) { - case NEAR: - return new DistanceComparisonBuilder(part, booleanOperator, entityType); - case BETWEEN: - return new BetweenComparisonBuilder(part, booleanOperator, entityType); - case IS_NULL: - case IS_NOT_NULL: - return new IsNullFilterBuilder(part, booleanOperator, entityType); - case EXISTS: - return new ExistsFilterBuilder(part, booleanOperator, entityType); - case TRUE: - case FALSE: - return new BooleanComparisonBuilder(part, booleanOperator, entityType); - default: - return new PropertyComparisonBuilder(part, booleanOperator, entityType); - } - } + private FilterBuilder builderForPart(Part part, BooleanOperator booleanOperator) { + switch (part.getType()) { + case NEAR: + return new DistanceComparisonBuilder(part, booleanOperator, entityType); + case BETWEEN: + return new BetweenComparisonBuilder(part, booleanOperator, entityType); + case IS_NULL: + case IS_NOT_NULL: + return new IsNullFilterBuilder(part, booleanOperator, entityType); + case EXISTS: + return new ExistsFilterBuilder(part, booleanOperator, entityType); + case TRUE: + case FALSE: + return new BooleanComparisonBuilder(part, booleanOperator, entityType); + default: + return new PropertyComparisonBuilder(part, booleanOperator, entityType); + } + } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedGraphRepositoryQuery.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedGraphRepositoryQuery.java index 04be1a21b..1bb338ee7 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedGraphRepositoryQuery.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedGraphRepositoryQuery.java @@ -13,7 +13,11 @@ package org.springframework.data.neo4j.repository.query.derived; -import java.util.*; +import java.util.EmptyStackException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import org.neo4j.ogm.cypher.Filters; import org.neo4j.ogm.cypher.query.Pagination; @@ -89,7 +93,7 @@ public class DerivedGraphRepositoryQuery implements RepositoryQuery { } return session.count(info.getJavaType(), filters); } else { - throw new RuntimeException("Long is required as the return type of a Count query"); + throw new RuntimeException("Long is required as the return type of a Count query"); } } @@ -175,11 +179,13 @@ public class DerivedGraphRepositoryQuery implements RepositoryQuery { return graphQueryMethod; } - private List queryResults(Class concreteType, int queryDepth, Filters params, PagingAndSorting pagingAndSorting) { + private List queryResults(Class concreteType, int queryDepth, Filters params, + PagingAndSorting pagingAndSorting) { List resultList; switch (pagingAndSorting.configuration()) { case PagingAndSorting.PAGING_AND_SORTING: - resultList = (List) session.loadAll(concreteType, params, pagingAndSorting.sortOrder, pagingAndSorting.pagination, queryDepth); + resultList = (List) session.loadAll(concreteType, params, pagingAndSorting.sortOrder, + pagingAndSorting.pagination, queryDepth); break; case PagingAndSorting.PAGING_ONLY: @@ -213,15 +219,14 @@ public class DerivedGraphRepositoryQuery implements RepositoryQuery { } } - @Override public QueryMethod getQueryMethod() { return graphQueryMethod; } - /** - * Sets values from parameters supplied by the finder on {@link org.neo4j.ogm.cypher.Filter} built by the {@link GraphQueryMethod} + * Sets values from parameters supplied by the finder on {@link org.neo4j.ogm.cypher.Filter} built by the + * {@link GraphQueryMethod} * * @param parameters parameter values supplied by the finder method * @return List of Parameter with values set @@ -239,22 +244,19 @@ public class DerivedGraphRepositoryQuery implements RepositoryQuery { return new Filters(queryDefinition.getFilters(params)); } - - protected Object createPage(GraphQueryMethod graphQueryMethod, List resultList, Pageable pageable) { if (pageable == null) { return graphQueryMethod.isPageQuery() ? new PageImpl(resultList) : new SliceImpl(resultList); } - int currentTotal = pageable.getOffset() + resultList.size() + - (resultList.size() == pageable.getPageSize() ? pageable.getPageSize() : 0); + int currentTotal = pageable.getOffset() + resultList.size() + + (resultList.size() == pageable.getPageSize() ? pageable.getPageSize() : 0); int resultWindowSize = Math.min(resultList.size(), pageable.getPageSize()); boolean hasNext = resultWindowSize < resultList.size(); List resultListPage = resultList.subList(0, resultWindowSize); - return graphQueryMethod.isPageQuery() ? - new PageImpl(resultListPage, pageable, currentTotal) : - new SliceImpl(resultListPage, pageable, hasNext); + return graphQueryMethod.isPageQuery() ? new PageImpl(resultListPage, pageable, currentTotal) + : new SliceImpl(resultListPage, pageable, hasNext); } private SortOrder convert(Sort sort) { @@ -290,7 +292,9 @@ public class DerivedGraphRepositoryQuery implements RepositoryQuery { if (graphQueryMethod.isPageQuery() || graphQueryMethod.isSliceQuery()) { if (graphQueryMethod.isSliceQuery()) { pagination = new Pagination(pageable.getPageNumber(), pageable.getPageSize() + 1); - pagination.setOffset(pageable.getPageNumber() * pageable.getPageSize()); //For a slice, need one extra result to determine if there is a next page + pagination.setOffset(pageable.getPageNumber() * pageable.getPageSize()); // For a slice, need one extra result + // to determine if there is a next + // page } else { pagination = new Pagination(pageable.getPageNumber(), pageable.getPageSize()); } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryBuilder.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryBuilder.java index fc9709fd4..5cb3210d6 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryBuilder.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryBuilder.java @@ -31,6 +31,7 @@ public class DerivedQueryBuilder { /** * Add a part as a parameter to the graph query. + * * @param part the Part to be added * @param booleanOperator the {@link BooleanOperator} to be used when appending the parameter to the query. */ @@ -40,6 +41,7 @@ public class DerivedQueryBuilder { /** * Add criteria from an intermediate builder to the query + * * @param fromBuilder the intermediate builder * @param booleanOperator the {@link BooleanOperator} to be used when appending the criteria to the query */ @@ -49,6 +51,7 @@ public class DerivedQueryBuilder { /** * Builds the final query + * * @return the final query */ public DerivedQueryDefinition buildQuery() { diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryCreator.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryCreator.java index 2b845278d..8d30c549c 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryCreator.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryCreator.java @@ -11,17 +11,16 @@ * */ - package org.springframework.data.neo4j.repository.query.derived; +import java.util.Iterator; + import org.neo4j.ogm.cypher.BooleanOperator; import org.springframework.data.domain.Sort; import org.springframework.data.repository.query.parser.AbstractQueryCreator; import org.springframework.data.repository.query.parser.Part; import org.springframework.data.repository.query.parser.PartTree; -import java.util.Iterator; - /** * An {@link AbstractQueryCreator} that builds a graph query. * diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryDefinition.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryDefinition.java index 4b19a7473..efd7670f7 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryDefinition.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/DerivedQueryDefinition.java @@ -21,9 +21,8 @@ import org.neo4j.ogm.cypher.Filter; import org.springframework.data.repository.query.parser.Part; /** - * The graph query created based on a derived query. + * The graph query created based on a derived query. /** * -/** * @author Luanne Misquitta * @author Nicolas Mervaillie */ @@ -31,19 +30,22 @@ public interface DerivedQueryDefinition { /** * Add a part as a parameter to the graph query. - * @param part the Part to be added + * + * @param part the Part to be added * @param booleanOperator the {@link BooleanOperator} to be used when appending the parameter to the query. */ void addPart(Part part, BooleanOperator booleanOperator); /** * Get the base part i.e. the first parameter of the graph query. + * * @return Part representing the base of the query. */ Part getBasePart(); /** * Gets all cypher filters for this query + * * @return The OGM filters with bound parameter values */ List getFilters(Map params); diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/BooleanComparisonBuilder.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/BooleanComparisonBuilder.java index ecce4e895..1666f8f68 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/BooleanComparisonBuilder.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/BooleanComparisonBuilder.java @@ -11,7 +11,6 @@ * */ - package org.springframework.data.neo4j.repository.query.derived.builder; import static org.springframework.data.repository.query.parser.Part.Type.*; diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/DistanceComparisonBuilder.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/DistanceComparisonBuilder.java index a952ff6c5..b715ab8a1 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/DistanceComparisonBuilder.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/DistanceComparisonBuilder.java @@ -11,7 +11,6 @@ * */ - package org.springframework.data.neo4j.repository.query.derived.builder; import java.util.Collections; @@ -54,7 +53,8 @@ public class DistanceComparisonBuilder extends FilterBuilder { distance = (Distance) secondArg; point = (Point) firstArg; } else { - throw new IllegalArgumentException("findNear requires an argument of type Distance and an argument of type Point"); + throw new IllegalArgumentException( + "findNear requires an argument of type Distance and an argument of type Point"); } double meters; @@ -66,7 +66,8 @@ public class DistanceComparisonBuilder extends FilterBuilder { meters = distance.getValue(); } - DistanceFromPoint distanceFromPoint = new DistanceFromPoint(point.getX(), point.getY(), distance.getValue() * meters); + DistanceFromPoint distanceFromPoint = new DistanceFromPoint(point.getX(), point.getY(), + distance.getValue() * meters); DistanceComparison distanceComparison = new DistanceComparison(distanceFromPoint); Filter filter = new Filter(); diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/ExistsFilterBuilder.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/ExistsFilterBuilder.java index 0f1b1bf6e..ee97578f3 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/ExistsFilterBuilder.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/ExistsFilterBuilder.java @@ -1,6 +1,5 @@ package org.springframework.data.neo4j.repository.query.derived.builder; - import java.util.Collections; import java.util.List; import java.util.Stack; diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/IsNullFilterBuilder.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/IsNullFilterBuilder.java index 8e11ccc7b..8f138443f 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/IsNullFilterBuilder.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/IsNullFilterBuilder.java @@ -11,7 +11,6 @@ * */ - package org.springframework.data.neo4j.repository.query.derived.builder; import static org.springframework.data.repository.query.parser.Part.Type.*; @@ -31,21 +30,21 @@ import org.springframework.data.repository.query.parser.Part; */ public class IsNullFilterBuilder extends FilterBuilder { - public IsNullFilterBuilder(Part part, BooleanOperator booleanOperator, Class entityType) { - super(part, booleanOperator, entityType); - } + public IsNullFilterBuilder(Part part, BooleanOperator booleanOperator, Class entityType) { + super(part, booleanOperator, entityType); + } - @Override - public List build(Stack params) { - Filter filter = new Filter(); - filter.setPropertyName(propertyName()); - filter.setOwnerEntityType(entityType); - filter.setBooleanOperator(booleanOperator); - filter.setNegated(isNegated() || part.getType() == IS_NOT_NULL); - filter.setComparisonOperator(ComparisonOperator.IS_NULL); - setNestedAttributes(part, filter); + @Override + public List build(Stack params) { + Filter filter = new Filter(); + filter.setPropertyName(propertyName()); + filter.setOwnerEntityType(entityType); + filter.setBooleanOperator(booleanOperator); + filter.setNegated(isNegated() || part.getType() == IS_NOT_NULL); + filter.setComparisonOperator(ComparisonOperator.IS_NULL); + setNestedAttributes(part, filter); - return Collections.singletonList(filter); - } + return Collections.singletonList(filter); + } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/PropertyComparisonBuilder.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/PropertyComparisonBuilder.java index 55f3b831a..1fd36f31a 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/PropertyComparisonBuilder.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/query/derived/builder/PropertyComparisonBuilder.java @@ -47,7 +47,6 @@ public class PropertyComparisonBuilder extends FilterBuilder { return Collections.singletonList(filter); } - private ComparisonOperator convertToComparisonOperator(Part.Type type) { switch (type) { case AFTER: diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/GraphEntityInformation.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/GraphEntityInformation.java index ef4aa4b2e..42b817ca7 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/GraphEntityInformation.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/GraphEntityInformation.java @@ -13,47 +13,47 @@ package org.springframework.data.neo4j.repository.support; +import java.io.Serializable; + import org.neo4j.ogm.MetaData; import org.neo4j.ogm.entity.io.EntityAccessManager; import org.neo4j.ogm.metadata.ClassInfo; import org.neo4j.ogm.metadata.FieldInfo; import org.springframework.data.repository.core.support.AbstractEntityInformation; -import java.io.Serializable; - /** * @author Mark Angrish */ public class GraphEntityInformation extends AbstractEntityInformation { - private final MetaData metaData; + private final MetaData metaData; - public GraphEntityInformation(MetaData metaData, Class type) { - super(type); - this.metaData = metaData; - } + public GraphEntityInformation(MetaData metaData, Class type) { + super(type); + this.metaData = metaData; + } - @Override - public ID getId(T entity) { - final ClassInfo classInfo = metaData.classInfo(getJavaType().getName()); - final FieldInfo primaryIndex = classInfo.primaryIndexField(); + @Override + public ID getId(T entity) { + final ClassInfo classInfo = metaData.classInfo(getJavaType().getName()); + final FieldInfo primaryIndex = classInfo.primaryIndexField(); - if (primaryIndex != null) { - return (ID) EntityAccessManager.getPropertyReader(classInfo, primaryIndex.getName()).readProperty(entity); - } - else { - return (ID) EntityAccessManager.getPropertyReader(classInfo, classInfo.identityField().getName()).readProperty(entity); - } - } + if (primaryIndex != null) { + return (ID) EntityAccessManager.getPropertyReader(classInfo, primaryIndex.getName()).readProperty(entity); + } else { + return (ID) EntityAccessManager.getPropertyReader(classInfo, classInfo.identityField().getName()) + .readProperty(entity); + } + } - @Override - public Class getIdType() { - final FieldInfo primaryIndex = metaData.classInfo(getJavaType().getName()).primaryIndexField(); + @Override + public Class getIdType() { + final FieldInfo primaryIndex = metaData.classInfo(getJavaType().getName()).primaryIndexField(); - if (primaryIndex != null) { - return (Class) primaryIndex.convertedType(); - } - return (Class) Long.class; - } + if (primaryIndex != null) { + return (Class) primaryIndex.convertedType(); + } + return (Class) Long.class; + } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jPersistenceExceptionTranslator.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jPersistenceExceptionTranslator.java index 25a255ce0..c7cd30a4f 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jPersistenceExceptionTranslator.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jPersistenceExceptionTranslator.java @@ -24,9 +24,9 @@ import org.springframework.data.neo4j.transaction.SessionFactoryUtils; */ public class Neo4jPersistenceExceptionTranslator implements PersistenceExceptionTranslator { - @Override - public DataAccessException translateExceptionIfPossible(RuntimeException ex) { - return SessionFactoryUtils.convertOgmAccessException(ex); - } + @Override + public DataAccessException translateExceptionIfPossible(RuntimeException ex) { + return SessionFactoryUtils.convertOgmAccessException(ex); + } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactory.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactory.java index 8d3c543b1..3aec4624e 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactory.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactory.java @@ -56,7 +56,7 @@ public class Neo4jRepositoryFactory extends RepositoryFactorySupport { public EntityInformation getEntityInformation(Class type) { Assert.notNull(type, "Domain class must not be null!"); Assert.notNull(session, "Session must not be null!"); - return new GraphEntityInformation(((Neo4jSession)session).metaData(), type); + return new GraphEntityInformation(((Neo4jSession) session).metaData(), type); } @Override @@ -71,7 +71,7 @@ public class Neo4jRepositoryFactory extends RepositoryFactorySupport { @Override protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key, - EvaluationContextProvider evaluationContextProvider) { + EvaluationContextProvider evaluationContextProvider) { return new GraphQueryLookupStrategy(session); } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactoryBean.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactoryBean.java index d1f7a5b14..dbd9232c0 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactoryBean.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactoryBean.java @@ -23,7 +23,6 @@ import org.springframework.data.repository.core.support.RepositoryFactorySupport import org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport; import org.springframework.util.Assert; - /** * Special adapter for Springs {@link org.springframework.beans.factory.FactoryBean} interface to allow easy setup of * repository factories via Spring configuration. @@ -33,13 +32,14 @@ import org.springframework.util.Assert; * @author Luanne Misquitta * @author Mark Angrish */ -public class Neo4jRepositoryFactoryBean, S, ID extends Serializable> extends TransactionalRepositoryFactoryBeanSupport { +public class Neo4jRepositoryFactoryBean, S, ID extends Serializable> + extends TransactionalRepositoryFactoryBeanSupport { private Session session; - + /** * Creates a new {@link Neo4jRepositoryFactoryBean} for the given repository interface. - * + * * @param repositoryInterface must not be {@literal null}. */ public Neo4jRepositoryFactoryBean(Class repositoryInterface) { @@ -81,5 +81,3 @@ public class Neo4jRepositoryFactoryBean, S, ID exten return new Neo4jRepositoryFactory(session); } } - - diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/SimpleNeo4jRepository.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/SimpleNeo4jRepository.java index e75833435..ec4a8ae85 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/SimpleNeo4jRepository.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/repository/support/SimpleNeo4jRepository.java @@ -18,10 +18,8 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.neo4j.ogm.MetaData; import org.neo4j.ogm.cypher.query.Pagination; import org.neo4j.ogm.cypher.query.SortOrder; -import org.neo4j.ogm.session.Neo4jSession; import org.neo4j.ogm.session.Session; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; @@ -37,7 +35,6 @@ import org.springframework.util.Assert; * you a more sophisticated interface than the plain {@link Session} . * * @param the type of the entity to handle - * * @author Vince Bickers * @author Luanne Misquitta * @author Mark Angrish @@ -199,7 +196,8 @@ public class SimpleNeo4jRepository implements Neo4jR @Override public Page findAll(Pageable pageable, int depth) { - Collection data = session.loadAll(clazz, convert(pageable.getSort()), new Pagination(pageable.getPageNumber(), pageable.getPageSize()), depth); + Collection data = session.loadAll(clazz, convert(pageable.getSort()), + new Pagination(pageable.getPageNumber(), pageable.getPageSize()), depth); return updatePage(pageable, new ArrayList(data)); } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jCallback.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jCallback.java index 10efeb7a6..0fd155b42 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jCallback.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jCallback.java @@ -15,10 +15,9 @@ package org.springframework.data.neo4j.template; import org.neo4j.ogm.session.Session; /** - * Callback interface for Neo4j OGM code. To be used with {@link Neo4jTemplate}'s - * execution methods, often as anonymous classes within a method implementation. - * A typical implementation will call {@code Session.load/find/update} to perform - * some operations on persistent objects. + * Callback interface for Neo4j OGM code. To be used with {@link Neo4jTemplate}'s execution methods, often as anonymous + * classes within a method implementation. A typical implementation will call {@code Session.load/find/update} to + * perform some operations on persistent objects. * * @author Juergen Hoeller * @see Neo4jTemplate @@ -29,13 +28,12 @@ import org.neo4j.ogm.session.Session; public interface Neo4jCallback { /** - * Gets called by {@code Neo4jTemplate.doExecute} with an active - * OGM {@code Session}. Does not need to care about activating - * or closing the {@code Session}, or handling transactions. - *

    Allows for returning a result object created within the callback, - * i.e. a domain object or a collection of domain objects. - * A thrown custom RuntimeException is treated as an application exception: - * It gets propagated to the caller of the template. + * Gets called by {@code Neo4jTemplate.doExecute} with an active OGM {@code Session}. Does not need to care about + * activating or closing the {@code Session}, or handling transactions. + *

    + * Allows for returning a result object created within the callback, i.e. a domain object or a collection of domain + * objects. A thrown custom RuntimeException is treated as an application exception: It gets propagated to the caller + * of the template. * * @param session active Neo4j session * @return a result object, or {@code null} if none diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jOperations.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jOperations.java index f60bf924b..dcb1ff4ab 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jOperations.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jOperations.java @@ -13,6 +13,8 @@ package org.springframework.data.neo4j.template; +import java.util.Collection; +import java.util.Map; import org.neo4j.ogm.cypher.Filter; import org.neo4j.ogm.cypher.Filters; @@ -26,416 +28,427 @@ import org.neo4j.ogm.session.Session; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Repository; -import java.util.Collection; -import java.util.Map; - /** - * Spring Data operations interface, implemented by {@link Neo4jTemplate}, that provides the API for using - * the persistence framework in a more direct way as an alternative to the repositories. + * Spring Data operations interface, implemented by {@link Neo4jTemplate}, that provides the API for using the + * persistence framework in a more direct way as an alternative to the repositories. * * @author Adam George * @author Luanne Misquitta * @author Mark Angrish - * * @deprecated Use {@link org.neo4j.ogm.session.Session} */ @Repository @Deprecated public interface Neo4jOperations { - /** - * Execute the action specified by the given action object within a - * {@link Session}. - *

    Application exceptions thrown by the action object get propagated - * to the caller (can only be unchecked). OGM exceptions are - * transformed into appropriate DAO ones. Allows for returning a result - * object, that is a domain object or a collection of domain objects. - *

    Note: Callback code is not supposed to handle transactions itself! - * Use an appropriate transaction manager like - * {@link org.springframework.data.neo4j.transaction.Neo4jTransactionManager}. Generally, callback code must not - * touch any {@code Session} lifecycle methods, like close, - * disconnect, or reconnect, to let the template do its work. - * @param action callback object that specifies the OGM action - * @return a result object returned by the action, or {@code null} - * @see Session - */ - T execute(Neo4jCallback action) throws DataAccessException; - - /** - * Loads an entity of type T that matches the specified ID to the default depth. - * - * @param type The type of entity to load - * @param id The ID of the node or relationship to match - * @return The instance of T loaded from the database that matches the specified ID or null if no match is found - */ - T load(Class type, Long id); - - /** - * Loads an entity of type T that matches the specified ID to the given depth. - * - * @param type The type of entity to load - * @param id The ID of the node or relationship to match - * @param depth The maximum number of relationships away from the identified object to follow when loading related entities. - * A value of 0 just loads the object's properties and no related entities. A value of -1 implies no depth limit. - * @return The instance of T loaded from the database that matches the specified ID or null if no match is found - */ - T load(Class type, Long id, int depth); - - /** - * Retrieves all the entities of the given class in the database hydrated to the default depth. - * - * @param type The type of entity to return. - * @return A {@link Collection} containing all instances of the given type in the database or an empty collection if none - * are found, never null - */ - Collection loadAll(Class type); - - /** - * Retrieves all the entities of the given class in the database hydrated to the specified depth. - * - * @param type The type of entity to return. - * @param depth The maximum number of relationships away from each loaded object to follow when loading related entities. - * A value of 0 just loads the object's properties and no related entities. A value of -1 implies no depth limit. - * @return A {@link Collection} containing all instances of the given type in the database or an empty collection if none - * are found, never null - */ - Collection loadAll(Class type, int depth); - - /** - * Retrieves all the entities of the given class in the database hydrated to the specified depth, with Sorting. - * - * @param type The type of entity to return. - * @param sortOrder The SortOrder to be applied - * @param depth The maximum number of relationships away from each loaded object to follow when loading related entities. - * A value of 0 just loads the object's properties and no related entities. A value of -1 implies no depth limit. - * @return A {@link Collection} containing all instances of the given type in the database or an empty collection if none - * are found, never null - */ - Collection loadAll(Class type, SortOrder sortOrder, int depth); - - /** - * Retrieves all the entities of the given class in the database hydrated to the specified depth, with Sorting and Pagination. - * - * @param type The type of entity to return. - * @param sortOrder The SortOrder to be applied - * @param pagination The Pagination to be applied - * @param depth The maximum number of relationships away from each loaded object to follow when loading related entities. - * A value of 0 just loads the object's properties and no related entities. A value of -1 implies no depth limit. - * @return A {@link Collection} containing all instances of the given type in the database or an empty collection if none - * are found, never null - */ - Collection loadAll(Class type, SortOrder sortOrder, Pagination pagination, int depth); - - - /** - * Reloads all of the entities which match IDs in the given {@link Collection} to the specified depth. Of course, this will - * only work for persistent objects (i.e., those with a non-null @GraphId field). - * - * @param type The type of entity to return. - * @param ids The IDs of objects to re-hydrate - * @param depth The depth to which the objects should be hydrated - * @return A new {@link Collection} of entities matching those in the given collection hydrated to the given depth - */ - Collection loadAll(Class type, Collection ids, int depth); - - /** - * Reloads all of the entities in the given {@link Collection} to the specified depth. Of course, this will - * only work for persistent objects (i.e., those with a non-null @GraphId field). - * - * @param objects The objects to re-hydrate - * @param depth The depth to which the objects should be hydrated - * @return A new {@link Collection} of entities matching those in the given collection hydrated to the given depth - */ - Collection loadAll(Collection objects, int depth); - - /** - * Reloads all of the entities in the given {@link Collection} to the specified depth, sorted by the sprcified SortOrder Of course, this will - * only work for persistent objects (i.e., those with a non-null @GraphId field). - * - * @param ids The IDs of objects to re-hydrate - * @param sortOrder The SortOrder to be used - * @param depth The depth to which the objects should be hydrated - * @return A new {@link Collection} of entities matching those in the given collection hydrated to the given depth - */ - Collection loadAll(Class type, Collection ids, SortOrder sortOrder, int depth); - - - /** - * Retrieves all the entities of the given class in the database hydrated to the default depth conforming to the specified - * filter criteria. - * - * @param type The type of entity to return. - * @param filter The filter to constrain entities with. - * @return A {@link Collection} containing all matching instances of the given type in the database or an empty collection if none - * are found, never null - */ - Collection loadAll(Class type, Filter filter); - - - /** - * Retrieves all the entities of the given class in the database hydrated to the specified depth, with Pagination. - * - * @param type The type of entity to return. - * @param pagination The Pagination to be applied - * @param depth The maximum number of relationships away from each loaded object to follow when loading related entities. - * A value of 0 just loads the object's properties and no related entities. A value of -1 implies no depth limit. - * @return A {@link Collection} containing all instances of the given type in the database or an empty collection if none - * are found, never null - */ - Collection loadAll(Class type, Pagination pagination, int depth); - - /** - * Retrieves all the entities of the given class in the database hydrated to the default depth conforming to the specified - * filter criteria. - * - * @param type The type of entity to return. - * @param filter The filter to constrain entities with. - * @param depth The depth to which the objects should be hydrated - * @return A {@link Collection} containing all matching instances of the given type in the database or an empty collection if none - * are found, never null - */ - Collection loadAll(Class type, Filter filter, int depth); - - - /** - * Retrieves the entity of the specified type that contains a property matching the given name with the given value. - * This method assumes that the requested property/value combination will be unique for all entities of this type in - * the database and will throw an exception unless exactly one result is found. If several entities are expected to - * be returned then use {@link #loadAllByProperty(Class, String, Object)} instead. - * - * @param type The type of entity to load - * @param propertyName The name of the property on the entity against which to match the given value - * @param propertyValue The value of the named property against which to match entities - * @return The instance of T corresponding to the entity that matches the given property, never null - * @throws NotFoundException if there are no matching entities - * @throws IllegalStateException if there's more than one matching entity - */ - T loadByProperty(Class type, String propertyName, Object propertyValue); - - /** - * Retrieves the entity of the specified type that contains a property matching the given name with the given value. - * This method assumes that the requested property/value combination will be unique for all entities of this type in - * the database and will throw an exception unless exactly one result is found. If several entities are expected to - * be returned then use {@link #loadAllByProperty(Class, String, Object)} instead. - * - * @param type The type of entity to load - * @param propertyName The name of the property on the entity against which to match the given value - * @param propertyValue The value of the named property against which to match entities - * @param depth The maximum number of relationships away from each loaded object to follow when loading related entities. - * A value of 0 just loads the object's properties and no related entities. A value of -1 implies no depth limit. - * @return The instance of T corresponding to the entity that matches the given property, never null - * @throws NotFoundException if there are no matching entities - * @throws IllegalStateException if there's more than one matching entity - */ - T loadByProperty(Class type, String propertyName, Object propertyValue, int depth); - - /** - * Retrieves all the entities of the specified type that contain a property matching the given name with the given value. - * - * @param type The type of entity to load - * @param propertyName The name of the property on the entity against which to match the given value - * @param propertyValue The value of the named property against which to match entities - * @return A {@link Collection} containing all the entities that match the given property or an empty {@link Collection} if - * there aren't any matches, never null - */ - Collection loadAllByProperty(Class type, String propertyName, Object propertyValue); - - /** - * Retrieves all the entities of the specified type that contain a property matching the given name with the given value. - * - * @param type The type of entity to load - * @param propertyName The name of the property on the entity against which to match the given value - * @param propertyValue The value of the named property against which to match entities - * @param depth The maximum number of relationships away from each loaded object to follow when loading related entities. - * A value of 0 just loads the object's properties and no related entities. A value of -1 implies no depth limit. - * @return A {@link Collection} containing all the entities that match the given property or an empty {@link Collection} if - * there aren't any matches, never null - */ - Collection loadAllByProperty(Class type, String propertyName, Object propertyValue, int depth); - - /** - * Retrieves the entity of the specified type that contains properties matching the ones supplied with given name and value. - * This method assumes that the requested property/value combinations will be unique for all entities of this type in - * the database and will throw an exception unless exactly one result is found. If several entities are expected to - * be returned then use {@link #loadAllByProperty(Class, String, Object)} instead. - * - * @param type The type of entity to load - * @param parameters The parameters to filter by - * @return The instance of T corresponding to the entity that matches the given properties, never null - * @throws NotFoundException if there are no matching entities - * @throws IllegalStateException if there's more than one matching entity - */ - T loadByProperties(Class type, Filters parameters); - - /** - * Retrieves the entity of the specified type that contains properties matching the ones supplied with given name and value. - * This method assumes that the requested property/value combinations will be unique for all entities of this type in - * the database and will throw an exception unless exactly one result is found. If several entities are expected to - * be returned then use {@link #loadAllByProperty(Class, String, Object)} instead. - * - * @param type The type of entity to load - * @param parameters The parameters to filter by - * @param depth The maximum number of relationships away from each loaded object to follow when loading related entities. - * A value of 0 just loads the object's properties and no related entities. A value of -1 implies no depth limit. - * @return The instance of T corresponding to the entity that matches the given properties, never null - * @throws NotFoundException if there are no matching entities - * @throws IllegalStateException if there's more than one matching entity - */ - T loadByProperties(Class type, Filters parameters, int depth); - - /** - * Retrieves all the entities of the specified type that contain a properties matching the ones supplied with given name and value. - * - * @param type The type of entity to load - * @param parameters The parameters to filter by - * @return A {@link Collection} containing all the entities that match the given properties or an empty {@link Collection} if - * there aren't any matches, never null - */ - Collection loadAllByProperties(Class type, Filters parameters); - - /** - * Retrieves all the entities of the specified type that contain a properties matching the ones supplied with given name and value. - * - * @param type The type of entity to load - * @param parameters The parameters to filter by - * @param depth The maximum number of relationships away from each loaded object to follow when loading related entities. - * A value of 0 just loads the object's properties and no related entities. A value of -1 implies no depth limit. - * @return A {@link Collection} containing all the entities that match the given properties or an empty {@link Collection} if - * there aren't any matches, never null - */ - Collection loadAllByProperties(Class type, Filters parameters, int depth); - - /** - * Saves the specified entity in the graph database. If the entity is currently transient then the persistent version of - * the entity will be returned, containing its new graph ID. - * - * @param entity The entity to save - * @return The saved entity - */ - T save(T entity); - - /** - * Saves the specified entity in the graph database to a custom depth. If the entity is currently transient then the persistent version of - * the entity will be returned, containing its new graph ID. - * - * @param entity The entity to save - * @param depth The maximum number of relationships away from the entity to follow when saving related entities. - * A value of 0 just saves the object's properties and no related entities. A value of -1 implies no depth limit. - * @return The saved entity - */ - T save(T entity, int depth); - - - /** - * Removes the given node or relationship entity from the graph. The entity is first removed - * from all indexes and then deleted. - * - * @param entity The entity to delete - */ - void delete(Object entity); + /** + * Execute the action specified by the given action object within a {@link Session}. + *

    + * Application exceptions thrown by the action object get propagated to the caller (can only be unchecked). OGM + * exceptions are transformed into appropriate DAO ones. Allows for returning a result object, that is a domain object + * or a collection of domain objects. + *

    + * Note: Callback code is not supposed to handle transactions itself! Use an appropriate transaction manager like + * {@link org.springframework.data.neo4j.transaction.Neo4jTransactionManager}. Generally, callback code must not touch + * any {@code Session} lifecycle methods, like close, disconnect, or reconnect, to let the template do its work. + * + * @param action callback object that specifies the OGM action + * @return a result object returned by the action, or {@code null} + * @see Session + */ + T execute(Neo4jCallback action) throws DataAccessException; /** - * Removes all nodes or relationship entities of a specific type from the graph. - * @param type the type of entity to delete - */ - void deleteAll(Class type); + * Loads an entity of type T that matches the specified ID to the default depth. + * + * @param type The type of entity to load + * @param id The ID of the node or relationship to match + * @return The instance of T loaded from the database that matches the specified ID or null if no match + * is found + */ + T load(Class type, Long id); - /** - * Removes all mapping information from the current session - */ - void clear(); + /** + * Loads an entity of type T that matches the specified ID to the given depth. + * + * @param type The type of entity to load + * @param id The ID of the node or relationship to match + * @param depth The maximum number of relationships away from the identified object to follow when loading related + * entities. A value of 0 just loads the object's properties and no related entities. A value of -1 implies + * no depth limit. + * @return The instance of T loaded from the database that matches the specified ID or null if no match + * is found + */ + T load(Class type, Long id, int depth); - /** - * Executes the specified Cypher query with the given parameters against the underlying Neo4j database and returns the - * row-based result in the form of an {@link Iterable} of {@link Map}s. - *

    - * Each of the resultant maps corresponds to a "row" in the result set and the key set in each map contains all the names - * contained in the RETURN clause of the given query. - *

    - * - * @param cypherQuery The Cypher query to execute - * @param params The parameter to merge into the cypher query or an empty {@link Map} if the given query isn't parameterised - * @return A {@link Query} containing an {@link Iterable} map representing query results and {@link QueryStatistics} if applicable. - * @throws RuntimeException if the given query is not a valid Cypherquery - */ - Result query(String cypherQuery, Map params); + /** + * Retrieves all the entities of the given class in the database hydrated to the default depth. + * + * @param type The type of entity to return. + * @return A {@link Collection} containing all instances of the given type in the database or an empty collection if + * none are found, never null + */ + Collection loadAll(Class type); - /** - * Runs the specified Cypher query with the given parameters against the underlying Neo4j database and returns the result - * marshalled as an object of the requested type. - * - * @param entityType The {@link Class} denoting the type of entity to return - * @param cypherQuery The Cypher query to execute - * @param parameters The parameter to merge into the Cypher query or an empty {@link Map} if the query's not parameterised - * @return An instance of T that corresponds to the entity found by executing the query or null if nothing is - * found by the query - * @throws RuntimeException If more than one result is returned or there's an issue executing the query - */ - T queryForObject(Class entityType, String cypherQuery, Map parameters); + /** + * Retrieves all the entities of the given class in the database hydrated to the specified depth. + * + * @param type The type of entity to return. + * @param depth The maximum number of relationships away from each loaded object to follow when loading related + * entities. A value of 0 just loads the object's properties and no related entities. A value of -1 implies + * no depth limit. + * @return A {@link Collection} containing all instances of the given type in the database or an empty collection if + * none are found, never null + */ + Collection loadAll(Class type, int depth); - /** - * Runs the specified Cypher query with the given parameters against the underlying Neo4j database and returns the result - * marshalled as a group of objects of the requested type. - * - * @param entityType The {@link Class} denoting the type of entity to return - * @param cypherQuery The Cypher query to execute - * @param parameters The parameter to merge into the Cypher query or an empty {@link Map} if the query's not parameterised - * @return An {@link Iterable} over the entities found by executing the query or an empty Iterable if nothing - * is found by the query, never null - * @throws RuntimeException If there's an issue executing the query - */ - Iterable queryForObjects(Class entityType, String cypherQuery, Map parameters); + /** + * Retrieves all the entities of the given class in the database hydrated to the specified depth, with Sorting. + * + * @param type The type of entity to return. + * @param sortOrder The SortOrder to be applied + * @param depth The maximum number of relationships away from each loaded object to follow when loading related + * entities. A value of 0 just loads the object's properties and no related entities. A value of -1 implies + * no depth limit. + * @return A {@link Collection} containing all instances of the given type in the database or an empty collection if + * none are found, never null + */ + Collection loadAll(Class type, SortOrder sortOrder, int depth); - /** - * Given a cypher statement this method will return a {@link Query} object containing a collection of Map's which represent Neo4j - * objects as properties, along with query statistics if applicable. - * - * Each element of the query result is a map which you can access by the name of the returned field - * - * TODO: Are we going to use the neo4jOperations conversion method to cast the value object to its proper class? - * - * @param cypher The parametrisable cypher to execute. - * @param parameters Any parameters to attach to the cypher. - * @param readOnly true if the query is readOnly, false otherwise - * - * @return A {@link Query} of {@link Iterable}s with each entry representing a neo4j object's properties. - */ - Result query(String cypher, Map parameters, boolean readOnly); + /** + * Retrieves all the entities of the given class in the database hydrated to the specified depth, with Sorting and + * Pagination. + * + * @param type The type of entity to return. + * @param sortOrder The SortOrder to be applied + * @param pagination The Pagination to be applied + * @param depth The maximum number of relationships away from each loaded object to follow when loading related + * entities. A value of 0 just loads the object's properties and no related entities. A value of -1 implies + * no depth limit. + * @return A {@link Collection} containing all instances of the given type in the database or an empty collection if + * none are found, never null + */ + Collection loadAll(Class type, SortOrder sortOrder, Pagination pagination, int depth); - /** - * Provides the instance count for the given node entity type. This method is also provided by the - * corresponding repository. - * - * @param entityClass The {@link Class} representing the type of node entity to count - * @return The number of entities in the database of the given type - */ - long count(Class entityClass); + /** + * Reloads all of the entities which match IDs in the given {@link Collection} to the specified depth. Of course, this + * will only work for persistent objects (i.e., those with a non-null @GraphId field). + * + * @param type The type of entity to return. + * @param ids The IDs of objects to re-hydrate + * @param depth The depth to which the objects should be hydrated + * @return A new {@link Collection} of entities matching those in the given collection hydrated to the given depth + */ + Collection loadAll(Class type, Collection ids, int depth); + /** + * Reloads all of the entities in the given {@link Collection} to the specified depth. Of course, this will only work + * for persistent objects (i.e., those with a non-null @GraphId field). + * + * @param objects The objects to re-hydrate + * @param depth The depth to which the objects should be hydrated + * @return A new {@link Collection} of entities matching those in the given collection hydrated to the given depth + */ + Collection loadAll(Collection objects, int depth); -// /** -// * Issue a single Cypher update operation (such as a CREATE, MERGE or DELETE statement). -// * -// * @deprecated Use {@link Neo4jOperations}.query() to return both results as well as query statistics. -// * @param cypherQuery The Cypher query to execute -// * @return {@link QueryStatistics} representing statistics about graph modifications as a result of the cypher execution. -// */ -// @Deprecated -// QueryStatistics execute(String cypherQuery); + /** + * Reloads all of the entities in the given {@link Collection} to the specified depth, sorted by the sprcified + * SortOrder Of course, this will only work for persistent objects (i.e., those with a non-null @GraphId + * field). + * + * @param ids The IDs of objects to re-hydrate + * @param sortOrder The SortOrder to be used + * @param depth The depth to which the objects should be hydrated + * @return A new {@link Collection} of entities matching those in the given collection hydrated to the given depth + */ + Collection loadAll(Class type, Collection ids, SortOrder sortOrder, int depth); -// /** -// * Allows a cypher statement with a modification statement to be executed. -// * -// *

    Parameters may be scalars or domain objects themselves.

    -// * @deprecated Use {@link Neo4jOperations}.query() to return both results as well as query statistics. -// * @param cypher The parametrisable cypher to execute. -// * @param parameters Any parameters to attach to the cypher. These may be domain objects or scalars. Note that -// * if a complex domain object is provided only the properties of that object will be set. -// * If relationships of a provided object also need to be set then the cypher should reflect this -// * and further domain object parameters provided. -// * -// * @return {@link QueryStatistics} representing statistics about graph modifications as a result of the cypher execution. -// */ -// @Deprecated -// QueryStatistics execute(String cypher, Map parameters); + /** + * Retrieves all the entities of the given class in the database hydrated to the default depth conforming to the + * specified filter criteria. + * + * @param type The type of entity to return. + * @param filter The filter to constrain entities with. + * @return A {@link Collection} containing all matching instances of the given type in the database or an empty + * collection if none are found, never null + */ + Collection loadAll(Class type, Filter filter); + + /** + * Retrieves all the entities of the given class in the database hydrated to the specified depth, with Pagination. + * + * @param type The type of entity to return. + * @param pagination The Pagination to be applied + * @param depth The maximum number of relationships away from each loaded object to follow when loading related + * entities. A value of 0 just loads the object's properties and no related entities. A value of -1 implies + * no depth limit. + * @return A {@link Collection} containing all instances of the given type in the database or an empty collection if + * none are found, never null + */ + Collection loadAll(Class type, Pagination pagination, int depth); + + /** + * Retrieves all the entities of the given class in the database hydrated to the default depth conforming to the + * specified filter criteria. + * + * @param type The type of entity to return. + * @param filter The filter to constrain entities with. + * @param depth The depth to which the objects should be hydrated + * @return A {@link Collection} containing all matching instances of the given type in the database or an empty + * collection if none are found, never null + */ + Collection loadAll(Class type, Filter filter, int depth); + + /** + * Retrieves the entity of the specified type that contains a property matching the given name with the given value. + * This method assumes that the requested property/value combination will be unique for all entities of this type in + * the database and will throw an exception unless exactly one result is found. If several entities are expected to be + * returned then use {@link #loadAllByProperty(Class, String, Object)} instead. + * + * @param type The type of entity to load + * @param propertyName The name of the property on the entity against which to match the given value + * @param propertyValue The value of the named property against which to match entities + * @return The instance of T corresponding to the entity that matches the given property, never null + * @throws NotFoundException if there are no matching entities + * @throws IllegalStateException if there's more than one matching entity + */ + T loadByProperty(Class type, String propertyName, Object propertyValue); + + /** + * Retrieves the entity of the specified type that contains a property matching the given name with the given value. + * This method assumes that the requested property/value combination will be unique for all entities of this type in + * the database and will throw an exception unless exactly one result is found. If several entities are expected to be + * returned then use {@link #loadAllByProperty(Class, String, Object)} instead. + * + * @param type The type of entity to load + * @param propertyName The name of the property on the entity against which to match the given value + * @param propertyValue The value of the named property against which to match entities + * @param depth The maximum number of relationships away from each loaded object to follow when loading related + * entities. A value of 0 just loads the object's properties and no related entities. A value of -1 implies + * no depth limit. + * @return The instance of T corresponding to the entity that matches the given property, never null + * @throws NotFoundException if there are no matching entities + * @throws IllegalStateException if there's more than one matching entity + */ + T loadByProperty(Class type, String propertyName, Object propertyValue, int depth); + + /** + * Retrieves all the entities of the specified type that contain a property matching the given name with the given + * value. + * + * @param type The type of entity to load + * @param propertyName The name of the property on the entity against which to match the given value + * @param propertyValue The value of the named property against which to match entities + * @return A {@link Collection} containing all the entities that match the given property or an empty + * {@link Collection} if there aren't any matches, never null + */ + Collection loadAllByProperty(Class type, String propertyName, Object propertyValue); + + /** + * Retrieves all the entities of the specified type that contain a property matching the given name with the given + * value. + * + * @param type The type of entity to load + * @param propertyName The name of the property on the entity against which to match the given value + * @param propertyValue The value of the named property against which to match entities + * @param depth The maximum number of relationships away from each loaded object to follow when loading related + * entities. A value of 0 just loads the object's properties and no related entities. A value of -1 implies + * no depth limit. + * @return A {@link Collection} containing all the entities that match the given property or an empty + * {@link Collection} if there aren't any matches, never null + */ + Collection loadAllByProperty(Class type, String propertyName, Object propertyValue, int depth); + + /** + * Retrieves the entity of the specified type that contains properties matching the ones supplied with given name and + * value. This method assumes that the requested property/value combinations will be unique for all entities of this + * type in the database and will throw an exception unless exactly one result is found. If several entities are + * expected to be returned then use {@link #loadAllByProperty(Class, String, Object)} instead. + * + * @param type The type of entity to load + * @param parameters The parameters to filter by + * @return The instance of T corresponding to the entity that matches the given properties, never null + * @throws NotFoundException if there are no matching entities + * @throws IllegalStateException if there's more than one matching entity + */ + T loadByProperties(Class type, Filters parameters); + + /** + * Retrieves the entity of the specified type that contains properties matching the ones supplied with given name and + * value. This method assumes that the requested property/value combinations will be unique for all entities of this + * type in the database and will throw an exception unless exactly one result is found. If several entities are + * expected to be returned then use {@link #loadAllByProperty(Class, String, Object)} instead. + * + * @param type The type of entity to load + * @param parameters The parameters to filter by + * @param depth The maximum number of relationships away from each loaded object to follow when loading related + * entities. A value of 0 just loads the object's properties and no related entities. A value of -1 implies + * no depth limit. + * @return The instance of T corresponding to the entity that matches the given properties, never null + * @throws NotFoundException if there are no matching entities + * @throws IllegalStateException if there's more than one matching entity + */ + T loadByProperties(Class type, Filters parameters, int depth); + + /** + * Retrieves all the entities of the specified type that contain a properties matching the ones supplied with given + * name and value. + * + * @param type The type of entity to load + * @param parameters The parameters to filter by + * @return A {@link Collection} containing all the entities that match the given properties or an empty + * {@link Collection} if there aren't any matches, never null + */ + Collection loadAllByProperties(Class type, Filters parameters); + + /** + * Retrieves all the entities of the specified type that contain a properties matching the ones supplied with given + * name and value. + * + * @param type The type of entity to load + * @param parameters The parameters to filter by + * @param depth The maximum number of relationships away from each loaded object to follow when loading related + * entities. A value of 0 just loads the object's properties and no related entities. A value of -1 implies + * no depth limit. + * @return A {@link Collection} containing all the entities that match the given properties or an empty + * {@link Collection} if there aren't any matches, never null + */ + Collection loadAllByProperties(Class type, Filters parameters, int depth); + + /** + * Saves the specified entity in the graph database. If the entity is currently transient then the persistent version + * of the entity will be returned, containing its new graph ID. + * + * @param entity The entity to save + * @return The saved entity + */ + T save(T entity); + + /** + * Saves the specified entity in the graph database to a custom depth. If the entity is currently transient then the + * persistent version of the entity will be returned, containing its new graph ID. + * + * @param entity The entity to save + * @param depth The maximum number of relationships away from the entity to follow when saving related entities. A + * value of 0 just saves the object's properties and no related entities. A value of -1 implies no depth + * limit. + * @return The saved entity + */ + T save(T entity, int depth); + + /** + * Removes the given node or relationship entity from the graph. The entity is first removed from all indexes and then + * deleted. + * + * @param entity The entity to delete + */ + void delete(Object entity); + + /** + * Removes all nodes or relationship entities of a specific type from the graph. + * + * @param type the type of entity to delete + */ + void deleteAll(Class type); + + /** + * Removes all mapping information from the current session + */ + void clear(); + + /** + * Executes the specified Cypher query with the given parameters against the underlying Neo4j database and returns the + * row-based result in the form of an {@link Iterable} of {@link Map}s. + *

    + * Each of the resultant maps corresponds to a "row" in the result set and the key set in each map contains all the + * names contained in the RETURN clause of the given query. + *

    + * + * @param cypherQuery The Cypher query to execute + * @param params The parameter to merge into the cypher query or an empty {@link Map} if the given query isn't + * parameterised + * @return A {@link Query} containing an {@link Iterable} map representing query results and {@link QueryStatistics} + * if applicable. + * @throws RuntimeException if the given query is not a valid Cypherquery + */ + Result query(String cypherQuery, Map params); + + /** + * Runs the specified Cypher query with the given parameters against the underlying Neo4j database and returns the + * result marshalled as an object of the requested type. + * + * @param entityType The {@link Class} denoting the type of entity to return + * @param cypherQuery The Cypher query to execute + * @param parameters The parameter to merge into the Cypher query or an empty {@link Map} if the query's not + * parameterised + * @return An instance of T that corresponds to the entity found by executing the query or null if + * nothing is found by the query + * @throws RuntimeException If more than one result is returned or there's an issue executing the query + */ + T queryForObject(Class entityType, String cypherQuery, Map parameters); + + /** + * Runs the specified Cypher query with the given parameters against the underlying Neo4j database and returns the + * result marshalled as a group of objects of the requested type. + * + * @param entityType The {@link Class} denoting the type of entity to return + * @param cypherQuery The Cypher query to execute + * @param parameters The parameter to merge into the Cypher query or an empty {@link Map} if the query's not + * parameterised + * @return An {@link Iterable} over the entities found by executing the query or an empty Iterable if + * nothing is found by the query, never null + * @throws RuntimeException If there's an issue executing the query + */ + Iterable queryForObjects(Class entityType, String cypherQuery, Map parameters); + + /** + * Given a cypher statement this method will return a {@link Query} object containing a collection of Map's which + * represent Neo4j objects as properties, along with query statistics if applicable. Each element of the query result + * is a map which you can access by the name of the returned field TODO: Are we going to use the neo4jOperations + * conversion method to cast the value object to its proper class? + * + * @param cypher The parametrisable cypher to execute. + * @param parameters Any parameters to attach to the cypher. + * @param readOnly true if the query is readOnly, false otherwise + * @return A {@link Query} of {@link Iterable}s with each entry representing a neo4j object's properties. + */ + Result query(String cypher, Map parameters, boolean readOnly); + + /** + * Provides the instance count for the given node entity type. This method is also provided by the + * corresponding repository. + * + * @param entityClass The {@link Class} representing the type of node entity to count + * @return The number of entities in the database of the given type + */ + long count(Class entityClass); + + // /** + // * Issue a single Cypher update operation (such as a CREATE, MERGE or DELETE statement). + // * + // * @deprecated Use {@link Neo4jOperations}.query() to return both results as well as query statistics. + // * @param cypherQuery The Cypher query to execute + // * @return {@link QueryStatistics} representing statistics about graph modifications as a result of the cypher + // execution. + // */ + // @Deprecated + // QueryStatistics execute(String cypherQuery); + + // /** + // * Allows a cypher statement with a modification statement to be executed. + // * + // *

    Parameters may be scalars or domain objects themselves.

    + // * @deprecated Use {@link Neo4jOperations}.query() to return both results as well as query statistics. + // * @param cypher The parametrisable cypher to execute. + // * @param parameters Any parameters to attach to the cypher. These may be domain objects or scalars. Note that + // * if a complex domain object is provided only the properties of that object will be set. + // * If relationships of a provided object also need to be set then the cypher should reflect this + // * and further domain object parameters provided. + // * + // * @return {@link QueryStatistics} representing statistics about graph modifications as a result of the cypher + // execution. + // */ + // @Deprecated + // QueryStatistics execute(String cypher, Map parameters); } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jTemplate.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jTemplate.java index 2fe804033..51b53d959 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jTemplate.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/template/Neo4jTemplate.java @@ -13,7 +13,6 @@ package org.springframework.data.neo4j.template; - import static org.springframework.data.neo4j.util.IterableUtils.*; import java.util.Collection; @@ -35,12 +34,12 @@ import org.springframework.data.neo4j.transaction.SessionFactoryUtils; import org.springframework.util.Assert; /** - * Spring Data template for Neo4j, which is an implementation of {@link Neo4jOperations}. Indeed, framework users are encouraged - * to favour coding against the {@link Neo4jOperations} interface rather than the {@link Neo4jTemplate} directly, as the - * interface API will be more consistent over time and enhanced proxy objects of the interface may actually be created by Spring - * for auto-wiring instead of this template. - * Please note also that all methods on this class throw a {@link DataAccessException} if any underlying {@code Exception} is - * thrown. Since {@link DataAccessException} is a runtime exception, this is not documented at the method level. + * Spring Data template for Neo4j, which is an implementation of {@link Neo4jOperations}. Indeed, framework users are + * encouraged to favour coding against the {@link Neo4jOperations} interface rather than the {@link Neo4jTemplate} + * directly, as the interface API will be more consistent over time and enhanced proxy objects of the interface may + * actually be created by Spring for auto-wiring instead of this template. Please note also that all methods on this + * class throw a {@link DataAccessException} if any underlying {@code Exception} is thrown. Since + * {@link DataAccessException} is a runtime exception, this is not documented at the method level. * * @author Adam George * @author Michal Bachman @@ -58,8 +57,7 @@ public class Neo4jTemplate implements Neo4jOperations, InitializingBean { /** * Create a new Neo4jTemplate instance. */ - public Neo4jTemplate() { - } + public Neo4jTemplate() {} /** * Constructs a new {@link Neo4jTemplate} based on the given Neo4j OGM {@link SessionFactory}. @@ -88,7 +86,6 @@ public class Neo4jTemplate implements Neo4jOperations, InitializingBean { } } - @Override public T execute(Neo4jCallback action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); @@ -185,7 +182,8 @@ public class Neo4jTemplate implements Neo4jOperations, InitializingBean { } @Override - public Collection loadAll(final Class type, final SortOrder sortOrder, final Pagination pagination, final int depth) { + public Collection loadAll(final Class type, final SortOrder sortOrder, final Pagination pagination, + final int depth) { return execute(new Neo4jCallback>() { @Override public Collection doInNeo4jOgm(Session session) { @@ -214,7 +212,8 @@ public class Neo4jTemplate implements Neo4jOperations, InitializingBean { } @Override - public Collection loadAll(final Class type, final Collection ids, final SortOrder sortOrder, final int depth) { + public Collection loadAll(final Class type, final Collection ids, final SortOrder sortOrder, + final int depth) { return execute(new Neo4jCallback>() { @Override public Collection doInNeo4jOgm(Session session) { @@ -264,7 +263,8 @@ public class Neo4jTemplate implements Neo4jOperations, InitializingBean { } @Override - public T loadByProperty(final Class type, final String propertyName, final Object propertyValue, final int depth) { + public T loadByProperty(final Class type, final String propertyName, final Object propertyValue, + final int depth) { return execute(new Neo4jCallback() { @Override public T doInNeo4jOgm(Session session) { @@ -312,7 +312,8 @@ public class Neo4jTemplate implements Neo4jOperations, InitializingBean { }); } - public Collection loadAllByProperty(final Class type, final String name, final Object value, final int depth) { + public Collection loadAllByProperty(final Class type, final String name, final Object value, + final int depth) { return execute(new Neo4jCallback>() { @Override public Collection doInNeo4jOgm(Session session) { @@ -353,7 +354,6 @@ public class Neo4jTemplate implements Neo4jOperations, InitializingBean { }); } - @Override public T save(final T entity) { return execute(new Neo4jCallback() { @@ -386,7 +386,8 @@ public class Neo4jTemplate implements Neo4jOperations, InitializingBean { } @Override - public Iterable queryForObjects(final Class objectType, final String cypher, final Map parameters) { + public Iterable queryForObjects(final Class objectType, final String cypher, + final Map parameters) { return execute(new Neo4jCallback>() { @Override public Iterable doInNeo4jOgm(Session session) { diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/Neo4jTransactionManager.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/Neo4jTransactionManager.java index 42aafc580..17ddf6f59 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/Neo4jTransactionManager.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/Neo4jTransactionManager.java @@ -13,7 +13,6 @@ package org.springframework.data.neo4j.transaction; - import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; import org.neo4j.ogm.transaction.Transaction; @@ -34,30 +33,29 @@ import org.springframework.transaction.support.ResourceTransactionManager; import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * {@link PlatformTransactionManager} implementation - * for a single Neo4j OGM {@link SessionFactory}. Binds a Neo4j OGM - * Session from the specified factory to the thread, potentially allowing for - * one thread-bound Session per factory. {@link SharedSessionCreator} - * is aware of thread-bound session and participates - * in such transactions automatically. It is required for Neo4j OGM access code - * supporting this transaction management mechanism. - *

    This transaction manager is appropriate for applications that use a single - * Neo4j OGM SessionFactory for transactional data access. JTA (usually through - * {@link org.springframework.transaction.jta.JtaTransactionManager}) has not been tested - * or considered at the moment. - *

    This transaction manager does not support nested transactions or - * requires new propagation. + * {@link PlatformTransactionManager} implementation for a single Neo4j OGM {@link SessionFactory}. Binds a Neo4j OGM + * Session from the specified factory to the thread, potentially allowing for one thread-bound Session per factory. + * {@link SharedSessionCreator} is aware of thread-bound session and participates in such transactions automatically. It + * is required for Neo4j OGM access code supporting this transaction management mechanism. + *

    + * This transaction manager is appropriate for applications that use a single Neo4j OGM SessionFactory for transactional + * data access. JTA (usually through {@link org.springframework.transaction.jta.JtaTransactionManager}) has not been + * tested or considered at the moment. + *

    + * This transaction manager does not support nested transactions or requires new propagation. * * @author Mark Angrish * @see #setSessionFactory */ -public class Neo4jTransactionManager extends AbstractPlatformTransactionManager implements ResourceTransactionManager, BeanFactoryAware, InitializingBean { +public class Neo4jTransactionManager extends AbstractPlatformTransactionManager + implements ResourceTransactionManager, BeanFactoryAware, InitializingBean { private SessionFactory sessionFactory; /** * Create a new Neo4jTransactionManager instance. - *

    An SessionFactory has to be set to be able to use it. + *

    + * An SessionFactory has to be set to be able to use it. * * @see #setSessionFactory(SessionFactory) */ @@ -65,7 +63,6 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager setTransactionSynchronization(SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); } - /** * Create a new Neo4jTransactionManager instance. * @@ -76,17 +73,16 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager this.sessionFactory = sessionFactory; } - /** * Set the SessionFactory that this instance should manage transactions for. - *

    By default, a default SessionFactory will be retrieved by finding a - * single unique bean of type SessionFactory in the containing BeanFactory. + *

    + * By default, a default SessionFactory will be retrieved by finding a single unique bean of type SessionFactory in + * the containing BeanFactory. */ public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } - /** * Return the SessionFactory that this instance should manage transactions for. */ @@ -94,7 +90,6 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager return this.sessionFactory; } - /** * Retrieves a default SessionFactory bean. */ @@ -105,7 +100,6 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager } } - @Override public void afterPropertiesSet() throws Exception { if (getSessionFactory() == null) { @@ -113,13 +107,11 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager } } - @Override public Object getResourceFactory() { return getSessionFactory(); } - @Override protected Object doGetTransaction() { Neo4jTransactionObject txObject = new Neo4jTransactionObject(); @@ -127,28 +119,24 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory()); if (sessionHolder != null) { if (logger.isDebugEnabled()) { - logger.debug("Found thread-bound Session [" + sessionHolder.getSession() + - "] for Neo4j OGM transaction"); + logger.debug("Found thread-bound Session [" + sessionHolder.getSession() + "] for Neo4j OGM transaction"); } txObject.setSessionHolder(sessionHolder, false); } return txObject; } - @Override protected boolean isExistingTransaction(Object transaction) { return ((Neo4jTransactionObject) transaction).hasTransaction(); } - @Override protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException { Neo4jTransactionObject txObject = (Neo4jTransactionObject) transaction; try { - if (txObject.getSessionHolder() == null || - txObject.getSessionHolder().isSynchronizedWithTransaction()) { + if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) { Session session = sessionFactory.openSession(); if (logger.isDebugEnabled()) { logger.debug("Opened new Session [" + session + "] for Neo4j OGM transaction"); @@ -165,12 +153,11 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager } if (definition.getPropagationBehavior() != TransactionDefinition.PROPAGATION_REQUIRED) { - throw new IllegalTransactionStateException( - "Neo4jTransactionManager only supports 'required' propagation."); + throw new IllegalTransactionStateException("Neo4jTransactionManager only supports 'required' propagation."); } Transaction transactionData; - if (definition.isReadOnly() && txObject.isNewSessionHolder()) { + if (definition.isReadOnly() && txObject.isNewSessionHolder()) { transactionData = session.beginTransaction(Transaction.Type.READ_ONLY); } else { transactionData = session.beginTransaction(); @@ -200,10 +187,8 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager } } - /** - * Close the current transaction's Session. - * Called after a transaction begin attempt failed. + * Close the current transaction's Session. Called after a transaction begin attempt failed. * * @param txObject the current transaction */ @@ -222,17 +207,14 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager } } - @Override protected Object doSuspend(Object transaction) { Neo4jTransactionObject txObject = (Neo4jTransactionObject) transaction; txObject.setSessionHolder(null, false); - SessionHolder sessionHolder = (SessionHolder) - TransactionSynchronizationManager.unbindResource(getSessionFactory()); + SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory()); return new SuspendedResourcesHolder(sessionHolder); } - @Override protected void doResume(Object transaction, Object suspendedResources) { SuspendedResourcesHolder resourcesHolder = (SuspendedResourcesHolder) suspendedResources; @@ -241,11 +223,9 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager // -> can be safely removed, will be closed on transaction completion. TransactionSynchronizationManager.unbindResource(getSessionFactory()); } - TransactionSynchronizationManager.bindResource( - getSessionFactory(), resourcesHolder.getSessionHolder()); + TransactionSynchronizationManager.bindResource(getSessionFactory(), resourcesHolder.getSessionHolder()); } - @Override protected void doCommit(DefaultTransactionStatus status) { @@ -267,7 +247,6 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager } } - @Override protected void doRollback(DefaultTransactionStatus status) { Neo4jTransactionObject txObject = (Neo4jTransactionObject) status.getTransaction(); @@ -293,18 +272,16 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager } } - @Override protected void doSetRollbackOnly(DefaultTransactionStatus status) { Neo4jTransactionObject txObject = (Neo4jTransactionObject) status.getTransaction(); if (status.isDebug()) { - logger.debug("Setting Neo4j OGM transaction on Session [" + - txObject.getSessionHolder().getSession() + "] rollback-only"); + logger.debug( + "Setting Neo4j OGM transaction on Session [" + txObject.getSessionHolder().getSession() + "] rollback-only"); } status.setRollbackOnly(); } - @Override protected void doCleanupAfterCompletion(Object transaction) { Neo4jTransactionObject txObject = (Neo4jTransactionObject) transaction; @@ -336,8 +313,7 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager } /** - * Neo4j OGM transaction object, representing a SessionHolder. - * Used as transaction object by Neo4jTransactionManager. + * Neo4j OGM transaction object, representing a SessionHolder. Used as transaction object by Neo4jTransactionManager. */ private static class Neo4jTransactionObject { @@ -347,8 +323,7 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager private Transaction transactionData; - void setSessionHolder( - SessionHolder sessionHolder, boolean newSessionHolder) { + void setSessionHolder(SessionHolder sessionHolder, boolean newSessionHolder) { this.sessionHolder = sessionHolder; this.newSessionHolder = newSessionHolder; } @@ -376,8 +351,7 @@ public class Neo4jTransactionManager extends AbstractPlatformTransactionManager } /** - * Holder for suspended resources. - * Used internally by {@code doSuspend} and {@code doResume}. + * Holder for suspended resources. Used internally by {@code doSuspend} and {@code doResume}. */ private static class SuspendedResourcesHolder { diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SessionFactoryUtils.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SessionFactoryUtils.java index c4688c6fc..b89c880b9 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SessionFactoryUtils.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SessionFactoryUtils.java @@ -37,10 +37,10 @@ import org.springframework.transaction.support.TransactionSynchronizationManager import org.springframework.util.Assert; /** - * Helper class featuring methods for Neo4j OGM Session handling, - * allowing for reuse of Session instances within transactions. - * Also provides support for exception translation. - *

    Mainly intended for internal use within the framework. + * Helper class featuring methods for Neo4j OGM Session handling, allowing for reuse of Session instances within + * transactions. Also provides support for exception translation. + *

    + * Mainly intended for internal use within the framework. * * @author Mark Angrish */ @@ -48,9 +48,7 @@ public class SessionFactoryUtils { private static final Logger logger = LoggerFactory.getLogger(SessionFactoryUtils.class); - - public static void closeSession(Session session) { - } + public static void closeSession(Session session) {} public static Session getSession(SessionFactory sessionFactory) throws IllegalStateException { @@ -58,11 +56,11 @@ public class SessionFactoryUtils { SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (sessionHolder != null) { - if (!sessionHolder.isSynchronizedWithTransaction() && - TransactionSynchronizationManager.isSynchronizationActive()) { + if (!sessionHolder.isSynchronizedWithTransaction() + && TransactionSynchronizationManager.isSynchronizationActive()) { sessionHolder.setSynchronizedWithTransaction(true); - TransactionSynchronizationManager.registerSynchronization( - new SessionSynchronization(sessionHolder, sessionFactory, false)); + TransactionSynchronizationManager + .registerSynchronization(new SessionSynchronization(sessionHolder, sessionFactory, false)); } return sessionHolder.getSession(); } @@ -83,22 +81,20 @@ public class SessionFactoryUtils { sessionHolder = new SessionHolder(session); sessionHolder.setSynchronizedWithTransaction(true); - TransactionSynchronizationManager.registerSynchronization( - new SessionSynchronization(sessionHolder, sessionFactory, true)); + TransactionSynchronizationManager + .registerSynchronization(new SessionSynchronization(sessionHolder, sessionFactory, true)); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); return session; } /** - * Convert the given runtime exception to an appropriate exception from the - * {@code org.springframework.dao} hierarchy. - * Return null if no translation is appropriate: any other exception may - * have resulted from user code, and should not be translated. + * Convert the given runtime exception to an appropriate exception from the {@code org.springframework.dao} hierarchy. + * Return null if no translation is appropriate: any other exception may have resulted from user code, and should not + * be translated. * * @param ex runtime exception that occurred - * @return the corresponding DataAccessException instance, - * or {@code null} if the exception should not be translated + * @return the corresponding DataAccessException instance, or {@code null} if the exception should not be translated */ public static DataAccessException convertOgmAccessException(RuntimeException ex) { @@ -161,9 +157,11 @@ public class SessionFactoryUtils { if (dae != null) { try { - final Constructor constructor = dae.getDeclaredConstructor(String.class, Throwable.class); + final Constructor constructor = dae.getDeclaredConstructor(String.class, + Throwable.class); return constructor.newInstance(ex.getMessage(), ex); - } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { + } catch (InstantiationException | IllegalAccessException | NoSuchMethodException + | InvocationTargetException e) { return null; } } @@ -176,15 +174,12 @@ public class SessionFactoryUtils { return null; } - - private static class SessionSynchronization - extends ResourceHolderSynchronization + private static class SessionSynchronization extends ResourceHolderSynchronization implements Ordered { private final boolean newSession; - SessionSynchronization( - SessionHolder sessionHolder, SessionFactory sessionFactory, boolean newSession) { + SessionSynchronization(SessionHolder sessionHolder, SessionFactory sessionFactory, boolean newSession) { super(sessionHolder, sessionFactory); this.newSession = newSession; } @@ -195,8 +190,7 @@ public class SessionFactoryUtils { } @Override - public void flushResource(SessionHolder resourceHolder) { - } + public void flushResource(SessionHolder resourceHolder) {} @Override protected boolean shouldUnbindAtCompletion() { @@ -205,7 +199,7 @@ public class SessionFactoryUtils { @Override protected boolean shouldReleaseAfterCompletion(SessionHolder resourceHolder) { -// return !resourceHolder.getSession().isClosed(); + // return !resourceHolder.getSession().isClosed(); return false; } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SessionHolder.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SessionHolder.java index 060a78188..0b8ffee5e 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SessionHolder.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SessionHolder.java @@ -18,11 +18,10 @@ import org.springframework.transaction.support.ResourceHolderSupport; import org.springframework.util.Assert; /** - * Holder wrapping a Neo4j OGM Session. - * Neo4jTransactionManager binds instances of this class to the thread, - * for a given SessionFactory. - * - *

    Note: This is an SPI class, not intended to be used by applications. + * Holder wrapping a Neo4j OGM Session. Neo4jTransactionManager binds instances of this class to the thread, for a given + * SessionFactory. + *

    + * Note: This is an SPI class, not intended to be used by applications. * * @author Mark Angrish * @see Neo4jTransactionManager @@ -39,7 +38,6 @@ public class SessionHolder extends ResourceHolderSupport { this.session = session; } - public Session getSession() { return this.session; } @@ -52,7 +50,6 @@ public class SessionHolder extends ResourceHolderSupport { return this.transactionActive; } - @Override public void clear() { super.clear(); diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SharedSessionCreator.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SharedSessionCreator.java index 9f28c6470..adfa1f2c1 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SharedSessionCreator.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/transaction/SharedSessionCreator.java @@ -30,12 +30,11 @@ import org.slf4j.LoggerFactory; import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * Delegate for creating a shareable Neo4j OGM {@link Session} - * reference for a given {@link SessionFactory}. - *

    A shared Session will behave just like a Session fetched from - * an application SessionFactory. - * It will delegate all calls to the current transactional Session, if any; - * otherwise it will fall back to a newly created Session per operation. + * Delegate for creating a shareable Neo4j OGM {@link Session} reference for a given {@link SessionFactory}. + *

    + * A shared Session will behave just like a Session fetched from an application SessionFactory. It will delegate all + * calls to the current transactional Session, if any; otherwise it will fall back to a newly created Session per + * operation. * * @author Mark Angrish * @see Neo4jTransactionManager @@ -54,22 +53,18 @@ public class SharedSessionCreator { /** * Create a transactional Session proxy for the given SessionFactory. * - * @param sessionFactory SessionFactory to obtain Sessions from as needed - * {@code createSession} call (may be {@code null}) - * Session. Allows the addition or specification of proprietary interfaces. + * @param sessionFactory SessionFactory to obtain Sessions from as needed {@code createSession} call (may be + * {@code null}) Session. Allows the addition or specification of proprietary interfaces. * @return a shareable transactional Session proxy */ public static Session createSharedSession(SessionFactory sessionFactory) { - return (Session) Proxy.newProxyInstance( - SharedSessionCreator.class.getClassLoader(), - new Class[]{Session.class}, new SharedSessionInvocationHandler(sessionFactory)); + return (Session) Proxy.newProxyInstance(SharedSessionCreator.class.getClassLoader(), + new Class[] { Session.class }, new SharedSessionInvocationHandler(sessionFactory)); } - /** - * Invocation handler that delegates all calls to the current - * transactional Session, if any; else, it will fall back + * Invocation handler that delegates all calls to the current transactional Session, if any; else, it will fall back * to a newly created Session per operation. */ private static class SharedSessionInvocationHandler implements InvocationHandler { @@ -84,7 +79,6 @@ public class SharedSessionCreator { this.proxyClassLoader = this.targetFactory.getClass().getClassLoader(); } - @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on Session interface coming in... @@ -100,8 +94,7 @@ public class SharedSessionCreator { return "Shared Session proxy for target factory [" + targetFactory + "]"; } else if (method.getName().equals("beginTransaction")) { throw new IllegalStateException( - "Not allowed to create transaction on shared Session - " + - "use Spring transactions instead"); + "Not allowed to create transaction on shared Session - " + "use Spring transactions instead"); } // Determine current Session: either the transactional one @@ -109,11 +102,11 @@ public class SharedSessionCreator { Session target = SessionFactoryUtils.getSession(this.targetFactory); if (transactionRequiringMethods.contains(method.getName())) { - if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() - && target.getTransaction() != null - && EnumSet.of(CLOSED, COMMITTED, ROLLEDBACK).contains(target.getTransaction().status()))) { - throw new IllegalStateException("No Session with actual transaction available " + - "for current thread - cannot reliably process '" + method.getName() + "' call"); + if (target == null + || (!TransactionSynchronizationManager.isActualTransactionActive() && target.getTransaction() != null + && EnumSet.of(CLOSED, COMMITTED, ROLLEDBACK).contains(target.getTransaction().status()))) { + throw new IllegalStateException("No Session with actual transaction available " + + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/util/IterableUtils.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/util/IterableUtils.java index a9916a380..eefaaea1b 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/util/IterableUtils.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/util/IterableUtils.java @@ -13,13 +13,13 @@ package org.springframework.data.neo4j.util; -import org.neo4j.ogm.exception.NotFoundException; - import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; +import org.neo4j.ogm.exception.NotFoundException; + /** * Utility methods for dealing with {@link Iterable}s. * @@ -27,229 +27,228 @@ import java.util.List; */ public final class IterableUtils { - /** - * Count items in an iterable. - * - * @param iterable to count items in. - * @return number of items in the iterable. - */ - public static long count(Iterable iterable) { - if (iterable instanceof Collection) { - return ((Collection) iterable).size(); - } + /** + * Count items in an iterable. + * + * @param iterable to count items in. + * @return number of items in the iterable. + */ + public static long count(Iterable iterable) { + if (iterable instanceof Collection) { + return ((Collection) iterable).size(); + } - int count = 0; - for (Object o : iterable) { - count++; - } + int count = 0; + for (Object o : iterable) { + count++; + } - return count; - } + return count; + } - /** - * Check whether an iterable contains the given object. - * - * @param iterable to check in. - * @param object to look for. - * @param type of the objects stored in the iterable. - * @return true iff the object is contained in the iterable. - */ - public static boolean contains(Iterable iterable, T object) { - if (iterable instanceof Collection) { - return ((Collection) iterable).contains(object); - } + /** + * Check whether an iterable contains the given object. + * + * @param iterable to check in. + * @param object to look for. + * @param type of the objects stored in the iterable. + * @return true iff the object is contained in the iterable. + */ + public static boolean contains(Iterable iterable, T object) { + if (iterable instanceof Collection) { + return ((Collection) iterable).contains(object); + } - for (T t : iterable) { - if (t.equals(object)) { - return true; - } - } + for (T t : iterable) { + if (t.equals(object)) { + return true; + } + } - return false; - } + return false; + } - /** - * Convert an iterable to a list. - * - * @param iterable to convert. - * @param type of the items held. - * @return a list. - */ - public static List toList(Iterable iterable) { - List list = new ArrayList<>(); + /** + * Convert an iterable to a list. + * + * @param iterable to convert. + * @param type of the items held. + * @return a list. + */ + public static List toList(Iterable iterable) { + List list = new ArrayList<>(); - if (iterable instanceof Collection) { - list.addAll((Collection) iterable); - } else { - for (T next : iterable) { - list.add(next); - } - } + if (iterable instanceof Collection) { + list.addAll((Collection) iterable); + } else { + for (T next : iterable) { + list.add(next); + } + } - return list; - } + return list; + } - /** - * Get a single element from iterator. - * - * @param iterator to find a single element. - * @param notFoundMessage exception message if there are no elements. - * @param type of the element. - * @return the element iff there is exactly one. - * @throws NotFoundException in case there are no elements. - * @throws IllegalStateException in case the iterable contains more than 1 element. - */ - public static T getSingle(Iterator iterator, String notFoundMessage) { - T result = getSingleOrNull(iterator); + /** + * Get a single element from iterator. + * + * @param iterator to find a single element. + * @param notFoundMessage exception message if there are no elements. + * @param type of the element. + * @return the element iff there is exactly one. + * @throws NotFoundException in case there are no elements. + * @throws IllegalStateException in case the iterable contains more than 1 element. + */ + public static T getSingle(Iterator iterator, String notFoundMessage) { + T result = getSingleOrNull(iterator); - if (result == null) { - throw new NotFoundException(notFoundMessage); - } + if (result == null) { + throw new NotFoundException(notFoundMessage); + } - return result; - } + return result; + } - /** - * Get a single element from iterable. - * - * @param iterable to find a single element. - * @param notFoundMessage exception message if there are no elements. - * @param type of the element. - * @return the element iff there is exactly one. - * @throws NotFoundException in case there are no elements. - * @throws IllegalStateException in case the iterable contains more than 1 element. - */ - public static T getSingle(Iterable iterable, String notFoundMessage) { - return getSingle(iterable.iterator(), notFoundMessage); - } + /** + * Get a single element from iterable. + * + * @param iterable to find a single element. + * @param notFoundMessage exception message if there are no elements. + * @param type of the element. + * @return the element iff there is exactly one. + * @throws NotFoundException in case there are no elements. + * @throws IllegalStateException in case the iterable contains more than 1 element. + */ + public static T getSingle(Iterable iterable, String notFoundMessage) { + return getSingle(iterable.iterator(), notFoundMessage); + } - /** - * Get a single element from iterator. - * - * @param iterator to find a single element. - * @param type of the element. - * @return the element iff there is exactly one. - * @throws NotFoundException in case there are no elements. - * @throws IllegalStateException in case the iterable contains more than 1 element. - */ - public static T getSingle(Iterator iterator) { - return getSingle(iterator, "Iterator is empty"); - } + /** + * Get a single element from iterator. + * + * @param iterator to find a single element. + * @param type of the element. + * @return the element iff there is exactly one. + * @throws NotFoundException in case there are no elements. + * @throws IllegalStateException in case the iterable contains more than 1 element. + */ + public static T getSingle(Iterator iterator) { + return getSingle(iterator, "Iterator is empty"); + } - /** - * Get a single element from iterable. - * - * @param iterable to find a single element. - * @param type of the element. - * @return the element iff there is exactly one. - * @throws NotFoundException in case there are no elements. - * @throws IllegalStateException in case the iterable contains more than 1 element. - */ - public static T getSingle(Iterable iterable) { - return getSingle(iterable.iterator(), "Iterable is empty"); - } + /** + * Get a single element from iterable. + * + * @param iterable to find a single element. + * @param type of the element. + * @return the element iff there is exactly one. + * @throws NotFoundException in case there are no elements. + * @throws IllegalStateException in case the iterable contains more than 1 element. + */ + public static T getSingle(Iterable iterable) { + return getSingle(iterable.iterator(), "Iterable is empty"); + } - /** - * Get a single element from iterator. - * - * @param iterator to find a single element. - * @param type of the element. - * @return the element iff there is exactly one, null iff there is 0. - * @throws IllegalStateException in case the iterable contains more than 1 element. - */ - public static T getSingleOrNull(Iterator iterator) { - T result = null; + /** + * Get a single element from iterator. + * + * @param iterator to find a single element. + * @param type of the element. + * @return the element iff there is exactly one, null iff there is 0. + * @throws IllegalStateException in case the iterable contains more than 1 element. + */ + public static T getSingleOrNull(Iterator iterator) { + T result = null; - if (iterator.hasNext()) { - result = iterator.next(); - } + if (iterator.hasNext()) { + result = iterator.next(); + } - if (iterator.hasNext()) { - throw new IllegalStateException("Iterable has more than one element, which is unexpected"); - } + if (iterator.hasNext()) { + throw new IllegalStateException("Iterable has more than one element, which is unexpected"); + } - return result; - } + return result; + } - /** - * Get a single element from iterable. - * - * @param iterable to find a single element. - * @param type of the element. - * @return the element iff there is exactly one, null iff there is 0. - * @throws IllegalStateException in case the iterable contains more than 1 element. - */ - public static T getSingleOrNull(Iterable iterable) { - return getSingleOrNull(iterable.iterator()); - } + /** + * Get a single element from iterable. + * + * @param iterable to find a single element. + * @param type of the element. + * @return the element iff there is exactly one, null iff there is 0. + * @throws IllegalStateException in case the iterable contains more than 1 element. + */ + public static T getSingleOrNull(Iterable iterable) { + return getSingleOrNull(iterable.iterator()); + } - /** - * Get the first element from iterator. - * - * @param iterator to find the first element. - * @param notFoundMessage exception message if there are no elements. - * @param type of the element. - * @return the element iff there is one or more. - * @throws NotFoundException in case there are no elements. - */ - public static T getFirst(Iterator iterator, String notFoundMessage) { - T result = null; + /** + * Get the first element from iterator. + * + * @param iterator to find the first element. + * @param notFoundMessage exception message if there are no elements. + * @param type of the element. + * @return the element iff there is one or more. + * @throws NotFoundException in case there are no elements. + */ + public static T getFirst(Iterator iterator, String notFoundMessage) { + T result = null; - if (iterator.hasNext()) { - result = iterator.next(); - } + if (iterator.hasNext()) { + result = iterator.next(); + } - if (result == null) { - throw new NotFoundException(notFoundMessage); - } + if (result == null) { + throw new NotFoundException(notFoundMessage); + } - return result; - } + return result; + } - /** - * Get the first element from iterable. - * - * @param iterable to find the first element. - * @param notFoundMessage exception message if there are no elements. - * @param type of the element. - * @return the element iff there is one or more. - * @throws NotFoundException in case there are no elements. - */ - public static T getFirst(Iterable iterable, String notFoundMessage) { - return getFirst(iterable.iterator(), notFoundMessage); - } + /** + * Get the first element from iterable. + * + * @param iterable to find the first element. + * @param notFoundMessage exception message if there are no elements. + * @param type of the element. + * @return the element iff there is one or more. + * @throws NotFoundException in case there are no elements. + */ + public static T getFirst(Iterable iterable, String notFoundMessage) { + return getFirst(iterable.iterator(), notFoundMessage); + } - /** - * Get the first element from iterator. - * - * @param iterator to find the first element. - * @param type of the element. - * @return the element iff there is one or more, null if there is none. - */ - public static T getFirstOrNull(Iterator iterator) { - T result = null; + /** + * Get the first element from iterator. + * + * @param iterator to find the first element. + * @param type of the element. + * @return the element iff there is one or more, null if there is none. + */ + public static T getFirstOrNull(Iterator iterator) { + T result = null; - if (iterator.hasNext()) { - result = iterator.next(); - } + if (iterator.hasNext()) { + result = iterator.next(); + } - return result; - } + return result; + } - /** - * Get the first element from iterable. - * - * @param iterable to find the first element. - * @param type of the element. - * @return the element iff there is one or more, null if there is none. - */ - public static T getFirstOrNull(Iterable iterable) { - return getFirstOrNull(iterable.iterator()); - } + /** + * Get the first element from iterable. + * + * @param iterable to find the first element. + * @param type of the element. + * @return the element iff there is one or more, null if there is none. + */ + public static T getFirstOrNull(Iterable iterable) { + return getFirstOrNull(iterable.iterator()); + } - /** - * private constructor to prevent instantiation. - */ - private IterableUtils() { - } + /** + * private constructor to prevent instantiation. + */ + private IterableUtils() {} } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/AsyncRequestInterceptor.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/AsyncRequestInterceptor.java index d3427dbc9..f927d910c 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/AsyncRequestInterceptor.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/AsyncRequestInterceptor.java @@ -26,15 +26,14 @@ import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; /** - * An interceptor with asynchronous web requests used in OpenSessionInViewFilter and - * OpenSessionInViewInterceptor. - * Ensures the following: - * 1) The session is bound/unbound when "callable processing" is started - * 2) The session is closed if an async request times out + * An interceptor with asynchronous web requests used in OpenSessionInViewFilter and OpenSessionInViewInterceptor. + * Ensures the following: 1) The session is bound/unbound when "callable processing" is started 2) The session is closed + * if an async request times out * * @author Mark Angrish */ -class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter implements DeferredResultProcessingInterceptor { +class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter + implements DeferredResultProcessingInterceptor { private static final Logger logger = LoggerFactory.getLogger(AsyncRequestInterceptor.class); @@ -49,7 +48,6 @@ class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter imple this.sessionHolder = sessionHolder; } - @Override public void preProcess(NativeWebRequest request, Callable task) { bindSession(); @@ -68,7 +66,7 @@ class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter imple @Override public Object handleTimeout(NativeWebRequest request, Callable task) { this.timeoutInProgress = true; - return RESULT_NONE; // give other interceptors a chance to handle the timeout + return RESULT_NONE; // give other interceptors a chance to handle the timeout } @Override @@ -80,13 +78,12 @@ class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter imple if (this.timeoutInProgress) { logger.debug("Closing Neo4j OGM Session after async request timeout"); // close session. -// SessionFactoryUtils.closeSession(session); + // SessionFactoryUtils.closeSession(session); } } @Override - public void beforeConcurrentHandling(NativeWebRequest request, DeferredResult deferredResult) { - } + public void beforeConcurrentHandling(NativeWebRequest request, DeferredResult deferredResult) {} @Override public void preProcess(NativeWebRequest request, DeferredResult deferredResult) { @@ -101,11 +98,12 @@ class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter imple @Override public boolean handleTimeout(NativeWebRequest request, DeferredResult deferredResult) { this.timeoutInProgress = true; - return true; // give other interceptors a chance to handle the timeout + return true; // give other interceptors a chance to handle the timeout } @Override - public void afterCompletion(NativeWebRequest nativeWebRequest, DeferredResult deferredResult) throws Exception { + public void afterCompletion(NativeWebRequest nativeWebRequest, DeferredResult deferredResult) + throws Exception { // Do nothing. } } diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/OpenSessionInViewFilter.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/OpenSessionInViewFilter.java index 53a81cd7e..7829adb42 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/OpenSessionInViewFilter.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/OpenSessionInViewFilter.java @@ -13,16 +13,16 @@ package org.springframework.data.neo4j.web.support; +import java.io.IOException; + import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; import org.springframework.data.neo4j.transaction.Neo4jTransactionManager; -import org.springframework.data.neo4j.transaction.SessionFactoryUtils; import org.springframework.data.neo4j.transaction.SessionHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.StringUtils; @@ -33,16 +33,15 @@ import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; /** - * Servlet Filter that binds a Neo4j OGM Session to the thread for the - * entire processing of the request. Intended for the "Open Session in - * View" pattern, i.e. to allow for lazy loading in web views despite the - * original transactions already being completed. - *

    This filter makes OGM Sessions available via the current thread, - * which will be autodetected by transaction managers. At the moment this service is - * only suitable for transactions via {@link Neo4jTransactionManager}. - *

    Looks up the SessionFactory in Spring's root web application context. - * Supports an "sessionFactoryBeanName" filter init-param in {@code web.xml}; - * the default bean name is "sessionFactory". + * Servlet Filter that binds a Neo4j OGM Session to the thread for the entire processing of the request. Intended for + * the "Open Session in View" pattern, i.e. to allow for lazy loading in web views despite the original transactions + * already being completed. + *

    + * This filter makes OGM Sessions available via the current thread, which will be autodetected by transaction managers. + * At the moment this service is only suitable for transactions via {@link Neo4jTransactionManager}. + *

    + * Looks up the SessionFactory in Spring's root web application context. Supports an "sessionFactoryBeanName" filter + * init-param in {@code web.xml}; the default bean name is "sessionFactory". * * @author Mark Angrish * @see OpenSessionInViewInterceptor @@ -63,9 +62,9 @@ public class OpenSessionInViewFilter extends OncePerRequestFilter { private volatile SessionFactory sessionFactory; /** - * Set the bean name of the SessionFactory to fetch from Spring's - * root application context. - *

    Default is "sessionFactory". + * Set the bean name of the SessionFactory to fetch from Spring's root application context. + *

    + * Default is "sessionFactory". * * @see #DEFAULT_SESSION_FACTORY_BEAN_NAME */ @@ -74,38 +73,31 @@ public class OpenSessionInViewFilter extends OncePerRequestFilter { } /** - * Return the bean name of the SessionFactory to fetch from Spring's - * root application context. + * Return the bean name of the SessionFactory to fetch from Spring's root application context. */ protected String getSessionFactoryBeanName() { return this.sessionFactoryBeanName; } - /** - * Returns "false" so that the filter may re-bind the opened {@code Session} - * to each asynchronously dispatched thread and postpone closing it until the very - * last asynchronous dispatch. + * Returns "false" so that the filter may re-bind the opened {@code Session} to each asynchronously dispatched thread + * and postpone closing it until the very last asynchronous dispatch. */ @Override protected boolean shouldNotFilterAsyncDispatch() { return false; } - /** - * Returns "false" so that the filter may provide an {@code Session} - * to each error dispatches. + * Returns "false" so that the filter may provide an {@code Session} to each error dispatches. */ @Override protected boolean shouldNotFilterErrorDispatch() { return false; } - @Override - protected void doFilterInternal( - HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { SessionFactory sessionFactory = lookupSessionFactory(request); @@ -139,17 +131,17 @@ public class OpenSessionInViewFilter extends OncePerRequestFilter { if (!isAsyncStarted(request)) { logger.debug("Closed Neo4J OGM Session in OpenSessionInViewFilter"); // close session. -// SessionFactoryUtils.closeSession(session); + // SessionFactoryUtils.closeSession(session); } } } } /** - * Look up the SessionFactory that this filter should use, - * taking the current HTTP request as argument. - *

    The default implementation delegates to the {@code lookupSessionFactory} - * without arguments, caching the SessionFactory reference once obtained. + * Look up the SessionFactory that this filter should use, taking the current HTTP request as argument. + *

    + * The default implementation delegates to the {@code lookupSessionFactory} without arguments, caching the + * SessionFactory reference once obtained. * * @return the SessionFactory to use * @see #lookupSessionFactory() @@ -163,8 +155,8 @@ public class OpenSessionInViewFilter extends OncePerRequestFilter { /** * Look up the SessionFactory that this filter should use. - *

    The default implementation looks for a bean with the specified name - * in Spring's root application context. + *

    + * The default implementation looks for a bean with the specified name in Spring's root application context. * * @return the SessionFactory to use * @see #getSessionFactoryBeanName @@ -182,10 +174,10 @@ public class OpenSessionInViewFilter extends OncePerRequestFilter { } } - /** * Create a Neo4j OGM Session to be bound to a request. - *

    Can be overridden in subclasses. + *

    + * Can be overridden in subclasses. * * @param sessionFactory the SessionFactory to use * @see SessionFactory#openSession diff --git a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/OpenSessionInViewInterceptor.java b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/OpenSessionInViewInterceptor.java index 8638e0f53..385d576f4 100644 --- a/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/OpenSessionInViewInterceptor.java +++ b/spring-data-neo4j/src/main/java/org/springframework/data/neo4j/web/support/OpenSessionInViewInterceptor.java @@ -13,7 +13,6 @@ package org.springframework.data.neo4j.web.support; - import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; import org.slf4j.Logger; @@ -32,15 +31,15 @@ import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; /** - * Spring web request interceptor that binds a Neo4j OGM Session to the - * thread for the entire processing of the request. Intended for the "Open - * Session in View" pattern, i.e. to allow for lazy loading in - * web views despite the original transactions already being completed. - *

    This interceptor makes Neo4j OGM Sessions available via the current thread, - * which will be autodetected by transaction managers. It is suitable for service - * layer transactions via {@link Neo4jTransactionManager}. - *

    In contrast to {@link OpenSessionInViewFilter}, this interceptor is set - * up in a Spring application context and can thus take advantage of bean wiring. + * Spring web request interceptor that binds a Neo4j OGM Session to the thread for the entire processing of the request. + * Intended for the "Open Session in View" pattern, i.e. to allow for lazy loading in web views despite the original + * transactions already being completed. + *

    + * This interceptor makes Neo4j OGM Sessions available via the current thread, which will be autodetected by transaction + * managers. It is suitable for service layer transactions via {@link Neo4jTransactionManager}. + *

    + * In contrast to {@link OpenSessionInViewFilter}, this interceptor is set up in a Spring application context and can + * thus take advantage of bean wiring. * * @author Mark Angrish * @see OpenSessionInViewFilter @@ -55,8 +54,7 @@ public class OpenSessionInViewInterceptor implements BeanFactoryAware, AsyncWebR protected final Logger logger = LoggerFactory.getLogger(getClass()); /** - * Suffix that gets appended to the SessionFactory toString - * representation for the "participate in existing session + * Suffix that gets appended to the SessionFactory toString representation for the "participate in existing session * handling" request attribute. * * @see #getParticipateAttributeName @@ -66,8 +64,7 @@ public class OpenSessionInViewInterceptor implements BeanFactoryAware, AsyncWebR private SessionFactory sessionFactory; /** - * Set the Neo4j OGM SessionFactory that should be used to create - * Sessions. + * Set the Neo4j OGM SessionFactory that should be used to create Sessions. * * @see SessionFactory#openSession */ @@ -76,8 +73,7 @@ public class OpenSessionInViewInterceptor implements BeanFactoryAware, AsyncWebR } /** - * Return the Neo4j OGM SessionFactory that should be used to create - * Sessions. + * Return the Neo4j OGM SessionFactory that should be used to create Sessions. */ public SessionFactory getSessionFactory() { return this.sessionFactory; @@ -93,7 +89,6 @@ public class OpenSessionInViewInterceptor implements BeanFactoryAware, AsyncWebR } } - @Override public void preHandle(WebRequest request) throws DataAccessException { String participateAttributeName = getParticipateAttributeName(); @@ -123,8 +118,7 @@ public class OpenSessionInViewInterceptor implements BeanFactoryAware, AsyncWebR } @Override - public void postHandle(WebRequest request, ModelMap model) { - } + public void postHandle(WebRequest request, ModelMap model) {} @Override public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException { @@ -132,7 +126,7 @@ public class OpenSessionInViewInterceptor implements BeanFactoryAware, AsyncWebR TransactionSynchronizationManager.unbindResource(getSessionFactory()); logger.debug("Closed Neo4j OGM Session in OpenSessionInViewInterceptor"); // close session. -// SessionFactoryUtils.closeSession(session); + // SessionFactoryUtils.closeSession(session); } } @@ -159,9 +153,8 @@ public class OpenSessionInViewInterceptor implements BeanFactoryAware, AsyncWebR } /** - * Return the name of the request attribute that identifies that a request is - * already filtered. Default implementation takes the toString representation - * of the SessionFactory instance and appends ".FILTERED". + * Return the name of the request attribute that identifies that a request is already filtered. Default implementation + * takes the toString representation of the SessionFactory instance and appends ".FILTERED". * * @see #PARTICIPATE_SUFFIX */ @@ -169,7 +162,6 @@ public class OpenSessionInViewInterceptor implements BeanFactoryAware, AsyncWebR return getSessionFactory().toString() + PARTICIPATE_SUFFIX; } - private boolean applyCallableInterceptor(WebAsyncManager asyncManager, String key) { if (asyncManager.getCallableInterceptor(key) == null) { return false; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/Role.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/Role.java index 1655b8e83..8077fb7da 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/Role.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/Role.java @@ -12,7 +12,6 @@ */ package org.springframework.data.neo4j.domain.sample; - import java.util.UUID; import org.neo4j.ogm.annotation.GraphId; @@ -28,8 +27,7 @@ public class Role { private static final String PREFIX = "ROLE_"; - @GraphId - private Long id; + @GraphId private Long id; private UUID uuid; private String name; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/SampleEntity.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/SampleEntity.java index 8bce21550..d7abc6b8b 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/SampleEntity.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/SampleEntity.java @@ -23,8 +23,7 @@ import org.springframework.util.Assert; @NodeEntity public class SampleEntity { - @GraphId - protected Long id; + @GraphId protected Long id; private String first; private String second; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/User.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/User.java index 34c6c75f3..3313a4345 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/User.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/domain/sample/User.java @@ -10,7 +10,6 @@ import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; import org.neo4j.ogm.annotation.typeconversion.DateString; - /** * Domain class representing a person emphasizing the use of {@code AbstractEntity}. No declaration of an id is * required. The id is typed by the parameterizable superclass. @@ -18,8 +17,7 @@ import org.neo4j.ogm.annotation.typeconversion.DateString; @NodeEntity public class User { - @GraphId - private Long id; + @GraphId private Long id; private String firstname; @@ -33,11 +31,9 @@ public class User { private String emailAddress; - @Relationship - private Set colleagues; + @Relationship private Set colleagues; - @Relationship - private Set roles; + @Relationship private Set roles; private User manager; @@ -47,8 +43,7 @@ public class User { private Set attributes; - @DateString - private Date dateOfBirth; + @DateString private Date dateOfBirth; /** * Creates a new empty instance of {@code User}. diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/EventPublisher.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/EventPublisher.java index 375a1487a..1b4045e79 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/EventPublisher.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/EventPublisher.java @@ -12,8 +12,7 @@ import org.springframework.stereotype.Component; @Component public class EventPublisher extends EventListenerAdapter { - @Autowired - private ApplicationEventPublisher publisher; + @Autowired private ApplicationEventPublisher publisher; @Override public void onPreSave(Event event) { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/Neo4jModificationEventListener.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/Neo4jModificationEventListener.java index eb831f119..99838d860 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/Neo4jModificationEventListener.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/Neo4jModificationEventListener.java @@ -1,7 +1,6 @@ package org.springframework.data.neo4j.events; import org.springframework.context.event.EventListener; -import org.springframework.core.ResolvableType; import org.springframework.stereotype.Component; /** @@ -21,7 +20,7 @@ public class Neo4jModificationEventListener { @EventListener public void onPreSaveEvent(PreSaveEvent event) { - preSaveEvent= event; + preSaveEvent = event; preSaveEventCount++; } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/PostDeleteEvent.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/PostDeleteEvent.java index d260d23d0..0815eb4db 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/PostDeleteEvent.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/PostDeleteEvent.java @@ -7,7 +7,7 @@ import org.neo4j.ogm.session.event.Event; */ public class PostDeleteEvent extends ModificationEvent { - public PostDeleteEvent( Event event) { + public PostDeleteEvent(Event event) { super(event); } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/PreDeleteEvent.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/PreDeleteEvent.java index c47528028..bbab73b8f 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/PreDeleteEvent.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/events/PreDeleteEvent.java @@ -7,7 +7,7 @@ import org.neo4j.ogm.session.event.Event; */ public class PreDeleteEvent extends ModificationEvent { - public PreDeleteEvent( Event event) { + public PreDeleteEvent(Event event) { super(event); } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/FriendIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/FriendIT.java index 689849188..dd5a666ac 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/FriendIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/FriendIT.java @@ -36,7 +36,7 @@ import org.springframework.transaction.annotation.Transactional; * @author Luanne Misquitta * @author Mark Angrish */ -@ContextConfiguration(classes = {FriendContext.class}) +@ContextConfiguration(classes = { FriendContext.class }) @RunWith(SpringJUnit4ClassRunner.class) public class FriendIT extends MultiDriverTestClass { @@ -47,11 +47,10 @@ public class FriendIT extends MultiDriverTestClass { @Autowired FriendService friendService; @BeforeClass - public static void beforeClass(){ + public static void beforeClass() { graphDatabaseService = getGraphDatabaseService(); } - @Before public void cleanUpDatabase() { graphDatabaseService.execute("MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE r, n"); diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/FriendService.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/FriendService.java index 4cd436194..9234d33b5 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/FriendService.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/FriendService.java @@ -27,8 +27,7 @@ import org.springframework.transaction.annotation.Transactional; @Service public class FriendService { - @Autowired - Session session; + @Autowired Session session; @Transactional public void createPersonAndFriends() { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/domain/Person.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/domain/Person.java index 0fbf10578..df702fe7b 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/domain/Person.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/friends/domain/Person.java @@ -13,13 +13,13 @@ package org.springframework.data.neo4j.examples.friends.domain; +import java.util.HashSet; +import java.util.Set; + import org.neo4j.ogm.annotation.GraphId; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; -import java.util.HashSet; -import java.util.Set; - /** * @author Luanne Misquitta */ @@ -30,8 +30,7 @@ public class Person { private String firstName; private String lastName; - @Relationship(type = "IS_FRIEND") - private Set friendships = new HashSet<>(); + @Relationship(type = "IS_FRIEND") private Set friendships = new HashSet<>(); public Person() {} diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/GalaxyServiceIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/GalaxyServiceIT.java index b1b3a4929..cdc874096 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/GalaxyServiceIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/GalaxyServiceIT.java @@ -40,17 +40,15 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; - /** * @author Vince Bickers */ -@ContextConfiguration(classes = {GalaxyContext.class}) +@ContextConfiguration(classes = { GalaxyContext.class }) @RunWith(SpringJUnit4ClassRunner.class) @Transactional public class GalaxyServiceIT extends MultiDriverTestClass { - @Autowired - private GalaxyService galaxyService; + @Autowired private GalaxyService galaxyService; @Before public void setUp() { @@ -98,7 +96,6 @@ public class GalaxyServiceIT extends MultiDriverTestClass { } } - @Test public void shouldFindWorldsByName() { galaxyService.makeSomeWorlds(); @@ -140,9 +137,7 @@ public class GalaxyServiceIT extends MultiDriverTestClass { galaxyService.makeSomeWorlds(); for (World worldWithOneMoon : galaxyService.findAllByNumberOfMoons(1)) { - assertThat( - worldWithOneMoon.getName(), - is(anyOf(containsString("Earth"), containsString("Midgard")))); + assertThat(worldWithOneMoon.getName(), is(anyOf(containsString("Earth"), containsString("Midgard")))); } } @@ -218,11 +213,11 @@ public class GalaxyServiceIT extends MultiDriverTestClass { sum += world.getId(); } // note: this doesn't work, because deleted node ids are not reclaimed - // long sum = (size * size - size) / 2; // 0-based node ids + // long sum = (size * size - size) / 2; // 0-based node ids Pageable pageable = new PageRequest(0, 3); - for (; ; ) { + for (;;) { Page page = galaxyService.findAllWorlds(pageable); for (World world : page) { System.out.println(world.getName() + ":" + world.getId()); @@ -249,7 +244,7 @@ public class GalaxyServiceIT extends MultiDriverTestClass { Pageable pageable = new PageRequest(0, 3, Sort.Direction.ASC, "name"); int i = 0; - for (; ; ) { + for (;;) { Page page = galaxyService.findAllWorlds(pageable); for (World world : page) { assertEquals(sortedNames[i], world.getName()); @@ -306,7 +301,7 @@ public class GalaxyServiceIT extends MultiDriverTestClass { names.add(world.getName()); } - String[] sortedNames = names.toArray(new String[]{}); + String[] sortedNames = names.toArray(new String[] {}); Arrays.sort(sortedNames); return sortedNames; } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/WorldRepositoryIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/WorldRepositoryIT.java index cab926302..b4622a97a 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/WorldRepositoryIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/WorldRepositoryIT.java @@ -28,34 +28,31 @@ import org.springframework.data.neo4j.examples.galaxy.domain.World; import org.springframework.data.neo4j.examples.galaxy.repo.WorldRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; -@ContextConfiguration(classes = {GalaxyContext.class}) +@ContextConfiguration(classes = { GalaxyContext.class }) @RunWith(SpringJUnit4ClassRunner.class) public class WorldRepositoryIT extends MultiDriverTestClass { - @Autowired - WorldRepository worldRepository; + @Autowired WorldRepository worldRepository; - @Autowired - TransactionTemplate transactionTemplate; + @Autowired TransactionTemplate transactionTemplate; boolean failed = false; /** * see https://jira.spring.io/browse/DATAGRAPH-951 + * * @throws Exception */ @Test public void multipleThreadsResultsGetMixedUp() throws Exception { - World world1 = new World("world 1", 1); - worldRepository.save(world1, 0); + World world1 = new World("world 1", 1); + worldRepository.save(world1, 0); - World world2 = new World("world 2", 2); - worldRepository.save(world2, 0); + World world2 = new World("world 2", 2); + worldRepository.save(world2, 0); int iterations = 10; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/context/GalaxyContext.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/context/GalaxyContext.java index 577c65211..ed2d78632 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/context/GalaxyContext.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/context/GalaxyContext.java @@ -29,7 +29,7 @@ import org.springframework.transaction.support.TransactionTemplate; * @author Mark Angrish */ @Configuration -@ComponentScan({"org.springframework.data.neo4j.examples.galaxy.service"}) +@ComponentScan({ "org.springframework.data.neo4j.examples.galaxy.service" }) @PropertySource("classpath:helloworld.properties") @EnableNeo4jRepositories("org.springframework.data.neo4j.examples.galaxy.repo") @EnableTransactionManagement @@ -46,7 +46,7 @@ public class GalaxyContext { } @Bean - public TransactionTemplate transactionTemplate() { + public TransactionTemplate transactionTemplate() { return new TransactionTemplate(transactionManager()); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/domain/World.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/domain/World.java index e33c362cc..f0070f9c2 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/domain/World.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/domain/World.java @@ -13,116 +13,118 @@ package org.springframework.data.neo4j.examples.galaxy.domain; -import org.neo4j.ogm.annotation.Relationship; - import java.util.HashSet; import java.util.Set; +import org.neo4j.ogm.annotation.Relationship; + /** * @author Vince Bickers * @author Luanne Misquitta */ public class World { - private final static String REACHABLE_BY_ROCKET = "REACHABLE_BY_ROCKET"; + private final static String REACHABLE_BY_ROCKET = "REACHABLE_BY_ROCKET"; - private Long id; + private Long id; - private String name; + private String name; - private int moons; + private int moons; - private Float radius; + private Float radius; - private Long updated; + private Long updated; - public Long getUpdated() { - return updated; - } + public Long getUpdated() { + return updated; + } - public void setUpdated(long updated) { - this.updated = updated; - } + public void setUpdated(long updated) { + this.updated = updated; + } + private Set reachableByRocket = new HashSet<>(); - private Set reachableByRocket = new HashSet<>(); + public World(String name, int moons) { + this.name = name; + this.moons = moons; + } - public World(String name, int moons) { - this.name = name; - this.moons = moons; - } + public World() {} - public World() { - } + public Long getId() { + return id; + } - public Long getId() { - return id; - } + public String getName() { + return name; + } - public String getName() { - return name; - } + public int getMoons() { + return moons; + } - public int getMoons() { - return moons; - } + public void addRocketRouteTo(World otherWorld) { + reachableByRocket.add(otherWorld); + // symmetric relationship. + otherWorld.reachableByRocket.add(this); // bi-directional in domain. + } - public void addRocketRouteTo(World otherWorld) { - reachableByRocket.add(otherWorld); - // symmetric relationship. - otherWorld.reachableByRocket.add(this); // bi-directional in domain. - } + @Relationship(type = REACHABLE_BY_ROCKET, direction = "UNDIRECTED") + public Set getReachableByRocket() { + return this.reachableByRocket; + } - @Relationship(type=REACHABLE_BY_ROCKET, direction = "UNDIRECTED") - public Set getReachableByRocket() { - return this.reachableByRocket; - } + @Relationship(type = REACHABLE_BY_ROCKET, direction = "UNDIRECTED") + public void setReachableByRocket(Set reachableByRocket) { + this.reachableByRocket.clear(); + this.reachableByRocket = reachableByRocket; + } - @Relationship(type=REACHABLE_BY_ROCKET , direction = "UNDIRECTED") - public void setReachableByRocket(Set reachableByRocket) { - this.reachableByRocket.clear(); - this.reachableByRocket = reachableByRocket; - } + public boolean canBeReachedFrom(World otherWorld) { + for (World world : reachableByRocket) { + if (world.equals(otherWorld)) { + return true; + } + } + return false; + } - public boolean canBeReachedFrom(World otherWorld) { - for(World world : reachableByRocket) { - if(world.equals(otherWorld)) { - return true; - } - } - return false; - } + public Float getRadius() { + return radius; + } - public Float getRadius() { - return radius; - } + public void setRadius(Float radius) { + this.radius = radius; + } - public void setRadius(Float radius) { - this.radius = radius; - } + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + World world = (World) o; - World world = (World) o; + if (moons != world.moons) + return false; + if (id != null ? !id.equals(world.id) : world.id != null) + return false; + return !(name != null ? !name.equals(world.name) : world.name != null); + } - if (moons != world.moons) return false; - if (id != null ? !id.equals(world.id) : world.id != null) return false; - return !(name != null ? !name.equals(world.name) : world.name != null); - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (name != null ? name.hashCode() : 0); + result = 31 * result + moons; + return result; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (name != null ? name.hashCode() : 0); - result = 31 * result + moons; - return result; - } - - @Override - public String toString() { - return String.format("World{name='%s', moons=%d}", name, moons); - } + @Override + public String toString() { + return String.format("World{name='%s', moons=%d}", name, moons); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/repo/WorldRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/repo/WorldRepository.java index 2d78be173..172286e33 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/repo/WorldRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/repo/WorldRepository.java @@ -17,7 +17,6 @@ import org.neo4j.ogm.model.Result; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.neo4j.examples.galaxy.domain.World; import org.springframework.data.neo4j.repository.GraphRepository; -import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.stereotype.Repository; /** @@ -27,12 +26,12 @@ import org.springframework.stereotype.Repository; @Repository public interface WorldRepository extends GraphRepository { - @Query("MATCH (n:World) SET n.updated=timestamp()") - void touchAllWorlds(); + @Query("MATCH (n:World) SET n.updated=timestamp()") + void touchAllWorlds(); - @Query("MATCH (n:World) SET n.updated=timestamp()") - Result touchAllWorldsWithStatistics(); + @Query("MATCH (n:World) SET n.updated=timestamp()") + Result touchAllWorldsWithStatistics(); - World findByName(String name); + World findByName(String name); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/service/GalaxyService.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/service/GalaxyService.java index f8f207be6..51f757d07 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/service/GalaxyService.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/galaxy/service/GalaxyService.java @@ -36,11 +36,9 @@ import org.springframework.transaction.annotation.Transactional; @Transactional public class GalaxyService { - @Autowired - private WorldRepository worldRepository; + @Autowired private WorldRepository worldRepository; - @Autowired - Session session; + @Autowired Session session; public long getNumberOfWorlds() { return worldRepository.count(); @@ -89,13 +87,13 @@ public class GalaxyService { mars.addRocketRouteTo(earth); // todo: handle bi-directional automatically - //earth.addRocketRouteTo(mars); + // earth.addRocketRouteTo(mars); // this is a bit silly worldRepository.save(mars); // todo: handle-bidirectional automatically - //worldRepository.save(earth); + // worldRepository.save(earth); worlds.add(earth); worlds.add(mars); @@ -163,7 +161,6 @@ public class GalaxyService { return session.loadAll(World.class, new Filter(propertyName, propertyValue), depth); } - public Iterable findAllWorlds(Pagination paging) { return session.loadAll(World.class, paging, 0); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/JSR303Context.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/JSR303Context.java index 7d319948c..d748ebda8 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/JSR303Context.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/JSR303Context.java @@ -28,7 +28,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; * @author Mark Angrish */ @Configuration -@ComponentScan(basePackageClasses = {AdultService.class}) +@ComponentScan(basePackageClasses = { AdultService.class }) @EnableNeo4jRepositories("org.springframework.data.neo4j.examples.jsr303.repo") @EnableTransactionManagement public class JSR303Context { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/JSR303IT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/JSR303IT.java index 732ad0661..4fb7734f0 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/JSR303IT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/JSR303IT.java @@ -35,18 +35,16 @@ import org.springframework.web.context.WebApplicationContext; * @author Vince Bickers * @author Mark Angrish */ -@ContextConfiguration(classes = {WebConfiguration.class, JSR303Context.class}) +@ContextConfiguration(classes = { WebConfiguration.class, JSR303Context.class }) @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) public class JSR303IT extends MultiDriverTestClass { private static final ObjectMapper objectMapper = new ObjectMapper(); - @Autowired - private AdultService service; + @Autowired private AdultService service; - @Autowired - WebApplicationContext wac; + @Autowired WebApplicationContext wac; private MockMvc mockMvc; @@ -61,11 +59,7 @@ public class JSR303IT extends MultiDriverTestClass { Adult adult = new Adult("Peter", 18); String json = objectMapper.writeValueAsString(adult); - mockMvc.perform( - post("/adults") - .contentType(MediaType.APPLICATION_JSON) - .content(json)) - .andExpect(status().isOk()); + mockMvc.perform(post("/adults").contentType(MediaType.APPLICATION_JSON).content(json)).andExpect(status().isOk()); } @Test @@ -74,10 +68,7 @@ public class JSR303IT extends MultiDriverTestClass { Adult adult = new Adult("Peter", 16); String json = objectMapper.writeValueAsString(adult); - mockMvc.perform( - post("/adults") - .contentType(MediaType.APPLICATION_JSON) - .content(json)) + mockMvc.perform(post("/adults").contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(status().isBadRequest()); } @@ -87,10 +78,7 @@ public class JSR303IT extends MultiDriverTestClass { Adult adult = new Adult(null, 21); String json = objectMapper.writeValueAsString(adult); - mockMvc.perform( - post("/adults") - .contentType(MediaType.APPLICATION_JSON) - .content(json)) + mockMvc.perform(post("/adults").contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(status().isBadRequest()); } @@ -100,10 +88,7 @@ public class JSR303IT extends MultiDriverTestClass { Adult adult = new Adult("A", 21); String json = objectMapper.writeValueAsString(adult); - mockMvc.perform( - post("/adults") - .contentType(MediaType.APPLICATION_JSON) - .content(json)) + mockMvc.perform(post("/adults").contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(status().isBadRequest()); } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/WebConfiguration.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/WebConfiguration.java index 8c98cba83..50928dd99 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/WebConfiguration.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/WebConfiguration.java @@ -24,13 +24,13 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter * @author Vince Bickers */ @Configuration -@ComponentScan({"org.springframework.data.neo4j.examples.jsr303.controller"}) +@ComponentScan({ "org.springframework.data.neo4j.examples.jsr303.controller" }) @EnableWebMvc public class WebConfiguration extends WebMvcConfigurerAdapter { - @Bean(name="validator") - public LocalValidatorFactoryBean validator() { - return new LocalValidatorFactoryBean(); - } + @Bean(name = "validator") + public LocalValidatorFactoryBean validator() { + return new LocalValidatorFactoryBean(); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/controller/AdultController.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/controller/AdultController.java index 47640c8f1..b01af2160 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/controller/AdultController.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/controller/AdultController.java @@ -13,16 +13,21 @@ package org.springframework.data.neo4j.examples.jsr303.controller; +import javax.validation.Valid; +import javax.validation.ValidationException; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.neo4j.examples.jsr303.domain.Adult; import org.springframework.data.neo4j.examples.jsr303.service.AdultService; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.*; - -import javax.validation.Valid; -import javax.validation.ValidationException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; /** * @author Vince Bickers @@ -30,22 +35,21 @@ import javax.validation.ValidationException; @Controller public class AdultController { - @Autowired - private AdultService service; + @Autowired private AdultService service; - @RequestMapping(value = "/adults", method = RequestMethod.POST, consumes = "application/json") - @ResponseBody - public Adult create (@Valid @RequestBody Adult entity, BindingResult bindingResult) { - // in practice we'd do a bit more than this... - if (bindingResult.hasErrors()) { - throw new ValidationException("oops"); - } - return service.save(entity); - } + @RequestMapping(value = "/adults", method = RequestMethod.POST, consumes = "application/json") + @ResponseBody + public Adult create(@Valid @RequestBody Adult entity, BindingResult bindingResult) { + // in practice we'd do a bit more than this... + if (bindingResult.hasErrors()) { + throw new ValidationException("oops"); + } + return service.save(entity); + } - @ExceptionHandler(ValidationException.class) - @ResponseBody - @ResponseStatus(value = HttpStatus.BAD_REQUEST) - public void handleException(ValidationException ve) { } + @ExceptionHandler(ValidationException.class) + @ResponseBody + @ResponseStatus(value = HttpStatus.BAD_REQUEST) + public void handleException(ValidationException ve) {} } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/domain/Adult.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/domain/Adult.java index b2663d568..912f58353 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/domain/Adult.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/domain/Adult.java @@ -27,20 +27,15 @@ import org.neo4j.ogm.annotation.NodeEntity; @NodeEntity public class Adult { - @GraphId - private Long id; + @GraphId private Long id; - @NotNull @Size(min = 2, max = 50) - private String name; + @NotNull @Size(min = 2, max = 50) private String name; - @Min(18) - private Integer age; + @Min(18) private Integer age; - @AssertTrue - private boolean votingAge; + @AssertTrue private boolean votingAge; - public Adult() { - } + public Adult() {} public Adult(String name, Integer age) { this.name = name; @@ -48,7 +43,6 @@ public class Adult { this.votingAge = true; } - public String getName() { return name; } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/repo/AdultRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/repo/AdultRepository.java index 3b1bcbbe4..58d98374d 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/repo/AdultRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/repo/AdultRepository.java @@ -21,5 +21,4 @@ import org.springframework.stereotype.Repository; * @author Vince Bickers */ @Repository -public interface AdultRepository extends Neo4jRepository { -} +public interface AdultRepository extends Neo4jRepository {} diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/service/AdultService.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/service/AdultService.java index d2e2d496c..0f9426253 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/service/AdultService.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/jsr303/service/AdultService.java @@ -24,10 +24,9 @@ import org.springframework.stereotype.Service; @Service public class AdultService { - @Autowired - private AdultRepository repository; + @Autowired private AdultRepository repository; - public Adult save(Adult adult) { - return repository.save(adult); - } + public Adult save(Adult adult) { + return repository.save(adult); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/MoviesIntegrationIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/MoviesIntegrationIT.java index 64744e0ee..42c2154eb 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/MoviesIntegrationIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/MoviesIntegrationIT.java @@ -15,14 +15,18 @@ package org.springframework.data.neo4j.examples.movies; import static org.junit.Assert.*; import static org.neo4j.ogm.testutil.GraphTestUtils.*; -import static org.springframework.data.repository.query.parser.Part.Type.*; -import java.util.*; +import java.util.Arrays; +import java.util.Calendar; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.TimeZone; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.apache.commons.lang.ArrayUtils; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; @@ -38,8 +42,20 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.data.neo4j.examples.movies.context.MoviesContext; -import org.springframework.data.neo4j.examples.movies.domain.*; -import org.springframework.data.neo4j.examples.movies.repo.*; +import org.springframework.data.neo4j.examples.movies.domain.Actor; +import org.springframework.data.neo4j.examples.movies.domain.Cinema; +import org.springframework.data.neo4j.examples.movies.domain.Genre; +import org.springframework.data.neo4j.examples.movies.domain.Movie; +import org.springframework.data.neo4j.examples.movies.domain.ReleasedMovie; +import org.springframework.data.neo4j.examples.movies.domain.TempMovie; +import org.springframework.data.neo4j.examples.movies.domain.User; +import org.springframework.data.neo4j.examples.movies.repo.AbstractAnnotatedEntityRepository; +import org.springframework.data.neo4j.examples.movies.repo.AbstractEntityRepository; +import org.springframework.data.neo4j.examples.movies.repo.ActorRepository; +import org.springframework.data.neo4j.examples.movies.repo.CinemaRepository; +import org.springframework.data.neo4j.examples.movies.repo.RatingRepository; +import org.springframework.data.neo4j.examples.movies.repo.TempMovieRepository; +import org.springframework.data.neo4j.examples.movies.repo.UserRepository; import org.springframework.data.neo4j.examples.movies.service.UserService; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -54,7 +70,7 @@ import org.springframework.transaction.support.TransactionTemplate; * @author Vince Bickers * @author Mark Angrish */ -@ContextConfiguration(classes = {MoviesContext.class}) +@ContextConfiguration(classes = { MoviesContext.class }) @RunWith(SpringJUnit4ClassRunner.class) public class MoviesIntegrationIT extends MultiDriverTestClass { @@ -62,26 +78,16 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { private static GraphDatabaseService graphDatabaseService; - @Autowired - PlatformTransactionManager platformTransactionManager; - @Autowired - private Session session; - @Autowired - private UserRepository userRepository; - @Autowired - private UserService userService; - @Autowired - private CinemaRepository cinemaRepository; - @Autowired - private AbstractAnnotatedEntityRepository abstractAnnotatedEntityRepository; - @Autowired - private AbstractEntityRepository abstractEntityRepository; - @Autowired - private TempMovieRepository tempMovieRepository; - @Autowired - private ActorRepository actorRepository; - @Autowired - private RatingRepository ratingRepository; + @Autowired PlatformTransactionManager platformTransactionManager; + @Autowired private Session session; + @Autowired private UserRepository userRepository; + @Autowired private UserService userService; + @Autowired private CinemaRepository cinemaRepository; + @Autowired private AbstractAnnotatedEntityRepository abstractAnnotatedEntityRepository; + @Autowired private AbstractEntityRepository abstractEntityRepository; + @Autowired private TempMovieRepository tempMovieRepository; + @Autowired private ActorRepository actorRepository; + @Autowired private RatingRepository ratingRepository; private TransactionTemplate transactionTemplate; @@ -112,7 +118,6 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { assertSameGraph(graphDatabaseService, "CREATE (u:User:Person)"); } - @Test public void shouldSaveReleasedMovie() { @@ -125,8 +130,8 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { abstractAnnotatedEntityRepository.save(releasedMovie); assertSameGraph(graphDatabaseService, - "CREATE (m:ReleasedMovie:AbstractAnnotatedEntity {cinemaRelease:'1994-09-10T00:00:00.000Z'," + - "cannesRelease:768700800000,title:'Pulp Fiction'})"); + "CREATE (m:ReleasedMovie:AbstractAnnotatedEntity {cinemaRelease:'1994-09-10T00:00:00.000Z'," + + "cannesRelease:768700800000,title:'Pulp Fiction'})"); } @Test @@ -146,14 +151,14 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { public void shouldSaveMovie() { Movie movie = new Movie("Pulp Fiction"); - movie.setTags(new String[]{"cool", "classic"}); - movie.setImage(new byte[]{1, 2, 3}); + movie.setTags(new String[] { "cool", "classic" }); + movie.setImage(new byte[] { 1, 2, 3 }); abstractEntityRepository.save(movie); // byte arrays have to be transferred with a JSON-supported format. Base64 is the default. - assertSameGraph(graphDatabaseService, "CREATE (m:Movie {name:'Pulp Fiction', tags:['cool','classic'], " + - "image:'AQID'})"); + assertSameGraph(graphDatabaseService, + "CREATE (m:Movie {name:'Pulp Fiction', tags:['cool','classic'], " + "image:'AQID'})"); } @Test @@ -171,12 +176,10 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { } }); - assertSameGraph(graphDatabaseService, "CREATE (:User:Person {name:'Michal'})," + - "(:User:Person {name:'Vince'})," + - "(:User:Person {name:'Adam'})"); + assertSameGraph(graphDatabaseService, + "CREATE (:User:Person {name:'Michal'})," + "(:User:Person {name:'Vince'})," + "(:User:Person {name:'Adam'})"); } - @Test public void shouldSaveUsers2() { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @@ -192,9 +195,8 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { } }); - assertSameGraph(graphDatabaseService, "CREATE (:User:Person {name:'Michal'})," + - "(:User:Person {name:'Vince'})," + - "(:User:Person {name:'Adam'})"); + assertSameGraph(graphDatabaseService, + "CREATE (:User:Person {name:'Michal'})," + "(:User:Person {name:'Vince'})," + "(:User:Person {name:'Adam'})"); } @Test @@ -211,16 +213,15 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { assertSameGraph(graphDatabaseService, "CREATE (u:User:Person {name:'Adam'})"); } - @Test - @Ignore // FIXME + @Ignore // FIXME // this test expects the session/tx to check for dirty objects, which it currently does not do // you must save objects explicitly. public void shouldUpdateUserUsingTransactionalService() { User user = new User("Michal"); userRepository.save(user); - userService.updateUser(user, "Adam"); //notice userRepository.save(..) isn't called, + userService.updateUser(user, "Adam"); // notice userRepository.save(..) isn't called, // not even in the service impl! assertSameGraph(graphDatabaseService, "CREATE (u:User {name:'Adam'})"); @@ -292,7 +293,6 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { } } - @Test public void shouldHandleMultipleConcurrentRequests() throws InterruptedException, Neo4jFailedToStartException { @@ -319,7 +319,8 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { @Test(expected = DataAccessException.class) public void shouldInterceptOGMExceptions() { - ratingRepository.findAll(0); // ratings are REs and must be found to at least depth 1 in order to get the start and end nodes + ratingRepository.findAll(0); // ratings are REs and must be found to at least depth 1 in order to get the start and + // end nodes } @Test @@ -329,7 +330,8 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { userRepository.save(user); - assertSameGraph(graphDatabaseService, "CREATE (u:User:Person {name:'Michal'})-[:INTERESTED]->(g:Genre {name:'Drama'})"); + assertSameGraph(graphDatabaseService, + "CREATE (u:User:Person {name:'Michal'})-[:INTERESTED]->(g:Genre {name:'Drama'})"); } @Test @@ -341,14 +343,10 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { userRepository.save(user); - assertSameGraph(graphDatabaseService, "CREATE " + - "(u:User:Person {name:'Michal'})," + - "(g1:Genre {name:'Drama'})," + - "(g2:Genre {name:'Historical'})," + - "(g3:Genre {name:'Thriller'})," + - "(u)-[:INTERESTED]->(g1)," + - "(u)-[:INTERESTED]->(g2)," + - "(u)-[:INTERESTED]->(g3)"); + assertSameGraph(graphDatabaseService, + "CREATE " + "(u:User:Person {name:'Michal'})," + "(g1:Genre {name:'Drama'})," + + "(g2:Genre {name:'Historical'})," + "(g3:Genre {name:'Thriller'})," + "(u)-[:INTERESTED]->(g1)," + + "(u)-[:INTERESTED]->(g2)," + "(u)-[:INTERESTED]->(g3)"); } @Test @@ -358,7 +356,8 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { userRepository.save(user, 1); - assertSameGraph(graphDatabaseService, "CREATE (u:User:Person {name:'Michal'})-[:INTERESTED]->(g:Genre {name:'Drama'})"); + assertSameGraph(graphDatabaseService, + "CREATE (u:User:Person {name:'Michal'})-[:INTERESTED]->(g:Genre {name:'Drama'})"); } @Test @@ -379,15 +378,11 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { } }); - assertSameGraph(graphDatabaseService, "CREATE " + - "(m:User:Person {name:'Michal'})," + - "(v:User:Person {name:'Vince'})," + - "(g:Genre {name:'Drama'})," + - "(m)-[:INTERESTED]->(g)," + - "(v)-[:INTERESTED]->(g)"); + assertSameGraph(graphDatabaseService, + "CREATE " + "(m:User:Person {name:'Michal'})," + "(v:User:Person {name:'Vince'})," + "(g:Genre {name:'Drama'})," + + "(m)-[:INTERESTED]->(g)," + "(v)-[:INTERESTED]->(g)"); } - @Test public void shouldSaveUserButNotGenre() { User user = new User("Michal"); @@ -416,13 +411,10 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { } }); - assertSameGraph(graphDatabaseService, "CREATE " + - "(m:User:Person {name:'Michal'})," + - "(g:Genre {name:'New Drama'})," + - "(m)-[:INTERESTED]->(g)"); + assertSameGraph(graphDatabaseService, + "CREATE " + "(m:User:Person {name:'Michal'})," + "(g:Genre {name:'New Drama'})," + "(m)-[:INTERESTED]->(g)"); } - @Test public void shouldRemoveGenreFromUser() { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @@ -440,9 +432,7 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { } }); - assertSameGraph(graphDatabaseService, "CREATE " + - "(m:User:Person {name:'Michal'})," + - "(g:Genre {name:'Drama'})"); + assertSameGraph(graphDatabaseService, "CREATE " + "(m:User:Person {name:'Michal'})," + "(g:Genre {name:'Drama'})"); } @Test @@ -460,12 +450,9 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { } }); - assertSameGraph(graphDatabaseService, "CREATE " + - "(m:User:Person {name:'Michal'})," + - "(g:Genre {name:'Drama'})"); + assertSameGraph(graphDatabaseService, "CREATE " + "(m:User:Person {name:'Michal'})," + "(g:Genre {name:'Drama'})"); } - @Test public void shouldAddNewVisitorToCinema() { Cinema cinema = new Cinema("Odeon"); @@ -473,10 +460,8 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { cinemaRepository.save(cinema); - assertSameGraph(graphDatabaseService, "CREATE " + - "(m:User:Person {name:'Michal'})," + - "(c:Theatre {name:'Odeon', capacity:0})," + - "(m)-[:VISITED]->(c)"); + assertSameGraph(graphDatabaseService, "CREATE " + "(m:User:Person {name:'Michal'})," + + "(c:Theatre {name:'Odeon', capacity:0})," + "(m)-[:VISITED]->(c)"); } @Test @@ -494,10 +479,8 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { } }); - assertSameGraph(graphDatabaseService, "CREATE " + - "(m:User:Person {name:'Michal'})," + - "(c:Theatre {name:'Odeon', capacity:0})," + - "(m)-[:VISITED]->(c)"); + assertSameGraph(graphDatabaseService, "CREATE " + "(m:User:Person {name:'Michal'})," + + "(c:Theatre {name:'Odeon', capacity:0})," + "(m)-[:VISITED]->(c)"); } @Test @@ -512,9 +495,11 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { }); try { - assertSameGraph(graphDatabaseService, "CREATE (m:User {name:'Michal'})-[:FRIEND_OF]->(a:User:Person {name:'Adam'})"); + assertSameGraph(graphDatabaseService, + "CREATE (m:User {name:'Michal'})-[:FRIEND_OF]->(a:User:Person {name:'Adam'})"); } catch (AssertionError error) { - assertSameGraph(graphDatabaseService, "CREATE (m:User:Person {name:'Michal'})<-[:FRIEND_OF]-(a:User:Person {name:'Adam'})"); + assertSameGraph(graphDatabaseService, + "CREATE (m:User:Person {name:'Michal'})<-[:FRIEND_OF]-(a:User:Person {name:'Adam'})"); } } @@ -559,8 +544,8 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { User michal = ((Iterable) findByProperty(User.class, "name", "Michal")).iterator().next(); - assertSameGraph(graphDatabaseService, "CREATE (u:User:Person {name:'Michal'})-[:RATED {stars:5, " + - "comment:'Best movie ever', ratingTimestamp:0}]->(m:Movie {name:'Pulp Fiction'})"); + assertSameGraph(graphDatabaseService, "CREATE (u:User:Person {name:'Michal'})-[:RATED {stars:5, " + + "comment:'Best movie ever', ratingTimestamp:0}]->(m:Movie {name:'Pulp Fiction'})"); } @Test @@ -570,15 +555,16 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { @Override public void doInTransactionWithoutResult(TransactionStatus status) { TempMovie movie = new TempMovie("Pulp Fiction"); - //Save the movie + // Save the movie movie = tempMovieRepository.save(movie); - //Create a new user and rate an existing movie + // Create a new user and rate an existing movie User user = new User("Michal"); user.rate(movie, 5, "Best movie ever"); userRepository.save(user); - TempMovie tempMovie = ((Iterable) findByProperty(TempMovie.class, "name", "Pulp Fiction")).iterator().next(); + TempMovie tempMovie = ((Iterable) findByProperty(TempMovie.class, "name", "Pulp Fiction")).iterator() + .next(); assertEquals(1, tempMovie.getRatings().size()); } }); @@ -594,10 +580,10 @@ public class MoviesIntegrationIT extends MultiDriverTestClass { @Override public void doInTransactionWithoutResult(TransactionStatus status) { TempMovie movie = new TempMovie("Pulp Fiction"); - //Save the movie + // Save the movie movie = tempMovieRepository.save(movie); - //Create a new user and rate an existing movie + // Create a new user and rate an existing movie User user = new User("Michal"); user.rate(movie, 5, "Best movie ever"); userRepository.save(user); diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/context/MoviesContext.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/context/MoviesContext.java index 47cf1160c..d8174dc5b 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/context/MoviesContext.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/context/MoviesContext.java @@ -27,7 +27,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; * @author Mark Angrish */ @Configuration -@ComponentScan({"org.springframework.data.neo4j.examples.movies.service"}) +@ComponentScan({ "org.springframework.data.neo4j.examples.movies.service" }) @EnableNeo4jRepositories("org.springframework.data.neo4j.examples.movies.repo") @EnableTransactionManagement public class MoviesContext { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/AbstractAnnotatedEntity.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/AbstractAnnotatedEntity.java index 6e876fb24..e0b94c38e 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/AbstractAnnotatedEntity.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/AbstractAnnotatedEntity.java @@ -22,6 +22,5 @@ import org.neo4j.ogm.annotation.NodeEntity; @NodeEntity public abstract class AbstractAnnotatedEntity { - @GraphId - Long nodeId; + @GraphId Long nodeId; } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/AbstractEntity.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/AbstractEntity.java index 720fbc62a..01dae19b7 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/AbstractEntity.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/AbstractEntity.java @@ -19,9 +19,9 @@ package org.springframework.data.neo4j.examples.movies.domain; */ public abstract class AbstractEntity { - Long id; + Long id; - public Long getId() { - return id; - } + public Long getId() { + return id; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Actor.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Actor.java index f4b5279dc..e2a255535 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Actor.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Actor.java @@ -13,40 +13,37 @@ package org.springframework.data.neo4j.examples.movies.domain; - import org.neo4j.ogm.annotation.GraphId; /** * @author Michal Bachman */ -public class Actor{ +public class Actor { - @GraphId - Long nodeId; - String id; - String name; + @GraphId Long nodeId; + String id; + String name; - public Actor() { - } + public Actor() {} - public Actor(String id, String name) { - this.id = id; - this.name = name; - } + public Actor(String id, String name) { + this.id = id; + this.name = name; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Cinema.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Cinema.java index 22e1270fb..ca26dabfc 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Cinema.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Cinema.java @@ -13,13 +13,13 @@ package org.springframework.data.neo4j.examples.movies.domain; +import java.util.HashSet; +import java.util.Set; + import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Property; import org.neo4j.ogm.annotation.Relationship; -import java.util.HashSet; -import java.util.Set; - /** * @author Michal Bachman * @author Luanne Misquitta @@ -31,19 +31,15 @@ public class Cinema { private Long id; private String name; - @Property(name = "city") - private String location; + @Property(name = "city") private String location; - @Relationship(type = "VISITED", direction = Relationship.INCOMING) - private Set visited = new HashSet<>(); + @Relationship(type = "VISITED", direction = Relationship.INCOMING) private Set visited = new HashSet<>(); - @Relationship(type = "BLOCKBUSTER", direction = Relationship.OUTGOING) - private TempMovie blockbusterOfTheWeek; + @Relationship(type = "BLOCKBUSTER", direction = Relationship.OUTGOING) private TempMovie blockbusterOfTheWeek; private int capacity; - public Cinema() { - } + public Cinema() {} public Cinema(String name) { this.name = name; @@ -93,8 +89,10 @@ public class Cinema { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Cinema cinema = (Cinema) o; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Director.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Director.java index 43c2132a6..0cc40f313 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Director.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Director.java @@ -20,6 +20,5 @@ public class Director extends Person { private Long id; - public Director() { - } + public Director() {} } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Genre.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Genre.java index 9364131be..93e2f73a0 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Genre.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Genre.java @@ -18,25 +18,24 @@ package org.springframework.data.neo4j.examples.movies.domain; */ public class Genre { - private Long id; - private String name; + private Long id; + private String name; - public Genre() { - } + public Genre() {} - public Genre(String name) { - this.name = name; - } + public Genre(String name) { + this.name = name; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Movie.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Movie.java index 9cbe2a6ec..e89b093a3 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Movie.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Movie.java @@ -18,34 +18,33 @@ package org.springframework.data.neo4j.examples.movies.domain; */ public class Movie extends AbstractEntity { - private String name; - private String[] tags; - private byte[] image; + private String name; + private String[] tags; + private byte[] image; - public Movie() { - } + public Movie() {} - public Movie(String name) { - this.name = name; - } + public Movie(String name) { + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String[] getTags() { - return tags; - } + public String[] getTags() { + return tags; + } - public void setTags(String[] tags) { - this.tags = tags; - } + public void setTags(String[] tags) { + this.tags = tags; + } - public byte[] getImage() { - return image; - } + public byte[] getImage() { + return image; + } - public void setImage(byte[] image) { - this.image = image; - } + public void setImage(byte[] image) { + this.image = image; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Person.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Person.java index e17d39cfc..f09dd5ad1 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Person.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Person.java @@ -21,7 +21,6 @@ public class Person { private String name; - public String getName() { return name; } @@ -36,8 +35,10 @@ public class Person { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Person person = (Person) o; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Rating.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Rating.java index fb5aca2e3..d85c741ea 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Rating.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/Rating.java @@ -21,77 +21,75 @@ import org.neo4j.ogm.annotation.StartNode; * @author Michal Bachman */ @RelationshipEntity(type = "RATED") -public class Rating implements Comparable{ - private Long id; +public class Rating implements Comparable { + private Long id; - @StartNode - private User user; - @EndNode - private TempMovie movie; - private int stars; - private String comment; + @StartNode private User user; + @EndNode private TempMovie movie; + private int stars; + private String comment; - private long ratingTimestamp; + private long ratingTimestamp; - public Rating() {} + public Rating() {} - public Rating(User user, TempMovie movie, int stars, String comment) { - this.user = user; - this.movie = movie; - this.stars = stars; - this.comment = comment; - } + public Rating(User user, TempMovie movie, int stars, String comment) { + this.user = user; + this.movie = movie; + this.stars = stars; + this.comment = comment; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setUser(User user) { - this.user = user; - } + public void setUser(User user) { + this.user = user; + } - public void setMovie(TempMovie movie) { - this.movie = movie; - } + public void setMovie(TempMovie movie) { + this.movie = movie; + } - public void setStars(int stars) { - this.stars = stars; - } + public void setStars(int stars) { + this.stars = stars; + } - public void setComment(String comment) { - this.comment = comment; - } + public void setComment(String comment) { + this.comment = comment; + } - public User getUser() { - return user; - } + public User getUser() { + return user; + } - public TempMovie getMovie() { - return movie; - } + public TempMovie getMovie() { + return movie; + } - public int getStars() { - return stars; - } + public int getStars() { + return stars; + } - public String getComment() { - return comment; - } + public String getComment() { + return comment; + } - public long getRatingTimestamp() { - return ratingTimestamp; - } + public long getRatingTimestamp() { + return ratingTimestamp; + } - public void setRatingTimestamp(long ratingTimestamp) { - this.ratingTimestamp = ratingTimestamp; - } + public void setRatingTimestamp(long ratingTimestamp) { + this.ratingTimestamp = ratingTimestamp; + } - @Override - public int compareTo(Object o) { - Rating other = (Rating) o; - if (stars == ((Rating) o).getStars()) { - return getUser().getName().compareTo(other.getUser().getName()); - } - return stars - other.getStars(); - } + @Override + public int compareTo(Object o) { + Rating other = (Rating) o; + if (stars == ((Rating) o).getStars()) { + return getUser().getName().compareTo(other.getUser().getName()); + } + return stars - other.getStars(); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/ReleasedMovie.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/ReleasedMovie.java index 8221b90b3..0156c3a3e 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/ReleasedMovie.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/ReleasedMovie.java @@ -13,43 +13,40 @@ package org.springframework.data.neo4j.examples.movies.domain; +import java.util.Date; + import org.neo4j.ogm.annotation.Property; import org.neo4j.ogm.annotation.typeconversion.DateLong; -import java.util.Date; - /** * @author Michal Bachman */ -//the fields here will move to Movie, this separate class exists temporarily after its tests pass +// the fields here will move to Movie, this separate class exists temporarily after its tests pass public class ReleasedMovie extends AbstractAnnotatedEntity { - private String title; + private String title; - @Property(name = "cinemaRelease") - private Date released; + @Property(name = "cinemaRelease") private Date released; - @DateLong - private Date cannesRelease; + @DateLong private Date cannesRelease; - public ReleasedMovie() { - } + public ReleasedMovie() {} - public ReleasedMovie(String title, Date released, Date cannesRelease) { - this.title = title; - this.released = released; - this.cannesRelease = cannesRelease; - } + public ReleasedMovie(String title, Date released, Date cannesRelease) { + this.title = title; + this.released = released; + this.cannesRelease = cannesRelease; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public Date getReleased() { - return released; - } + public Date getReleased() { + return released; + } - public Date getCannesRelease() { - return cannesRelease; - } + public Date getCannesRelease() { + return cannesRelease; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/TempMovie.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/TempMovie.java index 973e751d8..c7a3bd768 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/TempMovie.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/TempMovie.java @@ -13,40 +13,38 @@ package org.springframework.data.neo4j.examples.movies.domain; -import org.neo4j.ogm.annotation.NodeEntity; -import org.neo4j.ogm.annotation.Relationship; - import java.util.HashSet; import java.util.Set; +import org.neo4j.ogm.annotation.NodeEntity; +import org.neo4j.ogm.annotation.Relationship; + /** * @author Michal Bachman * @author Luanne Misquitta */ -//todo merge with movie when tests fixed +// todo merge with movie when tests fixed @NodeEntity(label = "Movie") public class TempMovie extends AbstractEntity { - private String name; - @Relationship(type = "RATED", direction = Relationship.INCOMING) - private Set ratings = new HashSet<>(); + private String name; + @Relationship(type = "RATED", direction = Relationship.INCOMING) private Set ratings = new HashSet<>(); - public TempMovie() { - } + public TempMovie() {} - public TempMovie(String name) { - this.name = name; - } + public TempMovie(String name) { + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void addRating(Rating rating) { - ratings.add(rating); - } + public void addRating(Rating rating) { + ratings.add(rating); + } - public Set getRatings() { - return ratings; - } + public Set getRatings() { + return ratings; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/User.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/User.java index 9fe180750..4c2ec0b4d 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/User.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/User.java @@ -13,80 +13,76 @@ package org.springframework.data.neo4j.examples.movies.domain; -import org.neo4j.ogm.annotation.Relationship; - import java.util.Collection; import java.util.HashSet; import java.util.Set; +import org.neo4j.ogm.annotation.Relationship; + /** * @author Michal Bachman * @author Luanne Misquitta */ -public class User extends Person{ +public class User extends Person { - private String middleName; - private String surname; + private String middleName; + private String surname; - private Collection interested = new HashSet<>(); + private Collection interested = new HashSet<>(); - @Relationship(type = "FRIEND_OF", direction = Relationship.UNDIRECTED) - private Collection friends = new HashSet<>(); + @Relationship(type = "FRIEND_OF", + direction = Relationship.UNDIRECTED) private Collection friends = new HashSet<>(); - @Relationship(type = "RATED") - private Set ratings = new HashSet<>(); + @Relationship(type = "RATED") private Set ratings = new HashSet<>(); - public User() { - } + public User() {} - public User(String name) { - setName(name); - } + public User(String name) { + setName(name); + } - public User(String name, String surname) { - setName(name); - this.surname = surname; - } + public User(String name, String surname) { + setName(name); + this.surname = surname; + } - public void interestedIn(Genre genre) { - interested.add(genre); - } + public void interestedIn(Genre genre) { + interested.add(genre); + } - public void notInterestedIn(Genre genre) { - interested.remove(genre); - } + public void notInterestedIn(Genre genre) { + interested.remove(genre); + } - public void befriend(User user) { - friends.add(user); - user.friends.add(this); - } + public void befriend(User user) { + friends.add(user); + user.friends.add(this); + } + public Rating rate(TempMovie movie, int stars, String comment) { + Rating rating = new Rating(this, movie, stars, comment); + movie.addRating(rating); + ratings.add(rating); + return rating; + } - public Rating rate(TempMovie movie, int stars, String comment) { - Rating rating = new Rating(this, movie, stars, comment); - movie.addRating(rating); - ratings.add(rating); - return rating; - } + public Collection getFriends() { + return friends; + } - public Collection getFriends() { - return friends; - } + public String getMiddleName() { + return middleName; + } - public String getMiddleName() - { - return middleName; - } + public Set getRatings() { + return ratings; + } - public Set getRatings() { - return ratings; - } + public void setMiddleName(String middleName) { + this.middleName = middleName; + } - public void setMiddleName(String middleName) { - this.middleName = middleName; - } - - public String getSurname() { - return surname; - } + public String getSurname() { + return surname; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResult.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResult.java index 65eb1a1d1..cdbcb5f46 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResult.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResult.java @@ -23,25 +23,24 @@ import org.springframework.data.neo4j.annotation.QueryResult; @QueryResult public class CinemaQueryResult { - private Long id; - private String name; + private Long id; + private String name; - public CinemaQueryResult() { - } + public CinemaQueryResult() {} - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResultInterface.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResultInterface.java index 425c82bd4..0d477540e 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResultInterface.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResultInterface.java @@ -23,12 +23,12 @@ import org.springframework.data.neo4j.annotation.QueryResult; @QueryResult public interface CinemaQueryResultInterface { - Long getId(); + Long getId(); - void setId(Long id); + void setId(Long id); - String getName(); + String getName(); - void setName(String name); + void setName(String name); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResultInterfaceImpl.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResultInterfaceImpl.java index 1e834c2de..6ab35b6f8 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResultInterfaceImpl.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/CinemaQueryResultInterfaceImpl.java @@ -21,8 +21,7 @@ public class CinemaQueryResultInterfaceImpl implements CinemaQueryResultInterfac private Long id; private String name; - public CinemaQueryResultInterfaceImpl() { - } + public CinemaQueryResultInterfaceImpl() {} public Long getId() { return id; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/EntityWrappingQueryResult.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/EntityWrappingQueryResult.java index 0d25aab29..3847935e1 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/EntityWrappingQueryResult.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/EntityWrappingQueryResult.java @@ -31,41 +31,40 @@ import org.springframework.data.neo4j.examples.movies.domain.User; @QueryResult public class EntityWrappingQueryResult { - private User user; - private Set friends; - private List ratings; - private TempMovie[] movies; - private float avgRating; - private List allRatings; - private Collection> literalMap; + private User user; + private Set friends; + private List ratings; + private TempMovie[] movies; + private float avgRating; + private List allRatings; + private Collection> literalMap; + public User getUser() { + return user; + } - public User getUser() { - return user; - } + public Set getFriends() { + return friends; + } - public Set getFriends() { - return friends; - } + public List getRatings() { + return ratings; + } - public List getRatings() { - return ratings; - } + public float getAvgRating() { + return avgRating; + } - public float getAvgRating() { - return avgRating; - } + public TempMovie[] getMovies() { + return movies; + } - public TempMovie[] getMovies() { - return movies; - } + public List getAllRatings() { + return allRatings; + } - public List getAllRatings() { - return allRatings; - } - - public Collection> getLiteralMap() { - return literalMap; - } + public Collection> getLiteralMap() { + return literalMap; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/Gender.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/Gender.java index 0ef66441c..d754fc84e 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/Gender.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/Gender.java @@ -15,6 +15,6 @@ package org.springframework.data.neo4j.examples.movies.domain.queryresult; public enum Gender { - FEMALE, MALE; + FEMALE, MALE; } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/RichUserQueryResult.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/RichUserQueryResult.java index 448326d74..4af6b7d7f 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/RichUserQueryResult.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/RichUserQueryResult.java @@ -13,11 +13,11 @@ package org.springframework.data.neo4j.examples.movies.domain.queryresult; -import org.springframework.data.neo4j.annotation.QueryResult; - import java.math.BigDecimal; import java.math.BigInteger; +import org.springframework.data.neo4j.annotation.QueryResult; + /** * A {@link QueryResult} that contains rich types. * @@ -27,24 +27,24 @@ import java.math.BigInteger; @QueryResult public class RichUserQueryResult { - private Gender userGender; // should be handled by default type conversion - private String userName; - private BigInteger userAccount; - private BigDecimal[] userDeposits; + private Gender userGender; // should be handled by default type conversion + private String userName; + private BigInteger userAccount; + private BigDecimal[] userDeposits; - public Gender getUserGender() { - return userGender; - } + public Gender getUserGender() { + return userGender; + } - public String getUserName() { - return userName; - } + public String getUserName() { + return userName; + } - public BigInteger getUserAccount() { - return userAccount; - } + public BigInteger getUserAccount() { + return userAccount; + } - public BigDecimal[] getUserDeposits() { - return userDeposits; - } -} \ No newline at end of file + public BigDecimal[] getUserDeposits() { + return userDeposits; + } +} diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/UserQueryResult.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/UserQueryResult.java index 0e9311781..1da9c8db8 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/UserQueryResult.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/UserQueryResult.java @@ -19,93 +19,91 @@ import org.springframework.data.neo4j.annotation.QueryResult; import org.springframework.data.neo4j.examples.movies.repo.UserRepository; /** - * Example POJO {@link QueryResult} to test mapping onto arbitrary objects, even for properties that are on the nodes but not in - * the entity classes. + * Example POJO {@link QueryResult} to test mapping onto arbitrary objects, even for properties that are on the nodes + * but not in the entity classes. * * @see UserRepository - * * @author Adam George * @author Luanne Misquitta */ @QueryResult public class UserQueryResult { - private Long id; - Long userId; - private String userName; - private int age; + private Long id; + Long userId; + private String userName; + private int age; - UserQueryResult() { - // default constructor for OGM - } + UserQueryResult() { + // default constructor for OGM + } - public UserQueryResult(String name, int age) { - this.userName = name; - this.age = age; - } + public UserQueryResult(String name, int age) { + this.userName = name; + this.age = age; + } - public String getUserName() { - return userName; - } + public String getUserName() { + return userName; + } - public void setUserName(String name) { - this.userName = name; - } + public void setUserName(String name) { + this.userName = name; + } - @Property(name = "user.age") - public int getAge() { - return age; - } + @Property(name = "user.age") + public int getAge() { + return age; + } - @Property(name = "user.age") - public void setAge(int age) { - this.age = age; - } + @Property(name = "user.age") + public void setAge(int age) { + this.age = age; + } - public Long getUserId() { - return userId; - } + public Long getUserId() { + return userId; + } + public Long getId() { + return id; + } - public Long getId() { - return id; - } + public void setId(Long id) { + this.id = id; + } - public void setId(Long id) { - this.id = id; - } + @Override + public int hashCode() { + final int prime = 23; + int result = 1; + result = prime * result + age; + result = prime * result + ((userName == null) ? 0 : userName.hashCode()); + return result; + } - @Override - public int hashCode() { - final int prime = 23; - int result = 1; - result = prime * result + age; - result = prime * result + ((userName == null) ? 0 : userName.hashCode()); - return result; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + UserQueryResult other = (UserQueryResult) obj; + if (age != other.age) + return false; + if (userName == null) { + if (other.userName != null) + return false; + } else if (!userName.equals(other.userName)) + return false; + return true; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - UserQueryResult other = (UserQueryResult) obj; - if (age != other.age) - return false; - if (userName == null) { - if (other.userName != null) - return false; - } else if (!userName.equals(other.userName)) - return false; - return true; - } - - @Override - public String toString() { - return ReflectionToStringBuilder.toString(this); - } + @Override + public String toString() { + return ReflectionToStringBuilder.toString(this); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/UserQueryResultInterface.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/UserQueryResultInterface.java index c8a763872..830649eae 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/UserQueryResultInterface.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/domain/queryresult/UserQueryResultInterface.java @@ -19,19 +19,19 @@ import org.springframework.data.neo4j.examples.movies.domain.User; import org.springframework.data.neo4j.examples.movies.repo.UserRepository; /** - * Example interface annotated with {@link QueryResult} to test mapping onto proxied objects, where only getter methods are - * needed to define the mapped result columns. + * Example interface annotated with {@link QueryResult} to test mapping onto proxied objects, where only getter methods + * are needed to define the mapped result columns. * * @see UserRepository */ @QueryResult public interface UserQueryResultInterface { - @Property(name = "user.name") - String getNameOfUser(); + @Property(name = "user.name") + String getNameOfUser(); - int getAgeOfUser(); + int getAgeOfUser(); - User getUser(); + User getUser(); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/AbstractAnnotatedEntityRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/AbstractAnnotatedEntityRepository.java index ff3da1967..d8873d6eb 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/AbstractAnnotatedEntityRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/AbstractAnnotatedEntityRepository.java @@ -21,5 +21,4 @@ import org.springframework.stereotype.Repository; * @author Michal Bachman */ @Repository -public interface AbstractAnnotatedEntityRepository extends Neo4jRepository { -} +public interface AbstractAnnotatedEntityRepository extends Neo4jRepository {} diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/AbstractEntityRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/AbstractEntityRepository.java index ca4534a27..8a4d5aa09 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/AbstractEntityRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/AbstractEntityRepository.java @@ -21,5 +21,4 @@ import org.springframework.stereotype.Repository; * @author Michal Bachman */ @Repository -public interface AbstractEntityRepository extends Neo4jRepository { -} +public interface AbstractEntityRepository extends Neo4jRepository {} diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/ActorRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/ActorRepository.java index a095b317f..08ba563ce 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/ActorRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/ActorRepository.java @@ -16,10 +16,7 @@ package org.springframework.data.neo4j.examples.movies.repo; import org.springframework.data.neo4j.examples.movies.domain.Actor; import org.springframework.data.neo4j.repository.Neo4jRepository; - /** * @author Michal Bachman */ -public interface ActorRepository extends Neo4jRepository { -} - +public interface ActorRepository extends Neo4jRepository {} diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/CinemaRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/CinemaRepository.java index 020556ca1..a02bb3e7f 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/CinemaRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/CinemaRepository.java @@ -93,7 +93,8 @@ public interface CinemaRepository extends Neo4jRepository { @Query(value = "MATCH (n:Theatre) RETURN n ORDER BY n.name", countQuery = "MATCH (n:Theatre) return count(*)") Page getPagedCinemasWithPageCount(Pageable pageable); - @Query(value = "MATCH (n:Theatre {city:{city}}) RETURN n ORDER BY n.name", countQuery = "MATCH (n:Theatre {city:{city}}) return count(*)") + @Query(value = "MATCH (n:Theatre {city:{city}}) RETURN n ORDER BY n.name", + countQuery = "MATCH (n:Theatre {city:{city}}) return count(*)") Page getPagedCinemasByCityWithPageCount(@Param("city") String city, Pageable pageable); @Query("MATCH (n:Theatre) RETURN n") diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/GenreRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/GenreRepository.java index 941064998..02906e82e 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/GenreRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/GenreRepository.java @@ -21,5 +21,4 @@ import org.springframework.stereotype.Repository; * @author Michal Bachman */ @Repository -public interface GenreRepository extends Neo4jRepository { -} +public interface GenreRepository extends Neo4jRepository {} diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/TempMovieRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/TempMovieRepository.java index b798bbe14..075de1fdc 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/TempMovieRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/TempMovieRepository.java @@ -19,5 +19,4 @@ import org.springframework.data.neo4j.repository.Neo4jRepository; /** * @author Michal Bachman */ -public interface TempMovieRepository extends Neo4jRepository { -} +public interface TempMovieRepository extends Neo4jRepository {} diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/UnmanagedUserPojo.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/UnmanagedUserPojo.java index 861c0e83b..e0bf0628c 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/UnmanagedUserPojo.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/UnmanagedUserPojo.java @@ -21,14 +21,14 @@ import org.springframework.data.neo4j.annotation.QueryResult; @QueryResult public class UnmanagedUserPojo { - private String name; + private String name; - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/UserRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/UserRepository.java index 500ec8f13..2f92c189a 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/UserRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/repo/UserRepository.java @@ -13,20 +13,24 @@ package org.springframework.data.neo4j.examples.movies.repo; +import java.util.Collection; +import java.util.List; +import java.util.Map; + import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import org.springframework.data.neo4j.annotation.Depth; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.neo4j.examples.movies.domain.User; -import org.springframework.data.neo4j.examples.movies.domain.queryresult.*; +import org.springframework.data.neo4j.examples.movies.domain.queryresult.EntityWrappingQueryResult; +import org.springframework.data.neo4j.examples.movies.domain.queryresult.Gender; +import org.springframework.data.neo4j.examples.movies.domain.queryresult.RichUserQueryResult; +import org.springframework.data.neo4j.examples.movies.domain.queryresult.UserQueryResult; +import org.springframework.data.neo4j.examples.movies.domain.queryresult.UserQueryResultInterface; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import java.util.Collection; -import java.util.List; -import java.util.Map; - /** * @author Michal Bachman * @author Luanne Misquitta @@ -34,91 +38,91 @@ import java.util.Map; @Repository public interface UserRepository extends PersonRepository { - Collection findByMiddleName(String middleName); + Collection findByMiddleName(String middleName); - List findByRatingsStars(int stars); + List findByRatingsStars(int stars); - List findByRatingsStarsAndInterestedName(int stars, String name); + List findByRatingsStarsAndInterestedName(int stars, String name); - @Query("MATCH (user:User) RETURN COUNT(user)") - int findTotalUsers(); + @Query("MATCH (user:User) RETURN COUNT(user)") + int findTotalUsers(); - @Query("MATCH (user:User) RETURN id(user)") - List getUserIds(); + @Query("MATCH (user:User) RETURN id(user)") + List getUserIds(); - @Query("MATCH (user:User) RETURN user.name, id(user)") - Iterable> getUsersAsProperties(); + @Query("MATCH (user:User) RETURN user.name, id(user)") + Iterable> getUsersAsProperties(); - @Query("MATCH (user:User) RETURN user") - Collection getAllUsers(); + @Query("MATCH (user:User) RETURN user") + Collection getAllUsers(); - @Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:User) RETURN m.name as movie, collect(a.name) as cast") - List> getGraph(); + @Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:User) RETURN m.name as movie, collect(a.name) as cast") + List> getGraph(); - @Query("MATCH (user:User{name:{name}}) RETURN user") - User findUserByNameWithNamedParam(@Param("name") String name); + @Query("MATCH (user:User{name:{name}}) RETURN user") + User findUserByNameWithNamedParam(@Param("name") String name); - @Query("MATCH (user:User{name:{0}}) RETURN user") - User findUserByName(String name); + @Query("MATCH (user:User{name:{0}}) RETURN user") + User findUserByName(String name); - @Query("MATCH (user:User) RETURN id(user) AS userId, id(user) as id, user.name AS userName, user.age ORDER BY user.age") - Iterable retrieveAllUsersAndTheirAges(); + @Query("MATCH (user:User) RETURN id(user) AS userId, id(user) as id, user.name AS userName, user.age ORDER BY user.age") + Iterable retrieveAllUsersAndTheirAges(); - @Query("MATCH (user:User{name:{0}}) RETURN user.name AS name") - UnmanagedUserPojo findIndividualUserAsDifferentObject(String name); + @Query("MATCH (user:User{name:{0}}) RETURN user.name AS name") + UnmanagedUserPojo findIndividualUserAsDifferentObject(String name); - @Query("MATCH (user:User) WHERE user.name={0} RETURN user.name, user.age AS ageOfUser") - UserQueryResultInterface findIndividualUserAsProxiedObject(String name); + @Query("MATCH (user:User) WHERE user.name={0} RETURN user.name, user.age AS ageOfUser") + UserQueryResultInterface findIndividualUserAsProxiedObject(String name); - @Query("MATCH (user:User) WHERE user.name={0} RETURN user as user, user.age AS ageOfUser") - UserQueryResultInterface findWrappedUserAsProxiedObject(String name); + @Query("MATCH (user:User) WHERE user.name={0} RETURN user as user, user.age AS ageOfUser") + UserQueryResultInterface findWrappedUserAsProxiedObject(String name); - @Query("MATCH (user:User) WHERE user.gender={0} RETURN user.name AS UserName, user.gender AS UserGender, user.account as UserAccount, user.deposits as UserDeposits") - Iterable findUsersByGender(Gender gender); + @Query("MATCH (user:User) WHERE user.gender={0} RETURN user.name AS UserName, user.gender AS UserGender, user.account as UserAccount, user.deposits as UserDeposits") + Iterable findUsersByGender(Gender gender); - @Query("MATCH (user:User) WHERE user.name={0} RETURN user") - EntityWrappingQueryResult findWrappedUserByName(String userName); + @Query("MATCH (user:User) WHERE user.name={0} RETURN user") + EntityWrappingQueryResult findWrappedUserByName(String userName); - @Query("MATCH (user:User)-[:FRIEND_OF]->(f) WHERE user.name={0} RETURN user, collect(f) as friends") - EntityWrappingQueryResult findWrappedUserAndFriendsDepth0(String userName); + @Query("MATCH (user:User)-[:FRIEND_OF]->(f) WHERE user.name={0} RETURN user, collect(f) as friends") + EntityWrappingQueryResult findWrappedUserAndFriendsDepth0(String userName); - @Query("MATCH (user:User)-[r:FRIEND_OF]->(f) WHERE user.name={0} RETURN user, collect(r) as rels, collect(f) as friends") - EntityWrappingQueryResult findWrappedUserAndFriendsDepth1(String userName); + @Query("MATCH (user:User)-[r:FRIEND_OF]->(f) WHERE user.name={0} RETURN user, collect(r) as rels, collect(f) as friends") + EntityWrappingQueryResult findWrappedUserAndFriendsDepth1(String userName); - @Query("MATCH (user:User)-[r:RATED]->(m) WHERE user.name={0} RETURN user, collect(r) as ratings, collect(m) as movies, avg(r.stars) as avgRating") - EntityWrappingQueryResult findWrappedUserAndRatingsByName(String userName); + @Query("MATCH (user:User)-[r:RATED]->(m) WHERE user.name={0} RETURN user, collect(r) as ratings, collect(m) as movies, avg(r.stars) as avgRating") + EntityWrappingQueryResult findWrappedUserAndRatingsByName(String userName); - @Query("MATCH (user:User)-[r:RATED]->(m) RETURN user, collect(r) as ratings, collect(m) as movies, avg(r.stars) as avgRating order by user.name desc") - List findAllUserRatings(); + @Query("MATCH (user:User)-[r:RATED]->(m) RETURN user, collect(r) as ratings, collect(m) as movies, avg(r.stars) as avgRating order by user.name desc") + List findAllUserRatings(); - @Query("MATCH (user:User) RETURN ID(user)") - List getUserNodeIds(); + @Query("MATCH (user:User) RETURN ID(user)") + List getUserNodeIds(); - @Query("MATCH (user:User) WHERE ID(user)={0} return user") - User loadUserById(User user); + @Query("MATCH (user:User) WHERE ID(user)={0} return user") + User loadUserById(User user); - @Query("MATCH (user:User) WHERE ID(user)={userId} RETURN user") - User loadUserByNamedId(@Param("userId") User user); + @Query("MATCH (user:User) WHERE ID(user)={userId} RETURN user") + User loadUserByNamedId(@Param("userId") User user); - @Query("MATCH (user:User) RETURN user") - Iterable getAllUsersIterable(); + @Query("MATCH (user:User) RETURN user") + Iterable getAllUsersIterable(); - @Query("MATCH (user:User) set user.name={0}") - void setNamesNull(String name); + @Query("MATCH (user:User) set user.name={0}") + void setNamesNull(String name); - List findByNameIsNotLike(String name); + List findByNameIsNotLike(String name); - @Depth(value = 0) - User findBySurname(String surname); + @Depth(value = 0) + User findBySurname(String surname); - @Query("MATCH (user:User) RETURN user.unknown as allRatings") - EntityWrappingQueryResult findAllRatingsNull(); + @Query("MATCH (user:User) RETURN user.unknown as allRatings") + EntityWrappingQueryResult findAllRatingsNull(); - @Query("match (u:User)-[r:RATED]->(m:Movie) return u as user, collect({username: u.name, movietitle: m.title, stars:r.stars}) as literalMap") - List findRatingsWithLiteralMap(); + @Query("match (u:User)-[r:RATED]->(m:Movie) return u as user, collect({username: u.name, movietitle: m.title, stars:r.stars}) as literalMap") + List findRatingsWithLiteralMap(); - Page findByNameAndSurname(String name, String surname, Pageable pageable); + Page findByNameAndSurname(String name, String surname, Pageable pageable); - Slice findByNameAndRatingsStars(String name, int stars, Pageable pageable); + Slice findByNameAndRatingsStars(String name, int stars, Pageable pageable); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/service/UserService.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/service/UserService.java index 997ef4590..8c1f15c00 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/service/UserService.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/service/UserService.java @@ -21,14 +21,14 @@ import org.springframework.transaction.annotation.Transactional; */ public interface UserService { - @Transactional - void updateUser(User user, String newName); + @Transactional + void updateUser(User user, String newName); - @Transactional - void notInterestedIn(Long userId, Long genreId); + @Transactional + void notInterestedIn(Long userId, Long genreId); - @Transactional - void saveWithTxAnnotationOnInterface(User user); + @Transactional + void saveWithTxAnnotationOnInterface(User user); - void saveWithTxAnnotationOnImpl(User user); + void saveWithTxAnnotationOnImpl(User user); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/service/UserServiceImpl.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/service/UserServiceImpl.java index 3a00395ec..1fc8e047a 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/service/UserServiceImpl.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/movies/service/UserServiceImpl.java @@ -27,34 +27,32 @@ import org.springframework.transaction.annotation.Transactional; @Service public class UserServiceImpl implements UserService { - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; - @Autowired - private GenreRepository genreRepository; + @Autowired private GenreRepository genreRepository; - @Override - public void updateUser(User user, String newName) { - user.setName(newName); - } + @Override + public void updateUser(User user, String newName) { + user.setName(newName); + } - @Override - public void notInterestedIn(Long userId, Long genreId) { - User user = userRepository.findOne(userId); - Genre genre = genreRepository.findOne(genreId); + @Override + public void notInterestedIn(Long userId, Long genreId) { + User user = userRepository.findOne(userId); + Genre genre = genreRepository.findOne(genreId); - user.notInterestedIn(genre); - userRepository.save(user); - } + user.notInterestedIn(genre); + userRepository.save(user); + } - @Override - public void saveWithTxAnnotationOnInterface(User user) { - userRepository.save(user); - } + @Override + public void saveWithTxAnnotationOnInterface(User user) { + userRepository.save(user); + } - @Transactional - @Override - public void saveWithTxAnnotationOnImpl(User user) { - userRepository.save(user); - } + @Transactional + @Override + public void saveWithTxAnnotationOnImpl(User user) { + userRepository.save(user); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/RestaurantIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/RestaurantIT.java index 0b41e3a32..d6837c875 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/RestaurantIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/RestaurantIT.java @@ -11,7 +11,6 @@ * */ - package org.springframework.data.neo4j.examples.restaurants; import static org.apache.webbeans.util.Asserts.assertNotNull; @@ -40,44 +39,39 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -@ContextConfiguration(classes = {RestaurantContext.class}) +@ContextConfiguration(classes = { RestaurantContext.class }) @RunWith(SpringJUnit4ClassRunner.class) @DirtiesContext /** - * * Tests that we support each kind of keyword specified by Part.Type * * @author Jasper Blues */ public class RestaurantIT extends MultiDriverTestClass { - @Autowired - private RestaurantRepository restaurantRepository; + @Autowired private RestaurantRepository restaurantRepository; @After public void tearDown() { restaurantRepository.deleteAll(); } - /** - * This test, as the below one does, asserts that the parameter index for each query part is set correctly. Most - * query parts are associated with one parameter, while certain kinds, such as NEAR, require more. - + * This test, as the below one does, asserts that the parameter index for each query part is set correctly. Most query + * parts are associated with one parameter, while certain kinds, such as NEAR, require more. * * @see DATAGRAPH-561 */ @Test public void shouldFindRestaurantsNear_nameParameterFirst() { Assume.assumeTrue(Components.neo4jVersion() >= 3); - Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", - new Point(37.61649, -122.38681), 94128); + Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", new Point(37.61649, -122.38681), + 94128); restaurantRepository.save(restaurant); List results = restaurantRepository.findByNameAndLocationNear( - "San Francisco International Airport (SFO)", - new Distance(150, Metrics.KILOMETERS), new Point(37.6, -122.3)); + "San Francisco International Airport (SFO)", new Distance(150, Metrics.KILOMETERS), new Point(37.6, -122.3)); assertNotNull(results); assertEquals(1, results.size()); @@ -88,22 +82,20 @@ public class RestaurantIT extends MultiDriverTestClass { } /** - * - * This test, as the above one does, asserts that the parameter index for each query part is set correctly. Most - * query parts are associated with one parameter, while certain kinds, such as NEAR, require more. + * This test, as the above one does, asserts that the parameter index for each query part is set correctly. Most query + * parts are associated with one parameter, while certain kinds, such as NEAR, require more. * * @see DATAGRAPH-561 */ @Test public void shouldFindRestaurantsNear_locationFirst() { Assume.assumeTrue(Components.neo4jVersion() >= 3); - Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", - new Point(37.61649, -122.38681), 94128); + Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", new Point(37.61649, -122.38681), + 94128); restaurantRepository.save(restaurant); - List results = restaurantRepository.findByLocationNearAndName( - new Distance(150, Metrics.KILOMETERS), new Point(37.6, -122.3), - "San Francisco International Airport (SFO)"); + List results = restaurantRepository.findByLocationNearAndName(new Distance(150, Metrics.KILOMETERS), + new Point(37.6, -122.3), "San Francisco International Airport (SFO)"); assertNotNull(results); assertEquals(1, results.size()); @@ -141,8 +133,8 @@ public class RestaurantIT extends MultiDriverTestClass { */ @Test public void shouldFindByPropertyIsNull() { - Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", - new Point(37.61649, -122.38681), 94128); + Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", new Point(37.61649, -122.38681), + 94128); restaurantRepository.save(restaurant); Restaurant kuroda = new Restaurant("Kuroda", "Mostly Ramen"); @@ -160,8 +152,8 @@ public class RestaurantIT extends MultiDriverTestClass { */ @Test public void shouldFindByPropertyIsNotNull() { - Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", - new Point(37.61649, -122.38681), 94128); + Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", new Point(37.61649, -122.38681), + 94128); restaurantRepository.save(restaurant); Restaurant kuroda = new Restaurant("Kuroda", "Mostly Ramen"); @@ -178,8 +170,8 @@ public class RestaurantIT extends MultiDriverTestClass { */ @Test public void shouldFindBNestedProperty_different_entity_type_IsNull() { - Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", - new Point(37.61649, -122.38681), 94128); + Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", new Point(37.61649, -122.38681), + 94128); Diner diner = new Diner("Jasper", null); restaurant.addRegularDiner(diner); @@ -197,8 +189,8 @@ public class RestaurantIT extends MultiDriverTestClass { */ @Test public void shouldFindBNestedProperty_same_entity_type_IsNull() { - Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", - new Point(37.61649, -122.38681), 94128); + Restaurant restaurant = new Restaurant("San Francisco International Airport (SFO)", new Point(37.61649, -122.38681), + 94128); Diner diner = new Diner("Jasper", null); restaurant.addRegularDiner(diner); @@ -314,6 +306,7 @@ public class RestaurantIT extends MultiDriverTestClass { /** * All findByPropertyLike does currently is to require an exact match, ignoring case. + * * @see DATAGRAPH-904 */ @Test @@ -332,9 +325,9 @@ public class RestaurantIT extends MultiDriverTestClass { } - /** * All findByPropertyLike does currently is to require an exact match, ignoring case. + * * @see DATAGRAPH-904 */ @Test @@ -508,8 +501,7 @@ public class RestaurantIT extends MultiDriverTestClass { * @see DATAGRAPH-904 */ @Test - public void shouldFindByPropertyIsTrue() - { + public void shouldFindByPropertyIsTrue() { Restaurant kazan = new Restaurant("Kazan", 77.0); kazan.setHalal(true); restaurantRepository.save(kazan); @@ -528,8 +520,7 @@ public class RestaurantIT extends MultiDriverTestClass { * @see DATAGRAPH-904 */ @Test - public void shouldFindByPropertyIsFalse() - { + public void shouldFindByPropertyIsFalse() { Restaurant kazan = new Restaurant("Kazan", 77.0); kazan.setHalal(true); restaurantRepository.save(kazan); diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/context/RestaurantContext.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/context/RestaurantContext.java index cc3885afa..9c7d791f8 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/context/RestaurantContext.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/context/RestaurantContext.java @@ -11,7 +11,6 @@ * */ - package org.springframework.data.neo4j.examples.restaurants.context; import org.neo4j.ogm.session.SessionFactory; @@ -24,12 +23,13 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@ComponentScan({"org.springframework.data.neo4j.examples.restaurants"}) +@ComponentScan({ "org.springframework.data.neo4j.examples.restaurants" }) @EnableNeo4jRepositories("org.springframework.data.neo4j.examples.restaurants.repo") @EnableTransactionManagement /** * Assembly for RestaurantIT. + * * @author Jasper Blues */ public class RestaurantContext { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/domain/Diner.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/domain/Diner.java index 590fa5a5f..b133cbf36 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/domain/Diner.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/domain/Diner.java @@ -8,15 +8,12 @@ import org.neo4j.ogm.annotation.GraphId; */ public class Diner { - @GraphId - private Long id; + @GraphId private Long id; private String firstName; private String lastName; - public Diner() - { - } + public Diner() {} public Diner(String firstName, String lastName) { this.firstName = firstName; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/domain/Restaurant.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/domain/Restaurant.java index 5026e9fc3..61cca57a8 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/domain/Restaurant.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/domain/Restaurant.java @@ -11,7 +11,6 @@ * */ - package org.springframework.data.neo4j.examples.restaurants.domain; import java.util.ArrayList; @@ -30,27 +29,23 @@ import org.springframework.data.neo4j.conversion.PointConverter; */ public class Restaurant implements Comparable { - @GraphId - private Long id; + @GraphId private Long id; private String name; - @Convert(PointConverter.class) - private Point location; + @Convert(PointConverter.class) private Point location; private int zip; private double score; private String description; private boolean halal; - @Relationship(type = "REGULAR_DINER", direction = Relationship.OUTGOING) - private List regularDiners = new ArrayList<>(); + @Relationship(type = "REGULAR_DINER", + direction = Relationship.OUTGOING) private List regularDiners = new ArrayList<>(); - @Relationship(type = "SIMILAR_RESTAURANT", direction = Relationship.OUTGOING) - private List similarRestaurants = new ArrayList<>(); + @Relationship(type = "SIMILAR_RESTAURANT", + direction = Relationship.OUTGOING) private List similarRestaurants = new ArrayList<>(); - @DateString - private Date launchDate; + @DateString private Date launchDate; - public Restaurant() { - } + public Restaurant() {} public Restaurant(String name, Point location, int zip) { this.name = name; @@ -142,10 +137,7 @@ public class Restaurant implements Comparable { @Override public String toString() { - return "Restaurant{" + - "name='" + name + '\'' + - ", score=" + score + - '}'; + return "Restaurant{" + "name='" + name + '\'' + ", score=" + score + '}'; } @Override diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/repo/RestaurantRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/repo/RestaurantRepository.java index 5d6ae0e99..b16696723 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/repo/RestaurantRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/examples/restaurants/repo/RestaurantRepository.java @@ -79,5 +79,3 @@ public interface RestaurantRepository extends Neo4jRepository List findByNameNotContainingOrDescriptionIsNull(String nameContaining); } - - diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomGraphRepositoryIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomGraphRepositoryIT.java index e45029473..df01f0d60 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomGraphRepositoryIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomGraphRepositoryIT.java @@ -24,16 +24,14 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author: Vince Bickers */ -@ContextConfiguration(classes = {CustomPersistenceContext.class}) +@ContextConfiguration(classes = { CustomPersistenceContext.class }) @RunWith(SpringJUnit4ClassRunner.class) public class CustomGraphRepositoryIT extends MultiDriverTestClass { - @Autowired - private UserRepository repository; + @Autowired private UserRepository repository; /** - * asserts that the correct proxied object is created by Spring - * and that we can integrate with it. + * asserts that the correct proxied object is created by Spring and that we can integrate with it. */ @Test public void shouldExposeCommonMethodOnExtendedRepository() { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomGraphRepositoryImpl.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomGraphRepositoryImpl.java index 8d0ee932d..ea09c252a 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomGraphRepositoryImpl.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomGraphRepositoryImpl.java @@ -26,7 +26,8 @@ import org.springframework.stereotype.Repository; * @author Mark Angrish */ @Repository -public class CustomGraphRepositoryImpl extends SimpleNeo4jRepository implements CustomNeo4jRepository { +public class CustomGraphRepositoryImpl extends SimpleNeo4jRepository + implements CustomNeo4jRepository { public CustomGraphRepositoryImpl(Class clazz, Session session) { super(clazz, session); diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomNeo4jRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomNeo4jRepository.java index c9461b017..eca0b278c 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomNeo4jRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomNeo4jRepository.java @@ -18,14 +18,13 @@ import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.data.repository.NoRepositoryBean; /** - * This interface declares a custom method that we want to - * be available to all repositories that extend this class + * This interface declares a custom method that we want to be available to all repositories that extend this class * * @author: Vince Bickers */ @NoRepositoryBean public interface CustomNeo4jRepository extends Neo4jRepository { - boolean sharedCustomMethod(); + boolean sharedCustomMethod(); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomPersistenceContext.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomPersistenceContext.java index 260ec36e5..3497736d5 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomPersistenceContext.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/CustomPersistenceContext.java @@ -21,10 +21,8 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; /** - * Note how the repository base class for all our repositories is overridden - * using the 'repositoryBaseClass' attribute. - * This annotation change allows all our repositories to easily extend one or more - * additional interfaces. + * Note how the repository base class for all our repositories is overridden using the 'repositoryBaseClass' attribute. + * This annotation change allows all our repositories to easily extend one or more additional interfaces. * * @author Vince Bickers * @author Mark Angrish diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/UserRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/UserRepository.java index 8c34fc9b3..41353cc1c 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/UserRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/UserRepository.java @@ -19,5 +19,4 @@ import org.springframework.stereotype.Repository; * @author: Vince Bickers */ @Repository -public interface UserRepository extends CustomNeo4jRepository { -} +public interface UserRepository extends CustomNeo4jRepository {} diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/domain/User.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/domain/User.java index 43828aed7..89275a56e 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/domain/User.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/extensions/domain/User.java @@ -17,6 +17,6 @@ package org.springframework.data.neo4j.extensions.domain; */ public class User { - Long id; + Long id; } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/ConversionServiceIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/ConversionServiceIT.java index 55f3031d2..9a4d8fe43 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/ConversionServiceIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/ConversionServiceIT.java @@ -32,20 +32,15 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConverterNotFoundException; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.convert.support.GenericConversionService; -import org.springframework.data.neo4j.examples.movies.domain.TempMovie; -import org.springframework.data.neo4j.examples.movies.domain.User; import org.springframework.data.neo4j.integration.conversion.domain.JavaElement; import org.springframework.data.neo4j.integration.conversion.domain.MonetaryAmount; import org.springframework.data.neo4j.integration.conversion.domain.PensionPlan; import org.springframework.data.neo4j.integration.conversion.domain.SiteMember; -import org.springframework.test.annotation.Commit; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionCallback; -import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; /** @@ -56,21 +51,16 @@ import org.springframework.transaction.support.TransactionTemplate; * @see DATAGRAPH-624 */ @RunWith(SpringRunner.class) -@ContextConfiguration(classes = {ConversionServicePersistenceContext.class}) +@ContextConfiguration(classes = { ConversionServicePersistenceContext.class }) public class ConversionServiceIT extends MultiDriverTestClass { private static GraphDatabaseService graphDatabaseService; - @Autowired - PlatformTransactionManager platformTransactionManager; - @Autowired - private PensionRepository pensionRepository; - @Autowired - private JavaElementRepository javaElementRepository; - @Autowired - private SiteMemberRepository siteMemberRepository; - @Autowired - private GenericConversionService conversionService; + @Autowired PlatformTransactionManager platformTransactionManager; + @Autowired private PensionRepository pensionRepository; + @Autowired private JavaElementRepository javaElementRepository; + @Autowired private SiteMemberRepository siteMemberRepository; + @Autowired private GenericConversionService conversionService; @Autowired Session session; @@ -93,7 +83,7 @@ public class ConversionServiceIT extends MultiDriverTestClass { @Test public void shouldBeAbleToConvertBetweenBytesAndBase64EncodedDataViaSpringConversionService() { String base64Representation = "YmNkZWY="; - byte[] binaryData = new byte[]{98, 99, 100, 101, 102}; + byte[] binaryData = new byte[] { 98, 99, 100, 101, 102 }; assertTrue(this.conversionService.canConvert(byte[].class, String.class)); assertEquals(base64Representation, this.conversionService.convert(binaryData, String.class)); @@ -104,8 +94,8 @@ public class ConversionServiceIT extends MultiDriverTestClass { @Test public void shouldConvertBase64StringOutOfGraphDatabaseBackIntoByteArray() { - Result rs = graphDatabaseService.execute( - "CREATE (u:SiteMember {profilePictureData:'MTIzNDU2Nzg5'}) RETURN id(u) AS userId"); + Result rs = graphDatabaseService + .execute("CREATE (u:SiteMember {profilePictureData:'MTIzNDU2Nzg5'}) RETURN id(u) AS userId"); Long userId = (Long) rs.columnAs("userId").next(); byte[] expectedData = "123456789".getBytes(); @@ -132,10 +122,10 @@ public class ConversionServiceIT extends MultiDriverTestClass { } }); - Result result = graphDatabaseService - .execute("MATCH (p:PensionPlan) RETURN p.fundValue AS fv"); + Result result = graphDatabaseService.execute("MATCH (p:PensionPlan) RETURN p.fundValue AS fv"); assertTrue("Nothing was saved", result.hasNext()); - assertEquals("The amount wasn't converted and persisted correctly", "1647281", String.valueOf(result.next().get("fv"))); + assertEquals("The amount wasn't converted and persisted correctly", "1647281", + String.valueOf(result.next().get("fv"))); result.close(); PensionPlan reloadedPension = this.pensionRepository.findOne(pensionToSave.getPensionPlanId()); @@ -149,14 +139,14 @@ public class ConversionServiceIT extends MultiDriverTestClass { public void shouldConvertFieldsUsingAnAvailableSupertypeConverterIfExactTypesDoNotMatch() { this.conversionService.addConverterFactory(new SpringMonetaryAmountToNumberConverterFactory()); - //this.conversionService.addConverter(new SpringIntegerToMonetaryAmountConverter()); + // this.conversionService.addConverter(new SpringIntegerToMonetaryAmountConverter()); PensionPlan pension = new PensionPlan(new MonetaryAmount(20_000, 00), "Ashes Assets LLP"); this.pensionRepository.save(pension); - Result result = graphDatabaseService - .execute("MATCH (p:PensionPlan) RETURN p.fundValue AS fv"); + Result result = graphDatabaseService.execute("MATCH (p:PensionPlan) RETURN p.fundValue AS fv"); assertTrue("Nothing was saved", result.hasNext()); - assertEquals("The amount wasn't converted and persisted correctly", "2000000", String.valueOf(result.next().get("fv"))); + assertEquals("The amount wasn't converted and persisted correctly", "2000000", + String.valueOf(result.next().get("fv"))); result.close(); } @@ -173,14 +163,14 @@ public class ConversionServiceIT extends MultiDriverTestClass { this.javaElementRepository.save(method); - Result result = graphDatabaseService - .execute("MATCH (e:JavaElement) RETURN e.elementType AS type"); + Result result = graphDatabaseService.execute("MATCH (e:JavaElement) RETURN e.elementType AS type"); assertTrue("Nothing was saved", result.hasNext()); assertEquals("The element type wasn't converted and persisted correctly", "METHOD", result.next().get("type")); result.close(); JavaElement loadedObject = this.javaElementRepository.findAll().iterator().next(); - assertEquals("The element type wasn't loaded and converted correctly", ElementType.METHOD, loadedObject.getElementType()); + assertEquals("The element type wasn't loaded and converted correctly", ElementType.METHOD, + loadedObject.getElementType()); } @Test(expected = ConverterNotFoundException.class) @@ -194,12 +184,12 @@ public class ConversionServiceIT extends MultiDriverTestClass { @Test public void shouldUseSpecifiedAttributeConverterInsteadOfSprings() { - //We're registering Spring converters as well + // We're registering Spring converters as well this.conversionService.addConverter(new SpringIntegerToByteArrayConverter()); this.conversionService.addConverter(new SpringByteArrayToIntegerConverter()); String base64Representation = "YmNkZWY="; - byte[] binaryData = new byte[]{98, 99, 100, 101, 102}; + byte[] binaryData = new byte[] { 98, 99, 100, 101, 102 }; assertTrue(this.conversionService.canConvert(byte[].class, String.class)); assertEquals(base64Representation, this.conversionService.convert(binaryData, String.class)); @@ -217,11 +207,11 @@ public class ConversionServiceIT extends MultiDriverTestClass { @Test public void shouldUseDefaultAttributeConverterInsteadOfSprings() { - //We're registering Spring converters which should not override the default ogm BigInteger converter + // We're registering Spring converters which should not override the default ogm BigInteger converter this.conversionService.addConverter(new SpringBigIntegerToBooleanConverter()); this.conversionService.addConverter(new SpringBooleanToBigIntegerConverter()); - byte[] binaryData = new byte[]{98, 99, 100, 101, 102}; + byte[] binaryData = new byte[] { 98, 99, 100, 101, 102 }; SiteMember siteMember = new SiteMember(); siteMember.setProfilePictureData(binaryData); diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/ConversionServicePersistenceContext.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/ConversionServicePersistenceContext.java index 99b18d589..cbfe692a2 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/ConversionServicePersistenceContext.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/ConversionServicePersistenceContext.java @@ -17,14 +17,10 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.ConversionService; import org.springframework.data.neo4j.conversion.MetaDataDrivenConversionService; -import org.springframework.data.neo4j.integration.conversion.domain.MonetaryAmount; -import org.springframework.data.neo4j.integration.conversion.domain.PensionPlan; import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; import org.springframework.data.neo4j.transaction.Neo4jTransactionManager; -import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.annotation.Transactional; /** * Testing Spring's type conversion service support. @@ -33,7 +29,8 @@ import org.springframework.transaction.annotation.Transactional; * @author Mark Angrish */ @Configuration -@EnableNeo4jRepositories(basePackageClasses = {SiteMemberRepository.class, PensionRepository.class, JavaElementRepository.class}) +@EnableNeo4jRepositories( + basePackageClasses = { SiteMemberRepository.class, PensionRepository.class, JavaElementRepository.class }) @EnableTransactionManagement public class ConversionServicePersistenceContext { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/JavaElementRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/JavaElementRepository.java index a8f19e759..6720e857c 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/JavaElementRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/JavaElementRepository.java @@ -23,6 +23,6 @@ import org.springframework.stereotype.Repository; @Repository public interface JavaElementRepository extends Neo4jRepository { - // no additional repository methods + // no additional repository methods } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/PensionRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/PensionRepository.java index 9c6f3f7ac..d9b3daf58 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/PensionRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/PensionRepository.java @@ -23,6 +23,6 @@ import org.springframework.stereotype.Repository; @Repository public interface PensionRepository extends Neo4jRepository { - // no additional repository methods + // no additional repository methods } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SiteMemberRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SiteMemberRepository.java index af0e7fb7c..8cf70bf34 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SiteMemberRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SiteMemberRepository.java @@ -23,6 +23,6 @@ import org.springframework.stereotype.Repository; @Repository public interface SiteMemberRepository extends Neo4jRepository { - // no additional repository methods + // no additional repository methods } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringBigIntegerToBooleanConverter.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringBigIntegerToBooleanConverter.java index c9c75358f..d8de6e91e 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringBigIntegerToBooleanConverter.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringBigIntegerToBooleanConverter.java @@ -13,15 +13,16 @@ package org.springframework.data.neo4j.integration.conversion; -import org.springframework.core.convert.converter.Converter; - import java.math.BigInteger; +import org.springframework.core.convert.converter.Converter; + /** * Nonsensical Spring converter for test purposes + * * @author Luanne Misquitta */ -public class SpringBigIntegerToBooleanConverter implements Converter { +public class SpringBigIntegerToBooleanConverter implements Converter { @Override public Boolean convert(BigInteger source) { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringBooleanToBigIntegerConverter.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringBooleanToBigIntegerConverter.java index c0357fdac..bb20bdc25 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringBooleanToBigIntegerConverter.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringBooleanToBigIntegerConverter.java @@ -13,19 +13,20 @@ package org.springframework.data.neo4j.integration.conversion; -import org.springframework.core.convert.converter.Converter; - import java.math.BigInteger; +import org.springframework.core.convert.converter.Converter; + /** * Nonsensical Spring converter for testing purposes + * * @author Luanne Misquitta */ public class SpringBooleanToBigIntegerConverter implements Converter { @Override public BigInteger convert(Boolean source) { - if(source) { + if (source) { return BigInteger.valueOf(101); } return BigInteger.valueOf(1); diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringByteArrayToIntegerConverter.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringByteArrayToIntegerConverter.java index a4fb3702c..27d243807 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringByteArrayToIntegerConverter.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringByteArrayToIntegerConverter.java @@ -17,9 +17,10 @@ import org.springframework.core.convert.converter.Converter; /** * Nonsensical spring converter from a byte[] to an Integer, for test purposes + * * @author Luanne Misquitta */ -public class SpringByteArrayToIntegerConverter implements Converter { +public class SpringByteArrayToIntegerConverter implements Converter { @Override public Integer convert(byte[] source) { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringIntegerToByteArrayConverter.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringIntegerToByteArrayConverter.java index 3aa1707cb..2aaa747a1 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringIntegerToByteArrayConverter.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringIntegerToByteArrayConverter.java @@ -13,14 +13,14 @@ package org.springframework.data.neo4j.integration.conversion; - import org.springframework.core.convert.converter.Converter; /** * Nonsensical spring converter from a byte[] to an Integer, for test purposes + * * @author Luanne Misquitta */ -public class SpringIntegerToByteArrayConverter implements Converter { +public class SpringIntegerToByteArrayConverter implements Converter { @Override public byte[] convert(Integer source) { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringIntegerToMonetaryAmountConverter.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringIntegerToMonetaryAmountConverter.java index 70d23a26a..06ca881a2 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringIntegerToMonetaryAmountConverter.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringIntegerToMonetaryAmountConverter.java @@ -18,9 +18,9 @@ import org.springframework.data.neo4j.integration.conversion.domain.MonetaryAmou public class SpringIntegerToMonetaryAmountConverter implements Converter { - @Override - public MonetaryAmount convert(Integer source) { - return source != null ? new MonetaryAmount(source.intValue() / 100, source.intValue() % 100) : null; - } + @Override + public MonetaryAmount convert(Integer source) { + return source != null ? new MonetaryAmount(source.intValue() / 100, source.intValue() % 100) : null; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringLongToMonetaryAmountConverter.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringLongToMonetaryAmountConverter.java index b0cdcf036..89236c4cc 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringLongToMonetaryAmountConverter.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringLongToMonetaryAmountConverter.java @@ -18,9 +18,9 @@ import org.springframework.data.neo4j.integration.conversion.domain.MonetaryAmou public class SpringLongToMonetaryAmountConverter implements Converter { - @Override - public MonetaryAmount convert(Long source) { - return source != null ? new MonetaryAmount(source.intValue() / 100, source.intValue() % 100) : null; - } + @Override + public MonetaryAmount convert(Long source) { + return source != null ? new MonetaryAmount(source.intValue() / 100, source.intValue() % 100) : null; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToIntegerConverter.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToIntegerConverter.java index df119e9ff..e870b325e 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToIntegerConverter.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToIntegerConverter.java @@ -18,9 +18,9 @@ import org.springframework.data.neo4j.integration.conversion.domain.MonetaryAmou public class SpringMonetaryAmountToIntegerConverter implements Converter { - @Override - public Integer convert(MonetaryAmount source) { - return source != null ? (int) source.getAmountAsSubUnits() : null; - } + @Override + public Integer convert(MonetaryAmount source) { + return source != null ? (int) source.getAmountAsSubUnits() : null; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToLongConverter.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToLongConverter.java index 59747fc42..f76cc061d 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToLongConverter.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToLongConverter.java @@ -18,9 +18,9 @@ import org.springframework.data.neo4j.integration.conversion.domain.MonetaryAmou public class SpringMonetaryAmountToLongConverter implements Converter { - @Override - public Long convert(MonetaryAmount source) { - return source != null ? (long) source.getAmountAsSubUnits() : null; - } + @Override + public Long convert(MonetaryAmount source) { + return source != null ? (long) source.getAmountAsSubUnits() : null; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToNumberConverter.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToNumberConverter.java index 9856c5231..73446e108 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToNumberConverter.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToNumberConverter.java @@ -18,9 +18,9 @@ import org.springframework.data.neo4j.integration.conversion.domain.MonetaryAmou public class SpringMonetaryAmountToNumberConverter implements Converter { - @Override - public Number convert(MonetaryAmount source) { - return source != null ? source.getAmountAsSubUnits() : null; - } + @Override + public Number convert(MonetaryAmount source) { + return source != null ? source.getAmountAsSubUnits() : null; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToNumberConverterFactory.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToNumberConverterFactory.java index 01713c227..42899b462 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToNumberConverterFactory.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringMonetaryAmountToNumberConverterFactory.java @@ -20,24 +20,26 @@ import org.springframework.core.convert.converter.ConverterFactory; import org.springframework.data.neo4j.integration.conversion.domain.MonetaryAmount; /** - * Not a properly-implemented factory, but it does serve the purpose of helping to verify that converters defined for abstract - * supertypes can still be used correctly. + * Not a properly-implemented factory, but it does serve the purpose of helping to verify that converters defined for + * abstract supertypes can still be used correctly. * * @author Adam George */ -public class SpringMonetaryAmountToNumberConverterFactory implements ConverterFactory, ConditionalConverter { +public class SpringMonetaryAmountToNumberConverterFactory + implements ConverterFactory, ConditionalConverter { - private final SpringMonetaryAmountToIntegerConverter wrappedConverter = new SpringMonetaryAmountToIntegerConverter(); + private final SpringMonetaryAmountToIntegerConverter wrappedConverter = new SpringMonetaryAmountToIntegerConverter(); - @Override - public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { - return MonetaryAmount.class.isAssignableFrom(sourceType.getType()) && Number.class.isAssignableFrom(targetType.getType()); - } + @Override + public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { + return MonetaryAmount.class.isAssignableFrom(sourceType.getType()) + && Number.class.isAssignableFrom(targetType.getType()); + } - @SuppressWarnings("unchecked") - @Override - public Converter getConverter(Class targetType) { - return (Converter) this.wrappedConverter; - } + @SuppressWarnings("unchecked") + @Override + public Converter getConverter(Class targetType) { + return (Converter) this.wrappedConverter; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringNumberToMonetaryAmountConverter.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringNumberToMonetaryAmountConverter.java index 02e220a56..6529f7c8f 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringNumberToMonetaryAmountConverter.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/SpringNumberToMonetaryAmountConverter.java @@ -18,9 +18,9 @@ import org.springframework.data.neo4j.integration.conversion.domain.MonetaryAmou public class SpringNumberToMonetaryAmountConverter implements Converter { - @Override - public MonetaryAmount convert(Number source) { - return source != null ? new MonetaryAmount(source.intValue() / 100, source.intValue() % 100) : null; - } + @Override + public MonetaryAmount convert(Number source) { + return source != null ? new MonetaryAmount(source.intValue() / 100, source.intValue() % 100) : null; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/JavaElement.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/JavaElement.java index fa1233eae..96a836feb 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/JavaElement.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/JavaElement.java @@ -13,47 +13,45 @@ package org.springframework.data.neo4j.integration.conversion.domain; +import java.lang.annotation.ElementType; + import org.neo4j.ogm.annotation.GraphId; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.typeconversion.Convert; -import java.lang.annotation.ElementType; - /** - * Models an element of the Java programming language, although more importantly contains an enum that isn't part of the scanned - * OGM meta-data and therefore tests an important part of the Spring conversion service. + * Models an element of the Java programming language, although more importantly contains an enum that isn't part of the + * scanned OGM meta-data and therefore tests an important part of the Spring conversion service. */ @NodeEntity public class JavaElement { - @GraphId - private Long identifier; - private String name; - @Convert(graphPropertyType = String.class) - private ElementType elementType; + @GraphId private Long identifier; + private String name; + @Convert(graphPropertyType = String.class) private ElementType elementType; - public Long getIdentifier() { - return identifier; - } + public Long getIdentifier() { + return identifier; + } - public void setIdentifier(Long identifier) { - this.identifier = identifier; - } + public void setIdentifier(Long identifier) { + this.identifier = identifier; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public ElementType getElementType() { - return elementType; - } + public ElementType getElementType() { + return elementType; + } - public void setElementType(ElementType elementType) { - this.elementType = elementType; - } + public void setElementType(ElementType elementType) { + this.elementType = elementType; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/MonetaryAmount.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/MonetaryAmount.java index 126029fdb..ef3c8ec6c 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/MonetaryAmount.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/MonetaryAmount.java @@ -15,41 +15,41 @@ package org.springframework.data.neo4j.integration.conversion.domain; public class MonetaryAmount { - private final int amount; + private final int amount; - public MonetaryAmount(int pounds, int pence) { - this.amount = pounds * 100 + pence; - } + public MonetaryAmount(int pounds, int pence) { + this.amount = pounds * 100 + pence; + } - public int getAmountAsSubUnits() { - return this.amount; - } + public int getAmountAsSubUnits() { + return this.amount; + } - @Override - public int hashCode() { - final int prime = 17; - int result = 1; - result = prime * result + (amount ^ (amount >>> 32)); - return result; - } + @Override + public int hashCode() { + final int prime = 17; + int result = 1; + result = prime * result + (amount ^ (amount >>> 32)); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof MonetaryAmount)) - return false; + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof MonetaryAmount)) + return false; - MonetaryAmount other = (MonetaryAmount) obj; - return this.amount == other.amount; - } + MonetaryAmount other = (MonetaryAmount) obj; + return this.amount == other.amount; + } - @Override - public String toString() { - int pence = this.amount % 100; - return "£" + (this.amount / 100) + "." + (pence < 10 ? "0" + pence : pence); - } + @Override + public String toString() { + int pence = this.amount % 100; + return "£" + (this.amount / 100) + "." + (pence < 10 ? "0" + pence : pence); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/PensionPlan.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/PensionPlan.java index 74320000f..4b34a06b9 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/PensionPlan.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/PensionPlan.java @@ -24,43 +24,41 @@ import org.neo4j.ogm.annotation.typeconversion.Convert; @NodeEntity public class PensionPlan { - @GraphId - private Long pensionPlanId; + @GraphId private Long pensionPlanId; - @Convert(graphPropertyType = Integer.class) - private MonetaryAmount fundValue; + @Convert(graphPropertyType = Integer.class) private MonetaryAmount fundValue; - @Convert(graphPropertyType = SiteMember.class) //nonsensical conversion for test purposes - private JavaElement javaElement; + @Convert(graphPropertyType = SiteMember.class) // nonsensical conversion for test purposes + private JavaElement javaElement; - private String providerName; + private String providerName; - PensionPlan() { - // default constructor for OGM - } + PensionPlan() { + // default constructor for OGM + } - public PensionPlan(MonetaryAmount fundValue, String providerName) { - this.fundValue = fundValue; - this.providerName = providerName; - } + public PensionPlan(MonetaryAmount fundValue, String providerName) { + this.fundValue = fundValue; + this.providerName = providerName; + } - public Long getPensionPlanId() { - return pensionPlanId; - } + public Long getPensionPlanId() { + return pensionPlanId; + } - public String getProviderName() { - return providerName; - } + public String getProviderName() { + return providerName; + } - public MonetaryAmount getFundValue() { - return fundValue; - } + public MonetaryAmount getFundValue() { + return fundValue; + } - public JavaElement getJavaElement() { - return javaElement; - } + public JavaElement getJavaElement() { + return javaElement; + } - public void setJavaElement(JavaElement javaElement) { - this.javaElement = javaElement; - } + public void setJavaElement(JavaElement javaElement) { + this.javaElement = javaElement; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/SiteMember.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/SiteMember.java index 85dd30efb..3e4e102b5 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/SiteMember.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/integration/conversion/domain/SiteMember.java @@ -27,38 +27,35 @@ import org.neo4j.ogm.typeconversion.ByteArrayBase64Converter; */ public class SiteMember { - @GraphId - private Long id; + @GraphId private Long id; - @Convert(ByteArrayBase64Converter.class) - private byte[] profilePictureData; + @Convert(ByteArrayBase64Converter.class) private byte[] profilePictureData; - private BigInteger years; + private BigInteger years; - @Property(name = "rounding") - private List roundingModes; + @Property(name = "rounding") private List roundingModes; - public byte[] getProfilePictureData() { - return this.profilePictureData; - } + public byte[] getProfilePictureData() { + return this.profilePictureData; + } - public void setProfilePictureData(byte[] profilePictureData) { - this.profilePictureData = profilePictureData; - } + public void setProfilePictureData(byte[] profilePictureData) { + this.profilePictureData = profilePictureData; + } - public BigInteger getYears() { - return years; - } + public BigInteger getYears() { + return years; + } - public void setYears(BigInteger years) { - this.years = years; - } + public void setYears(BigInteger years) { + this.years = years; + } - public List getRoundingModes() { - return roundingModes; - } + public List getRoundingModes() { + return roundingModes; + } - public void setRoundingModes(List roundingModes) { - this.roundingModes = roundingModes; - } + public void setRoundingModes(List roundingModes) { + this.roundingModes = roundingModes; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/DerivedQueryIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/DerivedQueryIT.java index 099bed3a3..2a48d4994 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/DerivedQueryIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/DerivedQueryIT.java @@ -44,8 +44,6 @@ import org.springframework.data.neo4j.examples.movies.repo.CinemaRepository; import org.springframework.data.neo4j.examples.movies.repo.DirectorRepository; import org.springframework.data.neo4j.examples.movies.repo.RatingRepository; import org.springframework.data.neo4j.examples.movies.repo.UserRepository; -import org.springframework.data.neo4j.repositories.domain.Movie; -import org.springframework.data.neo4j.util.IterableUtils; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.PlatformTransactionManager; @@ -58,33 +56,26 @@ import org.springframework.transaction.support.TransactionTemplate; * @author Luanne Misquitta * @author Mark Angrish */ -@ContextConfiguration(classes = {MoviesContext.class}) +@ContextConfiguration(classes = { MoviesContext.class }) @RunWith(SpringJUnit4ClassRunner.class) public class DerivedQueryIT extends MultiDriverTestClass { private static GraphDatabaseService graphDatabaseService; - @Autowired - PlatformTransactionManager platformTransactionManager; + @Autowired PlatformTransactionManager platformTransactionManager; - @Autowired - private Session session; + @Autowired private Session session; - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; - @Autowired - private CinemaRepository cinemaRepository; + @Autowired private CinemaRepository cinemaRepository; - @Autowired - private RatingRepository ratingRepository; + @Autowired private RatingRepository ratingRepository; - @Autowired - private DirectorRepository directorRepository; + @Autowired private DirectorRepository directorRepository; private TransactionTemplate transactionTemplate; - @BeforeClass public static void beforeClass() { graphDatabaseService = getGraphDatabaseService(); @@ -116,7 +107,8 @@ public class DerivedQueryIT extends MultiDriverTestClass { @Test public void shouldFindUsersByMiddleName() { - executeUpdate("CREATE (m:User:Person {middleName:'Joseph'})<-[:FRIEND_OF]-(a:User:Person {middleName:'Mary', name: 'Joseph'})"); + executeUpdate( + "CREATE (m:User:Person {middleName:'Joseph'})<-[:FRIEND_OF]-(a:User:Person {middleName:'Mary', name: 'Joseph'})"); Collection users = userRepository.findByMiddleName("Joseph"); Iterator iterator = users.iterator(); @@ -135,7 +127,8 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindNodeEntitiesWithLabels() { - executeUpdate("CREATE (u:User:Person {name:'Michal'}) CREATE (p:Theatre {name:'Picturehouse', city:'London'}) CREATE (r:Theatre {name:'Ritzy', city:'London'}) CREATE (u)-[:VISITED]->(p)"); + executeUpdate( + "CREATE (u:User:Person {name:'Michal'}) CREATE (p:Theatre {name:'Picturehouse', city:'London'}) CREATE (r:Theatre {name:'Ritzy', city:'London'}) CREATE (u)-[:VISITED]->(p)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -162,8 +155,9 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindNodeEntitiesMultipleAndedProperties() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London'}) CREATE (r:Theatre {name:'Ritzy', city:'London'})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); + executeUpdate( + "CREATE (p:Theatre {name:'Picturehouse', city:'London'}) CREATE (r:Theatre {name:'Ritzy', city:'London'})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); List theatres = cinemaRepository.findByNameAndLocation("Ritzy", "London"); assertEquals(1, theatres.size()); @@ -175,8 +169,9 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindNodeEntititiesMultipleOredProperties() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London'}) CREATE (r:Theatre {name:'Ritzy', city:'London'})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); + executeUpdate( + "CREATE (p:Theatre {name:'Picturehouse', city:'London'}) CREATE (r:Theatre {name:'Ritzy', city:'London'})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); List theatres = cinemaRepository.findByNameOrLocation("Ritzy", "London"); assertEquals(2, theatres.size()); @@ -187,21 +182,22 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldReturnNoResultsCorrectly() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London'}) CREATE (r:Theatre {name:'Ritzy', city:'London'})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); + executeUpdate( + "CREATE (p:Theatre {name:'Picturehouse', city:'London'}) CREATE (r:Theatre {name:'Ritzy', city:'London'})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); Collection theatres = cinemaRepository.findByName("Does not exist"); assertEquals(0, theatres.size()); } - /** * @see DATAGRAPH-629 */ @Test public void shouldFindNodeEntititiesWithComparisonOperators() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); + executeUpdate( + "CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -232,8 +228,9 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindNodeEntititiesWithMultipleComparisonOperatorsAnded() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) CREATE (m:Theatre {name:'Regal', city:'Bombay', capacity: 4500})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); + executeUpdate( + "CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) CREATE (m:Theatre {name:'Regal', city:'Bombay', capacity: 4500})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -255,8 +252,9 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindNodeEntititiesWithMultipleComparisonOperatorsOred() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) CREATE (m:Theatre {name:'Regal', city:'Bombay', capacity: 9000})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); + executeUpdate( + "CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) CREATE (m:Theatre {name:'Regal', city:'Bombay', capacity: 9000})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -273,14 +271,14 @@ public class DerivedQueryIT extends MultiDriverTestClass { }); } - /** * @see DATAGRAPH-629 */ @Test public void shouldFindNodeEntititiesWithNestedProperty() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); + executeUpdate( + "CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r)"); List theatres = cinemaRepository.findByVisitedName("Michal"); assertEquals(1, theatres.size()); @@ -292,8 +290,9 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindNodeEntititiesWithBaseAndNestedProperty() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) CREATE (m:Theatre {name:'Regal', city:'Bombay', capacity: 5000})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r) CREATE (u)-[:VISITED]->(m)"); + executeUpdate( + "CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) CREATE (m:Theatre {name:'Regal', city:'Bombay', capacity: 5000})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r) CREATE (u)-[:VISITED]->(m)"); List theatres = cinemaRepository.findByLocationAndVisitedName("London", "Michal"); assertEquals(1, theatres.size()); @@ -301,18 +300,18 @@ public class DerivedQueryIT extends MultiDriverTestClass { } /** - * @see DATAGRAPH-662 - * //TODO FIXME + * @see DATAGRAPH-662 //TODO FIXME */ @Test(expected = UnsupportedOperationException.class) public void shouldFindNodeEntititiesWithBaseOrNestedProperty() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) CREATE (m:Theatre {name:'The Old Vic', city:'London', capacity: 5000})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r) CREATE (u)-[:VISITED]->(m)"); + executeUpdate( + "CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) CREATE (m:Theatre {name:'The Old Vic', city:'London', capacity: 5000})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u)-[:VISITED]->(r) CREATE (u)-[:VISITED]->(m)"); List theatres = cinemaRepository.findByLocationOrVisitedName("P", "Michal"); assertEquals(2, theatres.size()); assertTrue(theatres.contains(new Cinema("Ritzy"))); - //assertTrue(theatres.contains(new Cinema("Picturehouse"))); + // assertTrue(theatres.contains(new Cinema("Picturehouse"))); assertTrue(theatres.contains(new Cinema("The Old Vic"))); } @@ -321,9 +320,10 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindNodeEntitiesWithNestedRelationshipEntityProperty() { - executeUpdate("CREATE (m1:Movie {title:'Speed'}) CREATE (m2:Movie {title:'The Matrix'}) CREATE (m:Movie {title:'Chocolat'})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u1:User:Person {name:'Vince'}) " + - " CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2) CREATE (u1)-[:RATED {stars:3}]->(m)"); + executeUpdate( + "CREATE (m1:Movie {title:'Speed'}) CREATE (m2:Movie {title:'The Matrix'}) CREATE (m:Movie {title:'Chocolat'})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u1:User:Person {name:'Vince'}) " + + " CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2) CREATE (u1)-[:RATED {stars:3}]->(m)"); List users = userRepository.findByRatingsStars(3); assertEquals(2, users.size()); @@ -337,14 +337,11 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindNodeEntititiesWithTwoNestedPropertiesAndedAcrossDifferentRelatedNodeEntities() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + - " CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + - " CREATE (u:User:Person {name:'Michal'}) " + - " CREATE (u)-[:VISITED]->(r) CREATE (u)-[:VISITED]->(p)" + - " CREATE (m1:Movie {name:'San Andreas'}) " + - " CREATE (m2:Movie {name:'Pitch Perfect 2'})" + - " CREATE (p)-[:BLOCKBUSTER]->(m1)" + - " CREATE (r)-[:BLOCKBUSTER]->(m2)"); + executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + + " CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + + " CREATE (u:User:Person {name:'Michal'}) " + " CREATE (u)-[:VISITED]->(r) CREATE (u)-[:VISITED]->(p)" + + " CREATE (m1:Movie {name:'San Andreas'}) " + " CREATE (m2:Movie {name:'Pitch Perfect 2'})" + + " CREATE (p)-[:BLOCKBUSTER]->(m1)" + " CREATE (r)-[:BLOCKBUSTER]->(m2)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -362,17 +359,14 @@ public class DerivedQueryIT extends MultiDriverTestClass { /** * @see DATAGRAPH-662 */ - //FIXME: OR is not supported for nested properties on an entity + // FIXME: OR is not supported for nested properties on an entity @Test(expected = UnsupportedOperationException.class) public void shouldFindNodeEntititiesWithTwoNestedPropertiesOred() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + - " CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + - " CREATE (u:User:Person {name:'Michal'}) " + - " CREATE (u)-[:VISITED]->(r) CREATE (u)-[:VISITED]->(p)" + - " CREATE (m1:Movie {title:'San Andreas'}) " + - " CREATE (m2:Movie {title:'Pitch Perfect 2'})" + - " CREATE (p)-[:BLOCKBUSTER]->(m1)" + - " CREATE (r)-[:BLOCKBUSTER]->(m2)"); + executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + + " CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + + " CREATE (u:User:Person {name:'Michal'}) " + " CREATE (u)-[:VISITED]->(r) CREATE (u)-[:VISITED]->(p)" + + " CREATE (m1:Movie {title:'San Andreas'}) " + " CREATE (m2:Movie {title:'Pitch Perfect 2'})" + + " CREATE (p)-[:BLOCKBUSTER]->(m1)" + " CREATE (r)-[:BLOCKBUSTER]->(m2)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -393,10 +387,10 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindNodeEntititiesWithMultipleNestedPropertiesAnded() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + - " CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + - " CREATE (u:User:Person {name:'Michal', middleName:'M'}) CREATE (u1:User:Person {name:'Vince', middleName:'M'}) " + - " CREATE (u)-[:VISITED]->(p) CREATE (u1)-[:VISITED]->(r)"); + executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + + " CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + + " CREATE (u:User:Person {name:'Michal', middleName:'M'}) CREATE (u1:User:Person {name:'Vince', middleName:'M'}) " + + " CREATE (u)-[:VISITED]->(p) CREATE (u1)-[:VISITED]->(r)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -416,9 +410,10 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindNodeEntititiesWithRelationshipEntityAndNestedProperty() { - executeUpdate("CREATE (m1:Movie {title:'Speed'}) CREATE (m2:Movie {title:'The Matrix'}) CREATE (m:Movie {title:'Chocolat'})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u1:User:Person {name:'Vince'}) CREATE (g:Genre {name:'Thriller'}) CREATE (u)-[:INTERESTED]->(g) " + - " CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2) CREATE (u1)-[:RATED {stars:3}]->(m)"); + executeUpdate( + "CREATE (m1:Movie {title:'Speed'}) CREATE (m2:Movie {title:'The Matrix'}) CREATE (m:Movie {title:'Chocolat'})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u1:User:Person {name:'Vince'}) CREATE (g:Genre {name:'Thriller'}) CREATE (u)-[:INTERESTED]->(g) " + + " CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2) CREATE (u1)-[:RATED {stars:3}]->(m)"); List users = userRepository.findByRatingsStarsAndInterestedName(3, "Thriller"); assertEquals(1, users.size()); @@ -430,8 +425,7 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindNodeEntitiesByRegularExpressionMatchingOnPropertiesInDerivedFinderMethods() { - executeUpdate("CREATE (:Theatre {name:'Odeon', city:'Preston'}), " - + "(:Theatre {name:'Vue', city:'Dumfries'}), " + executeUpdate("CREATE (:Theatre {name:'Odeon', city:'Preston'}), " + "(:Theatre {name:'Vue', city:'Dumfries'}), " + "(:Theatre {name:'PVR', city:'Mumbai'}) "); // ideally, I'd name this to be "findWhereNameMatches" or "findByNameMatching" @@ -446,8 +440,7 @@ public class DerivedQueryIT extends MultiDriverTestClass { @Test public void shouldMatchNodeEntitiesUsingCaseInsensitiveLikeWithWildcards() { executeUpdate("CREATE (:Theatre {name:'IMAX', city:'Chesterfield'}), " - + "(:Theatre {name:'Odeon', city:'Manchester'}), " - + "(:Theatre {name:'IMAX', city:'Edinburgh'}) "); + + "(:Theatre {name:'Odeon', city:'Manchester'}), " + "(:Theatre {name:'IMAX', city:'Edinburgh'}) "); List cinemas = cinemaRepository.findByLocationLike("*chest*"); assertEquals("The wrong number of cinemas was returned", 2, cinemas.size()); @@ -471,9 +464,8 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldMatchNodeEntitiesUsingNotLikeWithAsteriskWildcards() { - executeUpdate("CREATE (:User:Person {name:'Jeff'}), " - + "(:User:Person {name:'Jeremy'}), " - + "(:User:Person {name:'Alan'})"); + executeUpdate( + "CREATE (:User:Person {name:'Jeff'}), " + "(:User:Person {name:'Jeremy'}), " + "(:User:Person {name:'Alan'})"); List nonMatchingUsers = userRepository.findByNameIsNotLike("Je*"); assertEquals("The wrong number of users was returned", 1, nonMatchingUsers.size()); @@ -485,7 +477,8 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindDirectorsByName() { - executeUpdate("CREATE (m:User:Person {name:'Michal'})<-[:FRIEND_OF]-(a:User:Person {name:'Adam'}) CREATE (d:Director:Person {name:'Vince'})"); + executeUpdate( + "CREATE (m:User:Person {name:'Michal'})<-[:FRIEND_OF]-(a:User:Person {name:'Adam'}) CREATE (d:Director:Person {name:'Vince'})"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -504,21 +497,17 @@ public class DerivedQueryIT extends MultiDriverTestClass { }); } - /** * @see DATAGRAPH-744 */ @Test public void shouldFindUserWithCustomDepth() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + - " CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + - " CREATE (u:User:Person {name:'Michal'}) " + - " CREATE (u)-[:VISITED]->(r) CREATE (u)-[:VISITED]->(p)" + - " CREATE (m1:Movie {name:'San Andreas'}) " + - " CREATE (m2:Movie {name:'Pitch Perfect 2'})" + - " CREATE (p)-[:BLOCKBUSTER]->(m1)" + - " CREATE (r)-[:BLOCKBUSTER]->(m2)" + - " CREATE (u)-[:RATED {stars :3}]->(m1)"); + executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + + " CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + + " CREATE (u:User:Person {name:'Michal'}) " + " CREATE (u)-[:VISITED]->(r) CREATE (u)-[:VISITED]->(p)" + + " CREATE (m1:Movie {name:'San Andreas'}) " + " CREATE (m2:Movie {name:'Pitch Perfect 2'})" + + " CREATE (p)-[:BLOCKBUSTER]->(m1)" + " CREATE (r)-[:BLOCKBUSTER]->(m2)" + + " CREATE (u)-[:RATED {stars :3}]->(m1)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -546,13 +535,13 @@ public class DerivedQueryIT extends MultiDriverTestClass { }); } - /** * @see DATAGRAPH-744 */ @Test public void shouldFindUsersByNameWithStaticDepth() { - executeUpdate("CREATE (m:User:Person {name:'Michal', surname:'Bachman'})<-[:FRIEND_OF]-(a:User:Person {name:'Adam', surname:'George'})"); + executeUpdate( + "CREATE (m:User:Person {name:'Michal', surname:'Bachman'})<-[:FRIEND_OF]-(a:User:Person {name:'Adam', surname:'George'})"); User user = userRepository.findBySurname("Bachman"); assertNotNull(user); @@ -566,9 +555,10 @@ public class DerivedQueryIT extends MultiDriverTestClass { */ @Test public void shouldSupportLiteralMapsInQueryResults() { - executeUpdate("CREATE (m1:Movie {title:'Speed'}) CREATE (m2:Movie {title:'The Matrix'}) CREATE (m:Movie {title:'Chocolat'})" + - " CREATE (u:User:Person {name:'Michal'}) CREATE (u1:User:Person {name:'Vince'}) " + - " CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2) CREATE (u1)-[:RATED {stars:3}]->(m)"); + executeUpdate( + "CREATE (m1:Movie {title:'Speed'}) CREATE (m2:Movie {title:'The Matrix'}) CREATE (m:Movie {title:'Chocolat'})" + + " CREATE (u:User:Person {name:'Michal'}) CREATE (u1:User:Person {name:'Vince'}) " + + " CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2) CREATE (u1)-[:RATED {stars:3}]->(m)"); List result = userRepository.findRatingsWithLiteralMap(); assertNotNull(result); @@ -590,10 +580,11 @@ public class DerivedQueryIT extends MultiDriverTestClass { @Test public void shouldAllowMultiThreadedDerivedFinderExecution() throws InterruptedException { int numThreads = 3; - executeUpdate("CREATE (m:User:Person {name:'Michal', surname:'Bachman'}), (a:User:Person {name:'Adam', surname:'George'}), (l:User:Person {name:'Luanne', surname:'Misquitta'})"); + executeUpdate( + "CREATE (m:User:Person {name:'Michal', surname:'Bachman'}), (a:User:Person {name:'Adam', surname:'George'}), (l:User:Person {name:'Luanne', surname:'Misquitta'})"); - String[] firstNames = new String[]{"Michal", "Adam", "Luanne"}; - String[] lastNames = new String[]{"Bachman", "George", "Misquitta"}; + String[] firstNames = new String[] { "Michal", "Adam", "Luanne" }; + String[] lastNames = new String[] { "Bachman", "George", "Misquitta" }; ExecutorService executor = Executors.newFixedThreadPool(numThreads); CountDownLatch latch = new CountDownLatch(numThreads); @@ -621,23 +612,27 @@ public class DerivedQueryIT extends MultiDriverTestClass { Pageable pageable = new PageRequest(0, 4); Page page = userRepository.findByNameAndSurname("A", "B", pageable); assertEquals(4, page.getNumberOfElements()); - assertEquals(8, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(8, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate assertTrue(page.hasNext()); page = userRepository.findByNameAndSurname("A", "B", page.nextPageable()); assertEquals(4, page.getNumberOfElements()); - assertEquals(12, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(12, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate assertTrue(page.hasNext()); page = userRepository.findByNameAndSurname("A", "B", page.nextPageable()); assertEquals(2, page.getNumberOfElements()); - assertEquals(10, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(10, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate assertFalse(page.hasNext()); page = userRepository.findByNameAndSurname("A", "B", new PageRequest(0, 10)); assertEquals(10, page.getNumberOfElements()); - assertEquals(20, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate - assertTrue(page.hasNext()); //this cannot be relied upon because the total number of elements is an estimate + assertEquals(20, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate + assertTrue(page.hasNext()); // this cannot be relied upon because the total number of elements is an estimate page = userRepository.findByNameAndSurname("A", "B", page.nextPageable()); assertEquals(0, page.getNumberOfElements()); @@ -675,7 +670,6 @@ public class DerivedQueryIT extends MultiDriverTestClass { assertFalse(page.hasNext()); } - class DerivedQueryRunner implements Runnable { private final CountDownLatch latch; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/DerivedRelationshipEntityQueryIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/DerivedRelationshipEntityQueryIT.java index 0dfa501dc..e8e7ec956 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/DerivedRelationshipEntityQueryIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/DerivedRelationshipEntityQueryIT.java @@ -32,8 +32,6 @@ import org.springframework.data.neo4j.examples.movies.domain.User; import org.springframework.data.neo4j.examples.movies.repo.CinemaRepository; import org.springframework.data.neo4j.examples.movies.repo.RatingRepository; import org.springframework.data.neo4j.examples.movies.repo.UserRepository; -import org.springframework.data.neo4j.repositories.domain.Movie; -import org.springframework.data.neo4j.util.IterableUtils; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.PlatformTransactionManager; @@ -47,23 +45,19 @@ import org.springframework.transaction.support.TransactionTemplate; * @author Mark Angrish * @author Vince Bickers */ -@ContextConfiguration(classes = {MoviesContext.class}) +@ContextConfiguration(classes = { MoviesContext.class }) @RunWith(SpringJUnit4ClassRunner.class) public class DerivedRelationshipEntityQueryIT extends MultiDriverTestClass { private static GraphDatabaseService graphDatabaseService; - @Autowired - PlatformTransactionManager platformTransactionManager; + @Autowired PlatformTransactionManager platformTransactionManager; - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; - @Autowired - private CinemaRepository cinemaRepository; + @Autowired private CinemaRepository cinemaRepository; - @Autowired - private RatingRepository ratingRepository; + @Autowired private RatingRepository ratingRepository; private TransactionTemplate transactionTemplate; @@ -195,7 +189,6 @@ public class DerivedRelationshipEntityQueryIT extends MultiDriverTestClass { assertEquals(0, ratings.size()); } - /** * @see DATAGRAPH-629 */ @@ -226,8 +219,9 @@ public class DerivedRelationshipEntityQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindRelEntitiesWithNestedStartNodeProperty() { - executeUpdate("CREATE (m1:Movie {name:'Speed'}) CREATE (m2:Movie {name:'The Matrix'}) CREATE (m:Movie {name:'Chocolat'})" + - " CREATE (u:User {name:'Michal'}) CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)"); + executeUpdate( + "CREATE (m1:Movie {name:'Speed'}) CREATE (m2:Movie {name:'The Matrix'}) CREATE (m:Movie {name:'Chocolat'})" + + " CREATE (u:User {name:'Michal'}) CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -246,8 +240,9 @@ public class DerivedRelationshipEntityQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindRelEntitiesWithNestedEndNodeProperty() { - executeUpdate("CREATE (m1:Movie {name:'Finding Dory'}) CREATE (m2:Movie {name:'Captain America'}) CREATE (m:Movie {name:'X-Men'})" + - " CREATE (u:User {name:'Vince'}) CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)"); + executeUpdate( + "CREATE (m1:Movie {name:'Finding Dory'}) CREATE (m2:Movie {name:'Captain America'}) CREATE (m:Movie {name:'X-Men'})" + + " CREATE (u:User {name:'Vince'}) CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -269,8 +264,9 @@ public class DerivedRelationshipEntityQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindRelEntitiesWithBothStartEndNestedProperty() { - executeUpdate("CREATE (m1:Movie {name:'Independence Day: Resurgence'}) CREATE (m2:Movie {name:'The Conjuring 2'}) CREATE (m:Movie {name:'The BFG'})" + - " CREATE (u:User {name:'Daniela'}) CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)"); + executeUpdate( + "CREATE (m1:Movie {name:'Independence Day: Resurgence'}) CREATE (m2:Movie {name:'The Conjuring 2'}) CREATE (m:Movie {name:'The BFG'})" + + " CREATE (u:User {name:'Daniela'}) CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -292,8 +288,9 @@ public class DerivedRelationshipEntityQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindRelEntitiesWithBaseAndNestedStartNodePropertyAnded() { - executeUpdate("CREATE (m1:Movie {name:'The Shallows'}) CREATE (m2:Movie {name:'Central Intelligence'}) CREATE (m:Movie {name:'Now you see me'})" + - " CREATE (u:User {name:'Luanne'}) CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)"); + executeUpdate( + "CREATE (m1:Movie {name:'The Shallows'}) CREATE (m2:Movie {name:'Central Intelligence'}) CREATE (m:Movie {name:'Now you see me'})" + + " CREATE (u:User {name:'Luanne'}) CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -311,15 +308,15 @@ public class DerivedRelationshipEntityQueryIT extends MultiDriverTestClass { } /** - * @see DATAGRAPH-662 - * //TODO FIXME + * @see DATAGRAPH-662 //TODO FIXME */ @Test(expected = UnsupportedOperationException.class) public void shouldFindRelEntitiesWithBaseAndNestedStartNodePropertyOred() { - executeUpdate("CREATE (m1:Movie {name:'Swiss Army Man'}) CREATE (m2:Movie {name:'Me Before You'}) CREATE (m:Movie {name:'X-Men Apocalypse'})" + - " CREATE (u:User {name:'Mark'}) CREATE (u2:User {name:'Adam'}) " + - " CREATE (u)-[:RATED {stars:2}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)" + - " CREATE (u2)-[:RATED {stars:3}]->(m)"); + executeUpdate( + "CREATE (m1:Movie {name:'Swiss Army Man'}) CREATE (m2:Movie {name:'Me Before You'}) CREATE (m:Movie {name:'X-Men Apocalypse'})" + + " CREATE (u:User {name:'Mark'}) CREATE (u2:User {name:'Adam'}) " + + " CREATE (u)-[:RATED {stars:2}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)" + + " CREATE (u2)-[:RATED {stars:3}]->(m)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -342,10 +339,11 @@ public class DerivedRelationshipEntityQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindRelEntitiesWithBaseAndNestedEndNodeProperty() { - executeUpdate("CREATE (m1:Movie {name:'Our Kind of Traitor'}) CREATE (m2:Movie {name:'Teenage Mutant Ninja Turtles'}) CREATE (m:Movie {name:'Zootopia'})" + - " CREATE (u:User {name:'Chris'}) CREATE (u2:User {name:'Katerina'}) " + - " CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)" + - " CREATE (u2)-[:RATED {stars:4}]->(m2)"); + executeUpdate( + "CREATE (m1:Movie {name:'Our Kind of Traitor'}) CREATE (m2:Movie {name:'Teenage Mutant Ninja Turtles'}) CREATE (m:Movie {name:'Zootopia'})" + + " CREATE (u:User {name:'Chris'}) CREATE (u2:User {name:'Katerina'}) " + + " CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)" + + " CREATE (u2)-[:RATED {stars:4}]->(m2)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -367,8 +365,9 @@ public class DerivedRelationshipEntityQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindRelEntitiesWithBaseAndBothStartEndNestedProperty() { - executeUpdate("CREATE (m1:Movie {name:'The Jungle Book'}) CREATE (m2:Movie {name:'The Angry Birds Movie'}) CREATE (m:Movie {name:'Alice Through The Looking Glass'})" + - " CREATE (u:User {name:'Alessandro'}) CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)"); + executeUpdate( + "CREATE (m1:Movie {name:'The Jungle Book'}) CREATE (m2:Movie {name:'The Angry Birds Movie'}) CREATE (m:Movie {name:'Alice Through The Looking Glass'})" + + " CREATE (u:User {name:'Alessandro'}) CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -390,10 +389,11 @@ public class DerivedRelationshipEntityQueryIT extends MultiDriverTestClass { */ @Test public void shouldFindRelEntitiesWithTwoStartNodeNestedProperties() { - executeUpdate("CREATE (m1:Movie {name:'Batman v Superman'}) CREATE (m2:Movie {name:'Genius'}) CREATE (m:Movie {name:'Home'})" + - " CREATE (u:User {name:'David', middleName:'M'}) CREATE (u2:User {name:'Martin', middleName:'M'}) " + - " CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)" + - " CREATE (u2)-[:RATED {stars:4}]->(m2)"); + executeUpdate( + "CREATE (m1:Movie {name:'Batman v Superman'}) CREATE (m2:Movie {name:'Genius'}) CREATE (m:Movie {name:'Home'})" + + " CREATE (u:User {name:'David', middleName:'M'}) CREATE (u2:User {name:'Martin', middleName:'M'}) " + + " CREATE (u)-[:RATED {stars:3}]->(m1) CREATE (u)-[:RATED {stars:4}]->(m2)" + + " CREATE (u2)-[:RATED {stars:4}]->(m2)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/PagedQueryIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/PagedQueryIT.java index 1c329c833..1e717ab8c 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/PagedQueryIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/PagedQueryIT.java @@ -23,7 +23,11 @@ import org.junit.runner.RunWith; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.ogm.testutil.MultiDriverTestClass; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.*; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.data.domain.Sort; import org.springframework.data.neo4j.examples.movies.context.MoviesContext; import org.springframework.data.neo4j.examples.movies.domain.Cinema; import org.springframework.data.neo4j.examples.movies.domain.queryresult.CinemaQueryResult; @@ -43,17 +47,15 @@ import org.springframework.transaction.support.TransactionTemplate; * @author Mark Angrish * @see DATAGRAPH-680 */ -@ContextConfiguration(classes = {MoviesContext.class}) +@ContextConfiguration(classes = { MoviesContext.class }) @RunWith(SpringJUnit4ClassRunner.class) public class PagedQueryIT extends MultiDriverTestClass { private static GraphDatabaseService graphDatabaseService; - @Autowired - PlatformTransactionManager platformTransactionManager; + @Autowired PlatformTransactionManager platformTransactionManager; - @Autowired - private CinemaRepository cinemaRepository; + @Autowired private CinemaRepository cinemaRepository; private TransactionTemplate transactionTemplate; @@ -69,7 +71,8 @@ public class PagedQueryIT extends MultiDriverTestClass { } public void setup() { - String[] names = new String[]{"Picturehouse", "Regal", "Ritzy", "Metro", "Inox", "PVR", "Cineplex", "Landmark", "Rainbow", "Movietime"}; + String[] names = new String[] { "Picturehouse", "Regal", "Ritzy", "Metro", "Inox", "PVR", "Cineplex", "Landmark", + "Rainbow", "Movietime" }; for (String name : names) { Cinema cinema = new Cinema(name); cinema.setLocation("London"); @@ -82,7 +85,6 @@ public class PagedQueryIT extends MultiDriverTestClass { graphDatabaseService.execute(cypher); } - @Test @Transactional public void shouldFindPagedCinemas() { @@ -91,17 +93,20 @@ public class PagedQueryIT extends MultiDriverTestClass { Page page = cinemaRepository.getPagedCinemas(pageable); assertEquals(3, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(6, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(6, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate page = cinemaRepository.getPagedCinemas(page.nextPageable()); assertEquals(3, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(9, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(9, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate page = cinemaRepository.getPagedCinemas(page.nextPageable()); assertEquals(3, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(12, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(12, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate page = cinemaRepository.getPagedCinemas(page.nextPageable()); assertEquals(1, page.getNumberOfElements()); @@ -123,17 +128,20 @@ public class PagedQueryIT extends MultiDriverTestClass { assertEquals(3, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(6, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(6, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate page = cinemaRepository.getPagedCinemaQueryResults(page.nextPageable()); assertEquals(3, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(9, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(9, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate page = cinemaRepository.getPagedCinemaQueryResults(page.nextPageable()); assertEquals(3, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(12, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(12, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate page = cinemaRepository.getPagedCinemaQueryResults(page.nextPageable()); assertEquals(1, page.getNumberOfElements()); @@ -167,8 +175,7 @@ public class PagedQueryIT extends MultiDriverTestClass { } /** - * Repeats shouldFindPagedCinemas for query results - interfaces - * * @see DATAGRAPH-893 + * Repeats shouldFindPagedCinemas for query results - interfaces * @see DATAGRAPH-893 */ @Test @Transactional @@ -180,17 +187,20 @@ public class PagedQueryIT extends MultiDriverTestClass { assertEquals(3, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(6, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(6, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate page = cinemaRepository.getPagedCinemaQueryResultInterfaces(page.nextPageable()); assertEquals(3, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(9, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(9, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate page = cinemaRepository.getPagedCinemaQueryResultInterfaces(page.nextPageable()); assertEquals(3, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(12, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(12, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate page = cinemaRepository.getPagedCinemaQueryResultInterfaces(page.nextPageable()); assertEquals(1, page.getNumberOfElements()); @@ -208,7 +218,8 @@ public class PagedQueryIT extends MultiDriverTestClass { page = cinemaRepository.getPagedCinemas(page.nextPageable()); assertEquals(5, page.getNumberOfElements()); - assertTrue(page.hasNext()); //this is an estimate and so for the last page, page.hasNext() is true when the total number of elements / total number of pages=0 + assertTrue(page.hasNext()); // this is an estimate and so for the last page, page.hasNext() is true when the total + // number of elements / total number of pages=0 page = cinemaRepository.getPagedCinemas(page.nextPageable()); assertEquals(0, page.getNumberOfElements()); @@ -222,22 +233,26 @@ public class PagedQueryIT extends MultiDriverTestClass { Pageable pageable = new PageRequest(0, 3); Page page = cinemaRepository.getPagedCinemasWithPageCount(pageable); assertEquals(3, page.getNumberOfElements()); - assertEquals(10, page.getTotalElements()); //With a count query, the total elements should equal the number returned by the count query + assertEquals(10, page.getTotalElements()); // With a count query, the total elements should equal the number + // returned by the count query assertTrue(page.hasNext()); page = cinemaRepository.getPagedCinemasWithPageCount(page.nextPageable()); assertEquals(3, page.getNumberOfElements()); - assertEquals(10, page.getTotalElements()); //With a count query, the total elements should equal the number returned by the count query + assertEquals(10, page.getTotalElements()); // With a count query, the total elements should equal the number + // returned by the count query assertTrue(page.hasNext()); page = cinemaRepository.getPagedCinemasWithPageCount(page.nextPageable()); assertEquals(3, page.getNumberOfElements()); - assertEquals(10, page.getTotalElements()); //With a count query, the total elements should equal the number returned by the count query + assertEquals(10, page.getTotalElements()); // With a count query, the total elements should equal the number + // returned by the count query assertTrue(page.hasNext()); page = cinemaRepository.getPagedCinemasWithPageCount(page.nextPageable()); assertEquals(1, page.getNumberOfElements()); - assertEquals(10, page.getTotalElements()); //With a count query, the total elements should equal the number returned by the count query + assertEquals(10, page.getTotalElements()); // With a count query, the total elements should equal the number + // returned by the count query assertFalse(page.hasNext()); } @@ -248,13 +263,15 @@ public class PagedQueryIT extends MultiDriverTestClass { Pageable pageable = new PageRequest(0, 5); Page page = cinemaRepository.getPagedCinemasWithPageCount(pageable); assertEquals(5, page.getNumberOfElements()); - assertEquals(10, page.getTotalElements()); //With a count query, the total elements should equal the number returned by the count query + assertEquals(10, page.getTotalElements()); // With a count query, the total elements should equal the number + // returned by the count query assertTrue(page.hasNext()); page = cinemaRepository.getPagedCinemasWithPageCount(page.nextPageable()); assertEquals(5, page.getNumberOfElements()); - assertEquals(10, page.getTotalElements()); //With a count query, the total elements should equal the number returned by the count query - assertFalse(page.hasNext()); //with a count query, the next page calculation is correct + assertEquals(10, page.getTotalElements()); // With a count query, the total elements should equal the number + // returned by the count query + assertFalse(page.hasNext()); // with a count query, the next page calculation is correct } @Test @@ -264,13 +281,15 @@ public class PagedQueryIT extends MultiDriverTestClass { Pageable pageable = new PageRequest(0, 5); Page page = cinemaRepository.getPagedCinemasByCityWithPageCount("London", pageable); assertEquals(5, page.getNumberOfElements()); - assertEquals(10, page.getTotalElements()); //With a count query, the total elements should equal the number returned by the count query + assertEquals(10, page.getTotalElements()); // With a count query, the total elements should equal the number + // returned by the count query assertTrue(page.hasNext()); page = cinemaRepository.getPagedCinemasByCityWithPageCount("London", page.nextPageable()); assertEquals(5, page.getNumberOfElements()); - assertEquals(10, page.getTotalElements()); //With a count query, the total elements should equal the number returned by the count query - assertFalse(page.hasNext()); //with a count query, the next page calculation is correct + assertEquals(10, page.getTotalElements()); // With a count query, the total elements should equal the number + // returned by the count query + assertFalse(page.hasNext()); // with a count query, the next page calculation is correct } @Test @@ -309,7 +328,6 @@ public class PagedQueryIT extends MultiDriverTestClass { assertFalse(slice.hasNext()); } - /** * @see DATAGRAPH-887 */ @@ -322,7 +340,8 @@ public class PagedQueryIT extends MultiDriverTestClass { Page page = cinemaRepository.findByLocation("London", pageable); assertEquals(4, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(8, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(8, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate assertEquals("Cineplex", page.getContent().get(0).getName()); assertEquals("Inox", page.getContent().get(1).getName()); assertEquals("Landmark", page.getContent().get(2).getName()); @@ -331,7 +350,8 @@ public class PagedQueryIT extends MultiDriverTestClass { page = cinemaRepository.findByLocation("London", page.nextPageable()); assertEquals(4, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(12, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(12, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate assertEquals("Movietime", page.getContent().get(0).getName()); assertEquals("PVR", page.getContent().get(1).getName()); assertEquals("Picturehouse", page.getContent().get(2).getName()); @@ -340,7 +360,8 @@ public class PagedQueryIT extends MultiDriverTestClass { page = cinemaRepository.findByLocation("London", page.nextPageable()); assertEquals(2, page.getNumberOfElements()); assertFalse(page.hasNext()); - assertEquals(10, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(10, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate assertEquals("Regal", page.getContent().get(0).getName()); assertEquals("Ritzy", page.getContent().get(1).getName()); } @@ -350,21 +371,21 @@ public class PagedQueryIT extends MultiDriverTestClass { */ @Test public void shouldSortPageWhenNestedPropertyIsInvolved() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + - "CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + - "CREATE (m:Theatre {name:'Picturehouse', city:'London', capacity: 5000}) " + - "CREATE (u:User {name:'Michal'}) " + - "CREATE (u)-[:VISITED]->(r) " + - "CREATE (u)-[:VISITED]->(m)"); + executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + + "CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + + "CREATE (m:Theatre {name:'Picturehouse', city:'London', capacity: 5000}) " + + "CREATE (u:User {name:'Michal'}) " + "CREATE (u)-[:VISITED]->(r) " + "CREATE (u)-[:VISITED]->(m)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { - Page page = cinemaRepository.findByLocationAndVisitedName("London", "Michal", new PageRequest(0, 1, Sort.Direction.DESC, "name")); + Page page = cinemaRepository.findByLocationAndVisitedName("London", "Michal", + new PageRequest(0, 1, Sort.Direction.DESC, "name")); assertEquals(1, page.getNumberOfElements()); assertEquals("Ritzy", page.getContent().get(0).getName()); - page = cinemaRepository.findByLocationAndVisitedName("London", "Michal", new PageRequest(1, 1, Sort.Direction.DESC, "name")); + page = cinemaRepository.findByLocationAndVisitedName("London", "Michal", + new PageRequest(1, 1, Sort.Direction.DESC, "name")); assertEquals(1, page.getNumberOfElements()); assertEquals("Picturehouse", page.getContent().get(0).getName()); } @@ -376,17 +397,16 @@ public class PagedQueryIT extends MultiDriverTestClass { */ @Test public void shouldSortPageByNestedPropertyIsInvolved() { - executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + - "CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + - "CREATE (m:Theatre {name:'Regal', city:'Bombay', capacity: 5000}) " + - "CREATE (u:User {name:'Michal'}) " + - "CREATE (u)-[:VISITED]->(r) " + - "CREATE (u)-[:VISITED]->(m)"); + executeUpdate("CREATE (p:Theatre {name:'Picturehouse', city:'London', capacity:5000}) " + + "CREATE (r:Theatre {name:'Ritzy', city:'London', capacity: 7500}) " + + "CREATE (m:Theatre {name:'Regal', city:'Bombay', capacity: 5000}) " + "CREATE (u:User {name:'Michal'}) " + + "CREATE (u)-[:VISITED]->(r) " + "CREATE (u)-[:VISITED]->(m)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { - Page page = cinemaRepository.findByVisitedName("Michal", new PageRequest(0, 1, Sort.Direction.ASC, "location")); + Page page = cinemaRepository.findByVisitedName("Michal", + new PageRequest(0, 1, Sort.Direction.ASC, "location")); assertEquals(1, page.getNumberOfElements()); assertEquals("Regal", page.getContent().get(0).getName()); @@ -462,7 +482,8 @@ public class PagedQueryIT extends MultiDriverTestClass { Page page = cinemaRepository.getPagedCinemas(pageable); assertEquals(4, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(8, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(8, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate assertEquals("Cineplex", page.getContent().get(0).getName()); assertEquals("Inox", page.getContent().get(1).getName()); assertEquals("Landmark", page.getContent().get(2).getName()); @@ -471,7 +492,8 @@ public class PagedQueryIT extends MultiDriverTestClass { page = cinemaRepository.getPagedCinemas(page.nextPageable()); assertEquals(4, page.getNumberOfElements()); assertTrue(page.hasNext()); - assertEquals(12, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(12, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate assertEquals("Movietime", page.getContent().get(0).getName()); assertEquals("PVR", page.getContent().get(1).getName()); assertEquals("Picturehouse", page.getContent().get(2).getName()); @@ -480,7 +502,8 @@ public class PagedQueryIT extends MultiDriverTestClass { page = cinemaRepository.getPagedCinemas(page.nextPageable()); assertEquals(2, page.getNumberOfElements()); assertFalse(page.hasNext()); - assertEquals(10, page.getTotalElements()); //this should not be relied on as incorrect as the total elements is an estimate + assertEquals(10, page.getTotalElements()); // this should not be relied on as incorrect as the total elements is an + // estimate assertEquals("Regal", page.getContent().get(0).getName()); assertEquals("Ritzy", page.getContent().get(1).getName()); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/QueryIntegrationIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/QueryIntegrationIT.java index 218eea4f5..cbb69f216 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/QueryIntegrationIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/QueryIntegrationIT.java @@ -16,7 +16,12 @@ import static org.junit.Assert.*; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import org.junit.Before; import org.junit.BeforeClass; @@ -30,7 +35,11 @@ import org.springframework.data.neo4j.examples.movies.context.MoviesContext; import org.springframework.data.neo4j.examples.movies.domain.Rating; import org.springframework.data.neo4j.examples.movies.domain.TempMovie; import org.springframework.data.neo4j.examples.movies.domain.User; -import org.springframework.data.neo4j.examples.movies.domain.queryresult.*; +import org.springframework.data.neo4j.examples.movies.domain.queryresult.EntityWrappingQueryResult; +import org.springframework.data.neo4j.examples.movies.domain.queryresult.Gender; +import org.springframework.data.neo4j.examples.movies.domain.queryresult.RichUserQueryResult; +import org.springframework.data.neo4j.examples.movies.domain.queryresult.UserQueryResult; +import org.springframework.data.neo4j.examples.movies.domain.queryresult.UserQueryResultInterface; import org.springframework.data.neo4j.examples.movies.repo.CinemaRepository; import org.springframework.data.neo4j.examples.movies.repo.UnmanagedUserPojo; import org.springframework.data.neo4j.examples.movies.repo.UserRepository; @@ -46,24 +55,20 @@ import org.springframework.transaction.support.TransactionTemplate; * @author Luanne Misquitta * @author Mark Angrish */ -@ContextConfiguration(classes = {MoviesContext.class}) +@ContextConfiguration(classes = { MoviesContext.class }) @RunWith(SpringJUnit4ClassRunner.class) public class QueryIntegrationIT extends MultiDriverTestClass { private static GraphDatabaseService graphDatabaseService; - @Autowired - PlatformTransactionManager platformTransactionManager; + @Autowired PlatformTransactionManager platformTransactionManager; - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; - @Autowired - private CinemaRepository cinemaRepository; + @Autowired private CinemaRepository cinemaRepository; private TransactionTemplate transactionTemplate; - @Before public void init() { clearDatabase(); @@ -86,17 +91,10 @@ public class QueryIntegrationIT extends MultiDriverTestClass { @Test public void shouldFindArbitraryGraph() { - executeUpdate( - "CREATE " + - "(dh:Movie {name:'Die Hard'}), " + - "(fe:Movie {name: 'The Fifth Element'}), " + - "(bw:User {name: 'Bruce Willis'}), " + - "(ar:User {name: 'Alan Rickman'}), " + - "(mj:User {name: 'Milla Jovovich'}), " + - "(mj)-[:ACTED_IN]->(fe), " + - "(ar)-[:ACTED_IN]->(dh), " + - "(bw)-[:ACTED_IN]->(dh), " + - "(bw)-[:ACTED_IN]->(fe)"); + executeUpdate("CREATE " + "(dh:Movie {name:'Die Hard'}), " + "(fe:Movie {name: 'The Fifth Element'}), " + + "(bw:User {name: 'Bruce Willis'}), " + "(ar:User {name: 'Alan Rickman'}), " + + "(mj:User {name: 'Milla Jovovich'}), " + "(mj)-[:ACTED_IN]->(fe), " + "(ar)-[:ACTED_IN]->(dh), " + + "(bw)-[:ACTED_IN]->(dh), " + "(bw)-[:ACTED_IN]->(fe)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -205,7 +203,8 @@ public class QueryIntegrationIT extends MultiDriverTestClass { */ @Test public void shouldFindUsersAndMapThemToConcreteQueryResultObjectCollection() { - executeUpdate("CREATE (g:User {name:'Gary', age:32}), (s:User {name:'Sheila', age:29}), (v:User {name:'Vince', age:66})"); + executeUpdate( + "CREATE (g:User {name:'Gary', age:32}), (s:User {name:'Sheila', age:29}), (v:User {name:'Vince', age:66})"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -246,7 +245,8 @@ public class QueryIntegrationIT extends MultiDriverTestClass { @Test public void shouldFindUsersAndMapThemToProxiedQueryResultInterface() { - executeUpdate("CREATE (:User {name:'Morne', age:30}), (:User {name:'Abraham', age:31}), (:User {name:'Virat', age:27})"); + executeUpdate( + "CREATE (:User {name:'Morne', age:30}), (:User {name:'Abraham', age:31}), (:User {name:'Virat', age:27})"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -261,8 +261,9 @@ public class QueryIntegrationIT extends MultiDriverTestClass { @Test public void shouldRetrieveUsersByGenderAndConvertToCorrectTypes() { - executeUpdate("CREATE (:User {name:'David Warner', gender:'MALE'}), (:User {name:'Shikhar Dhawan', gender:'MALE'}), " - + "(:User {name:'Sarah Taylor', gender:'FEMALE', account: '3456789', deposits:['12345.6','45678.9']})"); + executeUpdate( + "CREATE (:User {name:'David Warner', gender:'MALE'}), (:User {name:'Shikhar Dhawan', gender:'MALE'}), " + + "(:User {name:'Sarah Taylor', gender:'FEMALE', account: '3456789', deposits:['12345.6','45678.9']})"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -276,7 +277,8 @@ public class QueryIntegrationIT extends MultiDriverTestClass { assertEquals(Gender.FEMALE, userQueryResult.getUserGender()); assertEquals("Sarah Taylor", userQueryResult.getUserName()); assertEquals(BigInteger.valueOf(3456789), userQueryResult.getUserAccount()); - assertArrayEquals(new BigDecimal[]{BigDecimal.valueOf(12345.6), BigDecimal.valueOf(45678.9)}, userQueryResult.getUserDeposits()); + assertArrayEquals(new BigDecimal[] { BigDecimal.valueOf(12345.6), BigDecimal.valueOf(45678.9) }, + userQueryResult.getUserDeposits()); assertFalse(userIterator.hasNext()); } }); @@ -369,8 +371,7 @@ public class QueryIntegrationIT extends MultiDriverTestClass { public void doInTransactionWithoutResult(TransactionStatus status) { assertEquals("There should be some users in the database", 2, userRepository.findTotalUsers()); - Iterable expected = Arrays.asList(new UserQueryResult(null, 0), - new UserQueryResult(null, 0)); + Iterable expected = Arrays.asList(new UserQueryResult(null, 0), new UserQueryResult(null, 0)); Iterable queryResult = userRepository.retrieveAllUsersAndTheirAges(); assertNotNull("The query result shouldn't be null", queryResult); @@ -405,7 +406,8 @@ public class QueryIntegrationIT extends MultiDriverTestClass { */ @Test public void shouldMapNodeCollectionsIntoQueryResultObjects() { - executeUpdate("CREATE (d:User {name:'Daniela'}), (e:User {name:'Ethan'}), (f:User {name:'Finn'}), (d)-[:FRIEND_OF]->(e), (d)-[:FRIEND_OF]->(f)"); + executeUpdate( + "CREATE (d:User {name:'Daniela'}), (e:User {name:'Ethan'}), (f:User {name:'Finn'}), (d)-[:FRIEND_OF]->(e), (d)-[:FRIEND_OF]->(f)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -421,7 +423,8 @@ public class QueryIntegrationIT extends MultiDriverTestClass { } assertTrue(friends.contains("Ethan")); assertTrue(friends.contains("Finn")); - assertEquals(2, result.getUser().getFriends().size()); //we expect friends to be mapped since the relationships were returned + assertEquals(2, result.getUser().getFriends().size()); // we expect friends to be mapped since the relationships + // were returned } }); } @@ -431,7 +434,8 @@ public class QueryIntegrationIT extends MultiDriverTestClass { */ @Test public void shouldMapRECollectionsIntoQueryResultObjects() { - executeUpdate("CREATE (g:User {name:'Gary'}), (sw:Movie {name: 'Star Wars: The Force Awakens'}), (hob:Movie {name:'The Hobbit: An Unexpected Journey'}), (g)-[:RATED {stars : 5}]->(sw), (g)-[:RATED {stars: 4}]->(hob) "); + executeUpdate( + "CREATE (g:User {name:'Gary'}), (sw:Movie {name: 'Star Wars: The Force Awakens'}), (hob:Movie {name:'The Hobbit: An Unexpected Journey'}), (g)-[:RATED {stars : 5}]->(sw), (g)-[:RATED {stars: 4}]->(hob) "); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -466,7 +470,8 @@ public class QueryIntegrationIT extends MultiDriverTestClass { */ @Test public void shouldMapRelationshipCollectionsWithDepth0IntoQueryResultObjects() { - executeUpdate("CREATE (i:User {name:'Ingrid'}), (j:User {name:'Jake'}), (k:User {name:'Kate'}), (i)-[:FRIEND_OF]->(j), (i)-[:FRIEND_OF]->(k)"); + executeUpdate( + "CREATE (i:User {name:'Ingrid'}), (j:User {name:'Jake'}), (k:User {name:'Kate'}), (i)-[:FRIEND_OF]->(j), (i)-[:FRIEND_OF]->(k)"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -482,7 +487,8 @@ public class QueryIntegrationIT extends MultiDriverTestClass { } assertTrue(friends.contains("Kate")); assertTrue(friends.contains("Jake")); - assertEquals(0, result.getUser().getFriends().size()); //we do not expect friends to be mapped since the relationships were not returned + assertEquals(0, result.getUser().getFriends().size()); // we do not expect friends to be mapped since the + // relationships were not returned } }); } @@ -492,7 +498,8 @@ public class QueryIntegrationIT extends MultiDriverTestClass { */ @Test public void shouldReturnMultipleQueryResultObjects() { - executeUpdate("CREATE (g:User {name:'Gary'}), (h:User {name:'Harry'}), (sw:Movie {name: 'Star Wars: The Force Awakens'}), (hob:Movie {name:'The Hobbit: An Unexpected Journey'}), (g)-[:RATED {stars : 5}]->(sw), (g)-[:RATED {stars: 4}]->(hob), (h)-[:RATED {stars: 3}]->(hob) "); + executeUpdate( + "CREATE (g:User {name:'Gary'}), (h:User {name:'Harry'}), (sw:Movie {name: 'Star Wars: The Force Awakens'}), (hob:Movie {name:'The Hobbit: An Unexpected Journey'}), (g)-[:RATED {stars : 5}]->(sw), (g)-[:RATED {stars: 4}]->(hob), (h)-[:RATED {stars: 3}]->(hob) "); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override @@ -541,7 +548,8 @@ public class QueryIntegrationIT extends MultiDriverTestClass { */ @Test public void shouldMapEntitiesToProxiedQueryResultInterface() { - executeUpdate("CREATE (:User {name:'Morne', age:30}), (:User {name:'Abraham', age:31}), (:User {name:'Virat', age:27})"); + executeUpdate( + "CREATE (:User {name:'Morne', age:30}), (:User {name:'Abraham', age:31}), (:User {name:'Virat', age:27})"); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/QueryReturnTypesIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/QueryReturnTypesIT.java index 9519b21ca..c94fffbd2 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/QueryReturnTypesIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/queries/QueryReturnTypesIT.java @@ -33,16 +33,14 @@ import org.springframework.transaction.annotation.Transactional; * @author Luanne Misquitta * @author Mark Angrish */ -@ContextConfiguration(classes = {GalaxyContext.class}) +@ContextConfiguration(classes = { GalaxyContext.class }) @RunWith(SpringJUnit4ClassRunner.class) @Transactional public class QueryReturnTypesIT extends MultiDriverTestClass { - @Autowired - WorldRepository worldRepository; + @Autowired WorldRepository worldRepository; - @Autowired - Session session; + @Autowired Session session; @Test public void shouldCallExecuteWhenPrimitiveVoidReturnTypeOnQuery() { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/ProgrammaticRepositoryIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/ProgrammaticRepositoryIT.java index 8722be21f..40101eb25 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/ProgrammaticRepositoryIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/ProgrammaticRepositoryIT.java @@ -48,160 +48,159 @@ import org.springframework.transaction.support.TransactionTemplate; */ public class ProgrammaticRepositoryIT extends MultiDriverTestClass { - private static GraphDatabaseService graphDatabaseService; + private static GraphDatabaseService graphDatabaseService; - private MovieRepository movieRepository; - private SessionFactory sessionFactory = new SessionFactory("org.springframework.data.neo4j.repositories.domain"); - private PlatformTransactionManager platformTransactionManager = new Neo4jTransactionManager(sessionFactory); - private Session session; - private TransactionTemplate transactionTemplate; + private MovieRepository movieRepository; + private SessionFactory sessionFactory = new SessionFactory("org.springframework.data.neo4j.repositories.domain"); + private PlatformTransactionManager platformTransactionManager = new Neo4jTransactionManager(sessionFactory); + private Session session; + private TransactionTemplate transactionTemplate; - @BeforeClass - public static void beforeClass(){ - graphDatabaseService = getGraphDatabaseService(); - } + @BeforeClass + public static void beforeClass() { + graphDatabaseService = getGraphDatabaseService(); + } - @Before - public void init() { - transactionTemplate = new TransactionTemplate(platformTransactionManager); - session = sessionFactory.openSession(); - session.purgeDatabase(); - } + @Before + public void init() { + transactionTemplate = new TransactionTemplate(platformTransactionManager); + session = sessionFactory.openSession(); + session.purgeDatabase(); + } - @Test - public void canInstantiateRepositoryProgrammatically() { + @Test + public void canInstantiateRepositoryProgrammatically() { - transactionTemplate.execute(new TransactionCallbackWithoutResult() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); + transactionTemplate.execute(new TransactionCallbackWithoutResult() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); - movieRepository = factory.getRepository(MovieRepository.class); + movieRepository = factory.getRepository(MovieRepository.class); - Movie movie = new Movie("PF"); - movieRepository.save(movie); - } - }); + Movie movie = new Movie("PF"); + movieRepository.save(movie); + } + }); - assertSameGraph(graphDatabaseService, "CREATE (m:Movie {title:'PF'})"); + assertSameGraph(graphDatabaseService, "CREATE (m:Movie {title:'PF'})"); - assertEquals(1, IterableUtils.count(movieRepository.findAll())); - } + assertEquals(1, IterableUtils.count(movieRepository.findAll())); + } /** - * @see DATAGRAPH-847 - */ - @Test - @Transactional - public void shouldBeAbleToDeleteAllViaRepository() { + * @see DATAGRAPH-847 + */ + @Test + @Transactional + public void shouldBeAbleToDeleteAllViaRepository() { - RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); + RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); - UserRepository userRepository = factory.getRepository(UserRepository.class); + UserRepository userRepository = factory.getRepository(UserRepository.class); - User userA = new User("A"); - User userB = new User("B"); - userRepository.save(userA); - userRepository.save(userB); + User userA = new User("A"); + User userB = new User("B"); + userRepository.save(userA); + userRepository.save(userB); - assertEquals(2, userRepository.count()); + assertEquals(2, userRepository.count()); - userRepository.deleteAll(); - assertEquals(0, userRepository.count()); - } + userRepository.deleteAll(); + assertEquals(0, userRepository.count()); + } - /** - * @see DATAGRAPH-813 - */ - @Test - @Transactional - public void shouldDeleteUserByNameAndReturnCountOfDeletedUsers() { + /** + * @see DATAGRAPH-813 + */ + @Test + @Transactional + public void shouldDeleteUserByNameAndReturnCountOfDeletedUsers() { - RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); + RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); - UserRepository userRepository = factory.getRepository(UserRepository.class); + UserRepository userRepository = factory.getRepository(UserRepository.class); - User userA = new User("A"); - userA.setName("A"); + User userA = new User("A"); + userA.setName("A"); - userRepository.save(userA); - Assert.assertEquals(1, userRepository.count()); + userRepository.save(userA); + Assert.assertEquals(1, userRepository.count()); - Assert.assertEquals(new Long(1), userRepository.deleteByName("A")); - Assert.assertEquals(0, userRepository.count()); + Assert.assertEquals(new Long(1), userRepository.deleteByName("A")); + Assert.assertEquals(0, userRepository.count()); - } + } - /** - * @see DATAGRAPH-813 - */ - @Test - @Transactional - public void shouldDeleteUserByNameAndReturnListOfDeletedUserIds() { + /** + * @see DATAGRAPH-813 + */ + @Test + @Transactional + public void shouldDeleteUserByNameAndReturnListOfDeletedUserIds() { - RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); + RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); - UserRepository userRepository = factory.getRepository(UserRepository.class); + UserRepository userRepository = factory.getRepository(UserRepository.class); - User userA = new User("A"); - User userAClone = new User("A"); + User userA = new User("A"); + User userAClone = new User("A"); + userRepository.save(userA); + userRepository.save(userAClone); - userRepository.save(userA); - userRepository.save(userAClone); + Assert.assertEquals(2, userRepository.count()); - Assert.assertEquals(2, userRepository.count()); + List deletedUserIds = userRepository.removeByName("A"); + Assert.assertEquals(2, deletedUserIds.size()); - List deletedUserIds = userRepository.removeByName("A"); - Assert.assertEquals(2, deletedUserIds.size()); + Assert.assertEquals(userA.getId(), deletedUserIds.get(0)); + Assert.assertEquals(userAClone.getId(), deletedUserIds.get(1)); - Assert.assertEquals(userA.getId(), deletedUserIds.get(0)); - Assert.assertEquals(userAClone.getId(), deletedUserIds.get(1)); + Assert.assertEquals(0, userRepository.count()); - Assert.assertEquals(0, userRepository.count()); + } - } + @Test + @Transactional + public void shouldBeAbleToDeleteUserWithRelationships() { - @Test - @Transactional - public void shouldBeAbleToDeleteUserWithRelationships() { + RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); - RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); + UserRepository userRepository = factory.getRepository(UserRepository.class); - UserRepository userRepository = factory.getRepository(UserRepository.class); + User userA = new User("A"); + User userB = new User("B"); - User userA = new User("A"); - User userB = new User("B"); + userA.getFriends().add(userB); + userB.getFriends().add(userA); - userA.getFriends().add(userB); - userB.getFriends().add(userA); + userRepository.save(userA); - userRepository.save(userA); + Assert.assertEquals(2, userRepository.count()); - Assert.assertEquals(2, userRepository.count()); + userRepository.deleteByName("A"); - userRepository.deleteByName("A"); + Assert.assertEquals(1, userRepository.count()); - Assert.assertEquals(1, userRepository.count()); + } - } + /** + * @see DATAGRAPH-813 + */ + @Test + @Transactional + public void shouldCountUserByName() { - /** - * @see DATAGRAPH-813 - */ - @Test - @Transactional - public void shouldCountUserByName() { + RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); - RepositoryFactorySupport factory = new Neo4jRepositoryFactory(session); + UserRepository userRepository = factory.getRepository(UserRepository.class); - UserRepository userRepository = factory.getRepository(UserRepository.class); + User userA = new User("A"); + userA.setName("A"); - User userA = new User("A"); - userA.setName("A"); + userRepository.save(userA); - userRepository.save(userA); - - Assert.assertEquals(new Long(1), userRepository.countByName("A")); - } + Assert.assertEquals(new Long(1), userRepository.countByName("A")); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/RepoScanningIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/RepoScanningIT.java index 258d79ccb..7a8fbb185 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/RepoScanningIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/RepoScanningIT.java @@ -13,7 +13,6 @@ package org.springframework.data.neo4j.repositories; -import static org.junit.Assert.assertEquals; import static org.neo4j.ogm.testutil.GraphTestUtils.*; import org.junit.Before; @@ -21,7 +20,6 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.neo4j.graphdb.GraphDatabaseService; -import org.neo4j.ogm.session.Session; import org.neo4j.ogm.testutil.MultiDriverTestClass; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.neo4j.repositories.domain.User; @@ -29,28 +27,21 @@ import org.springframework.data.neo4j.repositories.repo.PersistenceContextInTheS import org.springframework.data.neo4j.repositories.repo.UserRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.TransactionCallbackWithoutResult; -import org.springframework.transaction.support.TransactionTemplate; /** * @author Michal Bachman * @author Mark Angrish */ -@ContextConfiguration(classes = {PersistenceContextInTheSamePackage.class}) +@ContextConfiguration(classes = { PersistenceContextInTheSamePackage.class }) @RunWith(SpringJUnit4ClassRunner.class) public class RepoScanningIT extends MultiDriverTestClass { private static GraphDatabaseService graphDatabaseService; - @Autowired - private UserRepository userRepository; - + @Autowired private UserRepository userRepository; @BeforeClass - public static void beforeClass(){ + public static void beforeClass() { graphDatabaseService = getGraphDatabaseService(); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/RepositoryDefinitionIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/RepositoryDefinitionIT.java index 12ba7b78b..c4436d24b 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/RepositoryDefinitionIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/RepositoryDefinitionIT.java @@ -38,14 +38,13 @@ import org.springframework.transaction.support.TransactionTemplate; * @author Michal Bachman * @author Mark Angrish */ -@ContextConfiguration(classes = {RepositoriesTestContext.class}) +@ContextConfiguration(classes = { RepositoriesTestContext.class }) @RunWith(SpringJUnit4ClassRunner.class) public class RepositoryDefinitionIT extends MultiDriverTestClass { private static GraphDatabaseService graphDatabaseService; - @Autowired - PlatformTransactionManager platformTransactionManager; + @Autowired PlatformTransactionManager platformTransactionManager; private TransactionTemplate transactionTemplate; @@ -54,8 +53,7 @@ public class RepositoryDefinitionIT extends MultiDriverTestClass { graphDatabaseService = getGraphDatabaseService(); } - @Autowired - private MovieRepository movieRepository; + @Autowired private MovieRepository movieRepository; @Before public void clearDatabase() { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/domain/Movie.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/domain/Movie.java index efa3628ac..34a1bed3d 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/domain/Movie.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/domain/Movie.java @@ -13,23 +13,21 @@ package org.springframework.data.neo4j.repositories.domain; - /** * @author Michal Bachman */ public class Movie { - private Long id; - private String title; + private Long id; + private String title; - public Movie() { - } + public Movie() {} - public Movie(String title) { - this.title = title; - } + public Movie(String title) { + this.title = title; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/domain/User.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/domain/User.java index fa40a0e96..8a0a22eb8 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/domain/User.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/domain/User.java @@ -22,37 +22,35 @@ import java.util.List; */ public class User { - private Long id; - private String name; + private Long id; + private String name; - private List friends = new ArrayList<>(); - public User() { - } + private List friends = new ArrayList<>(); - public Long getId() { - return this.id; - } + public User() {} - public User(String name) { - this.name = name; - } + public Long getId() { + return this.id; + } - public String getName() { - return name; - } + public User(String name) { + this.name = name; + } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public List getFriends() { - return friends; - } - - public void setFriends(List friends) { - this.friends = friends; - } + public void setName(String name) { + this.name = name; + } + public List getFriends() { + return friends; + } + public void setFriends(List friends) { + this.friends = friends; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/MovieRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/MovieRepository.java index c819267e4..6d65ed3ca 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/MovieRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/MovieRepository.java @@ -22,7 +22,7 @@ import org.springframework.data.repository.RepositoryDefinition; @RepositoryDefinition(domainClass = Movie.class, idClass = Long.class) public interface MovieRepository { - S save(S entity); + S save(S entity); - Iterable findAll(); + Iterable findAll(); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/PersistenceContextInTheSamePackage.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/PersistenceContextInTheSamePackage.java index d549a986a..7921184ff 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/PersistenceContextInTheSamePackage.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/PersistenceContextInTheSamePackage.java @@ -26,7 +26,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; * @author Mark Angrish */ @Configuration -@EnableNeo4jRepositories //no package specified, that's the point of this test +@EnableNeo4jRepositories // no package specified, that's the point of this test @EnableTransactionManagement public class PersistenceContextInTheSamePackage { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/UserRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/UserRepository.java index 22e7840fc..17bf1deb4 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/UserRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repositories/repo/UserRepository.java @@ -17,7 +17,6 @@ import java.util.List; import org.springframework.data.neo4j.repositories.domain.User; import org.springframework.data.neo4j.repository.GraphRepository; -import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.stereotype.Repository; /** diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/Neo4jRepositoryIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/Neo4jRepositoryIT.java index d7f724fd1..2b352e878 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/Neo4jRepositoryIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/Neo4jRepositoryIT.java @@ -67,7 +67,6 @@ public class Neo4jRepositoryIT extends MultiDriverTestClass { assertThat(repository.count(), is(0L)); } - private interface SampleEntityRepository extends Neo4jRepository { } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/CdiExtensionIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/CdiExtensionIT.java index c18311d0d..d34e53c35 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/CdiExtensionIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/CdiExtensionIT.java @@ -38,25 +38,25 @@ public class CdiExtensionIT extends MultiDriverTestClass { static CdiTestContainer container; - @BeforeClass - public static void setUp() throws Exception { + @BeforeClass + public static void setUp() throws Exception { - // Prevent the Jersey extension to interact with the InitialContext - System.setProperty("com.sun.jersey.server.impl.cdi.lookupExtensionInBeanManager", "true"); + // Prevent the Jersey extension to interact with the InitialContext + System.setProperty("com.sun.jersey.server.impl.cdi.lookupExtensionInBeanManager", "true"); - setupMultiDriverTestEnvironment(); + setupMultiDriverTestEnvironment(); - container = CdiTestContainerLoader.getCdiContainer(); - container.bootContainer(); - } + container = CdiTestContainerLoader.getCdiContainer(); + container.bootContainer(); + } - @AfterClass - public static void tearDown() throws Exception { + @AfterClass + public static void tearDown() throws Exception { - container.shutdownContainer(); + container.shutdownContainer(); - tearDownMultiDriverTestEnvironment(); - } + tearDownMultiDriverTestEnvironment(); + } /** * @see DATAGRAPH-879 diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/CdiPersonRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/CdiPersonRepository.java index a79d21f8f..b85275b74 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/CdiPersonRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/CdiPersonRepository.java @@ -25,9 +25,9 @@ import org.springframework.data.repository.Repository; */ public interface CdiPersonRepository extends Repository { - void deleteAll(); + void deleteAll(); - Person save(Person person); + Person save(Person person); - Person findOne(Long id); + Person findOne(Long id); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiProducer.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiProducer.java index 8b0560896..6e970cef9 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiProducer.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/Neo4jCdiProducer.java @@ -16,13 +16,13 @@ package org.springframework.data.neo4j.repository.cdi; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Produces; + import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; import org.springframework.data.neo4j.examples.friends.domain.Person; -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.inject.Produces; - /** * Simple component exposing a {@link org.neo4j.ogm.session.Session} as CDI bean. * @@ -31,19 +31,19 @@ import javax.enterprise.inject.Produces; */ class Neo4jCdiProducer { - @Produces - @ApplicationScoped - Session createSession() { + @Produces + @ApplicationScoped + Session createSession() { - SessionFactory sessionFactory = new SessionFactory(Person.class.getPackage().getName()); - return sessionFactory.openSession(); - } + SessionFactory sessionFactory = new SessionFactory(Person.class.getPackage().getName()); + return sessionFactory.openSession(); + } - @Produces - @ApplicationScoped - @PersonDB - @OtherQualifier - Session createQualifiedSession() { - return createSession(); - } + @Produces + @ApplicationScoped + @PersonDB + @OtherQualifier + Session createQualifiedSession() { + return createSession(); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/Neo4jRepositoryExtensionTest.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/Neo4jRepositoryExtensionTest.java index 88206c1f9..a5f2fe0ed 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/Neo4jRepositoryExtensionTest.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/Neo4jRepositoryExtensionTest.java @@ -16,14 +16,15 @@ import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; -import javax.enterprise.inject.spi.Bean; -import javax.enterprise.inject.spi.ProcessBean; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map; import java.util.Set; +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.ProcessBean; + import org.junit.Before; import org.junit.Test; import org.neo4j.ogm.session.Session; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/OtherQualifier.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/OtherQualifier.java index 0b121dda6..c95e0f6f7 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/OtherQualifier.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/OtherQualifier.java @@ -16,19 +16,20 @@ package org.springframework.data.neo4j.repository.cdi; -import javax.inject.Qualifier; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.inject.Qualifier; + /** * @author Mark Paluch * @see DATAGRAPH-879 */ @Qualifier @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) +@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @interface OtherQualifier { } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/PersonDB.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/PersonDB.java index c50c7e973..5d9ff4ee4 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/PersonDB.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/PersonDB.java @@ -15,19 +15,20 @@ */ package org.springframework.data.neo4j.repository.cdi; -import javax.inject.Qualifier; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.inject.Qualifier; + /** * @author Mark Paluch * @see DATAGRAPH-879 */ @Qualifier @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) +@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @interface PersonDB { } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/RepositoryClient.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/RepositoryClient.java index 7c8bc0097..ce33b15b7 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/RepositoryClient.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/RepositoryClient.java @@ -24,14 +24,9 @@ import javax.inject.Inject; */ class RepositoryClient { - @Inject - CdiPersonRepository repository; + @Inject CdiPersonRepository repository; - @OtherQualifier - @PersonDB - @Inject - QualifiedPersonRepository qualifiedPersonRepository; + @OtherQualifier @PersonDB @Inject QualifiedPersonRepository qualifiedPersonRepository; - @Inject - SamplePersonRepository samplePersonRepository; + @Inject SamplePersonRepository samplePersonRepository; } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/SamplePersonRepositoryCustom.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/SamplePersonRepositoryCustom.java index 81e797ce9..d1596976f 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/SamplePersonRepositoryCustom.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/SamplePersonRepositoryCustom.java @@ -22,5 +22,5 @@ package org.springframework.data.neo4j.repository.cdi; */ interface SamplePersonRepositoryCustom { - int returnOne(); + int returnOne(); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/SamplePersonRepositoryImpl.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/SamplePersonRepositoryImpl.java index 1b712be5e..39a57c539 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/SamplePersonRepositoryImpl.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/cdi/SamplePersonRepositoryImpl.java @@ -22,8 +22,8 @@ package org.springframework.data.neo4j.repository.cdi; */ class SamplePersonRepositoryImpl implements SamplePersonRepositoryCustom { - @Override - public int returnOne() { - return 1; - } + @Override + public int returnOne() { + return 1; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/config/RepositoriesJavaConfigTests.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/config/RepositoriesJavaConfigTests.java index d2db06dce..7e96b3408 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/config/RepositoriesJavaConfigTests.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/config/RepositoriesJavaConfigTests.java @@ -43,8 +43,7 @@ public class RepositoriesJavaConfigTests { @EnableNeo4jRepositories(basePackageClasses = UserRepository.class) static class Config { - @Autowired - ApplicationContext context; + @Autowired ApplicationContext context; @Bean public Repositories repositories() { @@ -62,8 +61,7 @@ public class RepositoriesJavaConfigTests { } } - @Autowired - Repositories repositories; + @Autowired Repositories repositories; /** */ diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/sample/UserRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/sample/UserRepository.java index ae6391000..03a13b1f6 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/sample/UserRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/sample/UserRepository.java @@ -17,11 +17,9 @@ import java.util.List; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.neo4j.domain.sample.User; import org.springframework.data.neo4j.repository.GraphRepository; -import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.data.repository.CrudRepository; import org.springframework.transaction.annotation.Transactional; - /** * Repository interface for {@code User}s. * diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/DefaultTransactionDisablingIntegrationIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/DefaultTransactionDisablingIntegrationIT.java index 4c3512a69..03f922806 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/DefaultTransactionDisablingIntegrationIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/DefaultTransactionDisablingIntegrationIT.java @@ -75,7 +75,7 @@ public class DefaultTransactionDisablingIntegrationIT extends MultiDriverTestCla public void persistingAnEntityShouldThrowExceptionDueToMissingTransaction() { exception.expect(InvalidDataAccessApiUsageException.class); - exception.expectCause(is(Matchers.instanceOf(IllegalStateException.class))); + exception.expectCause(is(Matchers. instanceOf(IllegalStateException.class))); repository.save(new User()); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactoryBeanTests.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactoryBeanTests.java index 34d5ae3b7..417fb7006 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactoryBeanTests.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/Neo4jRepositoryFactoryBeanTests.java @@ -45,18 +45,12 @@ public class Neo4jRepositoryFactoryBeanTests { Neo4jRepositoryFactoryBean factoryBean; - @Mock - Session session; - @Mock - RepositoryFactorySupport factory; - @Mock - ListableBeanFactory beanFactory; - @Mock - PersistenceExceptionTranslator translator; - @Mock - Repository repository; - @Mock - MetaData metaData; + @Mock Session session; + @Mock RepositoryFactorySupport factory; + @Mock ListableBeanFactory beanFactory; + @Mock PersistenceExceptionTranslator translator; + @Mock Repository repository; + @Mock MetaData metaData; @Before @SuppressWarnings("unchecked") @@ -64,8 +58,8 @@ public class Neo4jRepositoryFactoryBeanTests { Map beans = new HashMap<>(); beans.put("foo", translator); - when(beanFactory.getBeansOfType(eq(PersistenceExceptionTranslator.class), anyBoolean(), anyBoolean())).thenReturn( - beans); + when(beanFactory.getBeansOfType(eq(PersistenceExceptionTranslator.class), anyBoolean(), anyBoolean())) + .thenReturn(beans); when(factory.getRepository(any(Class.class), any(Object.class))).thenReturn(repository); // Setup standard factory configuration @@ -103,8 +97,8 @@ public class Neo4jRepositoryFactoryBeanTests { factoryBean = new DummyNeo4jRepositoryFactoryBean(null); } - private class DummyNeo4jRepositoryFactoryBean, S, ID extends Serializable> extends - Neo4jRepositoryFactoryBean { + private class DummyNeo4jRepositoryFactoryBean, S, ID extends Serializable> + extends Neo4jRepositoryFactoryBean { /** * @param repositoryInterface diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/TransactionalRepositoryIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/TransactionalRepositoryIT.java index 9cd91cfe0..60a001ea7 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/TransactionalRepositoryIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/support/TransactionalRepositoryIT.java @@ -39,7 +39,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; /** * @author Mark Angrish */ -@ContextConfiguration(classes = {TransactionalRepositoryIT.Config.class}) +@ContextConfiguration(classes = { TransactionalRepositoryIT.Config.class }) @RunWith(SpringJUnit4ClassRunner.class) public class TransactionalRepositoryIT extends MultiDriverTestClass { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/ExceptionTranslationIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/ExceptionTranslationIT.java index 51840fa5f..cd31b2ed8 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/ExceptionTranslationIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/ExceptionTranslationIT.java @@ -33,8 +33,7 @@ import org.springframework.util.Assert; @RunWith(SpringJUnit4ClassRunner.class) public class ExceptionTranslationIT extends MultiDriverTestClass { - @Autowired - private Neo4jOperations neo4jTemplate; + @Autowired private Neo4jOperations neo4jTemplate; @Before public void setUp() { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/Neo4jTemplateIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/Neo4jTemplateIT.java index 9a2571c75..501df6511 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/Neo4jTemplateIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/Neo4jTemplateIT.java @@ -13,13 +13,25 @@ package org.springframework.data.neo4j.template; +import static org.junit.Assert.*; +import static org.neo4j.ogm.session.Utils.*; + +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.Map; + import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; -import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; -import org.neo4j.graphdb.*; +import org.neo4j.graphdb.DynamicLabel; +import org.neo4j.graphdb.DynamicRelationshipType; +import org.neo4j.graphdb.GraphDatabaseService; +import org.neo4j.graphdb.Label; +import org.neo4j.graphdb.Node; +import org.neo4j.graphdb.Transaction; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.cypher.BooleanOperator; import org.neo4j.ogm.cypher.ComparisonOperator; @@ -31,491 +43,501 @@ import org.neo4j.ogm.session.Utils; import org.neo4j.ogm.testutil.MultiDriverTestClass; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.InvalidDataAccessApiUsageException; -import org.springframework.data.neo4j.examples.movies.domain.*; +import org.springframework.data.neo4j.examples.movies.domain.Actor; +import org.springframework.data.neo4j.examples.movies.domain.Cinema; +import org.springframework.data.neo4j.examples.movies.domain.Genre; +import org.springframework.data.neo4j.examples.movies.domain.Movie; +import org.springframework.data.neo4j.examples.movies.domain.Rating; +import org.springframework.data.neo4j.examples.movies.domain.TempMovie; +import org.springframework.data.neo4j.examples.movies.domain.User; import org.springframework.data.neo4j.template.context.Neo4jTemplateConfiguration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.Map; - -import static org.junit.Assert.*; -import static org.neo4j.ogm.session.Utils.map; - /** * @author Adam George * @author Luanne Misquitta * @author Vince Bickers */ -@ContextConfiguration(classes = {Neo4jTemplateConfiguration.class}) +@ContextConfiguration(classes = { Neo4jTemplateConfiguration.class }) @RunWith(SpringJUnit4ClassRunner.class) public class Neo4jTemplateIT extends MultiDriverTestClass { - private static GraphDatabaseService graphDatabaseService; + private static GraphDatabaseService graphDatabaseService; - @Autowired private Neo4jOperations template; + @Autowired private Neo4jOperations template; - @BeforeClass - public static void beforeClass(){ - graphDatabaseService = getGraphDatabaseService(); - } + @BeforeClass + public static void beforeClass() { + graphDatabaseService = getGraphDatabaseService(); + } - @Before - public void setUpOgmSession() { - clearDatabase(); - addArbitraryDataToDatabase(); - } + @Before + public void setUpOgmSession() { + clearDatabase(); + addArbitraryDataToDatabase(); + } - public void clearDatabase() { - try (Transaction tx = graphDatabaseService.beginTx()) { - graphDatabaseService.execute("MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE r, n"); - tx.success(); - } - } - - /** - * While this may seem trivial, some of these tests actually used to fail when run against a database containing unrelated data. - */ - private void addArbitraryDataToDatabase() { - - try (Transaction tx = graphDatabaseService.beginTx()) { - Node arbitraryNode = graphDatabaseService.createNode(DynamicLabel.label("NotAClass")); - arbitraryNode.setProperty("name", "Colin"); - Node otherNode = graphDatabaseService.createNode(DynamicLabel.label("NotAClass")); - otherNode.setProperty("age", 39); - arbitraryNode.createRelationshipTo(otherNode, DynamicRelationshipType.withName("TEST")); - - tx.success(); - } - } - - @Test - @Transactional - public void shouldSaveAndRetrieveNodeEntitiesWithoutExplicitTransactionManagement() { - Genre filmGenre = new Genre(); - filmGenre.setName("Comedy"); - this.template.save(filmGenre); - - Genre loadedGenre = this.template.load(Genre.class, filmGenre.getId()); - assertNotNull("The entity loaded from the template shouldn't be null", loadedGenre); - assertEquals("The loaded entity wasn't as expected", filmGenre, loadedGenre); - - Genre anotherGenre = new Genre(); - anotherGenre.setName("Action"); - this.template.save(anotherGenre); - - Collection allGenres = this.template.loadAll(Genre.class); - assertNotNull("The collection of all genres shouldn't be null", allGenres); - assertEquals("The number of genres in the database wasn't as expected", 2, allGenres.size()); - } - - @Test - @Transactional - public void shouldSaveAndRetrieveRelationshipEntitiesWithoutExplicitTransactionManagement() { - User critic = new User("Gary"); - TempMovie film = new TempMovie("Fast and Furious XVII"); - Rating filmRating = critic.rate(film, 2, "They've made far too many of these films now!"); - - this.template.save(filmRating); - - Rating loadedRating = this.template.load(Rating.class, filmRating.getId()); - assertNotNull("The loaded rating shouldn't be null", loadedRating); - assertEquals("The relationship properties weren't saved correctly", filmRating.getStars(), loadedRating.getStars()); - assertEquals("The rated film wasn't saved correctly", film.getName(), loadedRating.getMovie().getName()); - assertEquals("The critic wasn't saved correctly", critic.getId(), loadedRating.getUser().getId()); - } - - @Test - @Transactional - public void shouldExecuteArbitraryReadQuery() { - User user = new User("Harmanpreet Singh"); - TempMovie bollywood = new TempMovie("Desi Boyz"); - TempMovie hollywood = new TempMovie("Mission Impossible"); - template.save(user.rate(bollywood, 1, "Bakwaas")); - template.save(user.rate(hollywood, 4, "Pretty good")); - - Result queryResults = - this.template.query("MATCH (u:User)-[r]->(m:Movie) RETURN AVG(r.stars) AS avg", Collections.EMPTY_MAP); - Iterator> queryResultIterator = queryResults.iterator(); - assertTrue("There should've been some query result returned", queryResultIterator.hasNext()); - assertEquals(2.5, (Double) queryResultIterator.next().get("avg"), 0.01); - } - - @Test - @Transactional - public void shouldQueryForSpecificObjectUsingBespokeParameterisedCypherQuery() { - this.template.save(new Actor("ab", "Alec Baldwin")); - this.template.save(new Actor("hm", "Helen Mirren")); - this.template.save(new Actor("md", "Matt Damon")); - - Actor loadedActor = this.template.queryForObject(Actor.class, "MATCH (a:Actor) WHERE a.name={param} RETURN a", - Collections.singletonMap("param", "Alec Baldwin")); - assertNotNull("The entity wasn't loaded", loadedActor); - assertEquals("Alec Baldwin", loadedActor.getName()); - } - - @Test - @Transactional - public void shouldQueryForObjectCollectionUsingBespokeCypherQuery() { - this.template.save(new User("Jeff")); - this.template.save(new User("John")); - this.template.save(new User("Colin")); - - Iterable users = this.template.queryForObjects(User.class, "MATCH (u:User) WHERE u.name=~'J.*' RETURN u", - Collections.emptyMap()); - assertNotNull("The entity wasn't loaded", users); - assertTrue("The entity wasn't loaded", users.iterator().hasNext()); - for (User loadedUser : users) { - assertTrue("Shouldn't've loaded " + loadedUser.getName(), - loadedUser.getName().equals("John") || loadedUser.getName().equals("Jeff")); - } - } - - @Test - @Transactional - public void shouldRetrieveEntitiesByMatchingProperty() { - this.template.save(new Genre("Thriller")); - this.template.save(new Genre("Horror")); - this.template.save(new Genre("Period Drama")); - - Genre loadedGenre = this.template.loadByProperty(Genre.class, "name", "Horror"); - assertNotNull("No genre was loaded", loadedGenre); - assertEquals("Horror", loadedGenre.getName()); - } + public void clearDatabase() { + try (Transaction tx = graphDatabaseService.beginTx()) { + graphDatabaseService.execute("MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE r, n"); + tx.success(); + } + } /** - * @see DATAGRAPH-685 - */ - @Test - @Transactional - public void shouldRetrieveEntitiesByMatchingPropertyAndDepth() { - User user = new User("Harmanpreet Singh"); - TempMovie bollywood = new TempMovie("Desi Boyz"); - TempMovie hollywood = new TempMovie("Mission Impossible"); + * While this may seem trivial, some of these tests actually used to fail when run against a database containing + * unrelated data. + */ + private void addArbitraryDataToDatabase() { + try (Transaction tx = graphDatabaseService.beginTx()) { + Node arbitraryNode = graphDatabaseService.createNode(DynamicLabel.label("NotAClass")); + arbitraryNode.setProperty("name", "Colin"); + Node otherNode = graphDatabaseService.createNode(DynamicLabel.label("NotAClass")); + otherNode.setProperty("age", 39); + arbitraryNode.createRelationshipTo(otherNode, DynamicRelationshipType.withName("TEST")); - template.save(user.rate(bollywood, 1, "Bakwaas")); - template.save(user.rate(hollywood, 4, "Pretty good")); + tx.success(); + } + } - template.clear(); + @Test + @Transactional + public void shouldSaveAndRetrieveNodeEntitiesWithoutExplicitTransactionManagement() { + Genre filmGenre = new Genre(); + filmGenre.setName("Comedy"); + this.template.save(filmGenre); - User u = template.loadByProperty(User.class, "name", "Harmanpreet Singh",0); - assertEquals(0,u.getRatings().size()); + Genre loadedGenre = this.template.load(Genre.class, filmGenre.getId()); + assertNotNull("The entity loaded from the template shouldn't be null", loadedGenre); + assertEquals("The loaded entity wasn't as expected", filmGenre, loadedGenre); - u = template.loadByProperty(User.class, "name", "Harmanpreet Singh",2); - assertEquals(2,u.getRatings().size()); - assertNotNull(u.getRatings().iterator().next().getMovie().getRatings()); - } + Genre anotherGenre = new Genre(); + anotherGenre.setName("Action"); + this.template.save(anotherGenre); - /** - * @see DATAGRAPH-685 - */ - @Test - public void shouldRetrieveAllEntitiesByMatchingPropertyAndDepth() { - saveUsers(); + Collection allGenres = this.template.loadAll(Genre.class); + assertNotNull("The collection of all genres shouldn't be null", allGenres); + assertEquals("The number of genres in the database wasn't as expected", 2, allGenres.size()); + } - Collection m = template.loadAllByProperty(TempMovie.class, "name", "Desi Boyz",0); - assertEquals(2,m.size()); - assertEquals(0, m.iterator().next().getRatings().size()); + @Test + @Transactional + public void shouldSaveAndRetrieveRelationshipEntitiesWithoutExplicitTransactionManagement() { + User critic = new User("Gary"); + TempMovie film = new TempMovie("Fast and Furious XVII"); + Rating filmRating = critic.rate(film, 2, "They've made far too many of these films now!"); - m = template.loadAllByProperty(TempMovie.class, "name", "Desi Boyz",1); - assertEquals(2,m.size()); - assertEquals(1, m.iterator().next().getRatings().size()); - } + this.template.save(filmRating); - @Transactional - public void saveUsers() { - User user = new User("Harmanpreet Singh"); - TempMovie bollywood = new TempMovie("Desi Boyz"); - TempMovie hollywood = new TempMovie("Desi Boyz"); - template.save(user.rate(bollywood, 1, "Bakwaas")); - template.save(user.rate(hollywood, 4, "Pretty good")); - } + Rating loadedRating = this.template.load(Rating.class, filmRating.getId()); + assertNotNull("The loaded rating shouldn't be null", loadedRating); + assertEquals("The relationship properties weren't saved correctly", filmRating.getStars(), loadedRating.getStars()); + assertEquals("The rated film wasn't saved correctly", film.getName(), loadedRating.getMovie().getName()); + assertEquals("The critic wasn't saved correctly", critic.getId(), loadedRating.getUser().getId()); + } + @Test + @Transactional + public void shouldExecuteArbitraryReadQuery() { + User user = new User("Harmanpreet Singh"); + TempMovie bollywood = new TempMovie("Desi Boyz"); + TempMovie hollywood = new TempMovie("Mission Impossible"); + template.save(user.rate(bollywood, 1, "Bakwaas")); + template.save(user.rate(hollywood, 4, "Pretty good")); - /** - * @see DATAGRAPH-685 - */ - @Test - public void shouldRetrieveEntitiesByMatchingPropertiesAndDepth() { - saveUsers2(); + Result queryResults = this.template.query("MATCH (u:User)-[r]->(m:Movie) RETURN AVG(r.stars) AS avg", + Collections.EMPTY_MAP); + Iterator> queryResultIterator = queryResults.iterator(); + assertTrue("There should've been some query result returned", queryResultIterator.hasNext()); + assertEquals(2.5, (Double) queryResultIterator.next().get("avg"), 0.01); + } + @Test + @Transactional + public void shouldQueryForSpecificObjectUsingBespokeParameterisedCypherQuery() { + this.template.save(new Actor("ab", "Alec Baldwin")); + this.template.save(new Actor("hm", "Helen Mirren")); + this.template.save(new Actor("md", "Matt Damon")); - Filter nameFilter = new Filter("name","Harmanpreet Singh"); - Filter middleNameFilter = new Filter("middleName","A"); - middleNameFilter.setBooleanOperator(BooleanOperator.AND); - Filters filters = new Filters(); - filters.add(nameFilter, middleNameFilter); + Actor loadedActor = this.template.queryForObject(Actor.class, "MATCH (a:Actor) WHERE a.name={param} RETURN a", + Collections.singletonMap("param", "Alec Baldwin")); + assertNotNull("The entity wasn't loaded", loadedActor); + assertEquals("Alec Baldwin", loadedActor.getName()); + } - User u = template.loadByProperties(User.class,filters,0); - assertEquals(0,u.getRatings().size()); + @Test + @Transactional + public void shouldQueryForObjectCollectionUsingBespokeCypherQuery() { + this.template.save(new User("Jeff")); + this.template.save(new User("John")); + this.template.save(new User("Colin")); - u = template.loadByProperties(User.class, filters,2); - assertEquals(2,u.getRatings().size()); - assertNotNull(u.getRatings().iterator().next().getMovie().getRatings()); - } + Iterable users = this.template.queryForObjects(User.class, "MATCH (u:User) WHERE u.name=~'J.*' RETURN u", + Collections. emptyMap()); + assertNotNull("The entity wasn't loaded", users); + assertTrue("The entity wasn't loaded", users.iterator().hasNext()); + for (User loadedUser : users) { + assertTrue("Shouldn't've loaded " + loadedUser.getName(), + loadedUser.getName().equals("John") || loadedUser.getName().equals("Jeff")); + } + } - @Transactional - public void saveUsers2() { - User user = new User("Harmanpreet Singh"); - user.setMiddleName("A"); - User user2 = new User("Harmanpreet Singh"); - user2.setMiddleName("B"); - TempMovie bollywood = new TempMovie("Desi Boyz"); - TempMovie hollywood = new TempMovie("Mission Impossible"); - template.save(user.rate(bollywood, 1, "Bakwaas")); - template.save(user.rate(hollywood, 4, "Pretty good")); - template.save(user2); - } + @Test + @Transactional + public void shouldRetrieveEntitiesByMatchingProperty() { + this.template.save(new Genre("Thriller")); + this.template.save(new Genre("Horror")); + this.template.save(new Genre("Period Drama")); - /** - * @see DATAGRAPH-685 - */ - @Test - public void shouldRetrieveAllEntitiesByMatchingPropertiesAndDepth() { - saveUsers3(); + Genre loadedGenre = this.template.loadByProperty(Genre.class, "name", "Horror"); + assertNotNull("No genre was loaded", loadedGenre); + assertEquals("Horror", loadedGenre.getName()); + } + /** + * @see DATAGRAPH-685 + */ + @Test + @Transactional + public void shouldRetrieveEntitiesByMatchingPropertyAndDepth() { + User user = new User("Harmanpreet Singh"); + TempMovie bollywood = new TempMovie("Desi Boyz"); + TempMovie hollywood = new TempMovie("Mission Impossible"); - Filter nameFilter = new Filter("name","Harmanpreet Singh"); - Filter middleNameFilter = new Filter("middleName","A"); - middleNameFilter.setBooleanOperator(BooleanOperator.AND); - Filters filters = new Filters(); - filters.add(nameFilter, middleNameFilter); + template.save(user.rate(bollywood, 1, "Bakwaas")); + template.save(user.rate(hollywood, 4, "Pretty good")); - Collection u = template.loadAllByProperties(User.class,filters,0); - assertEquals(2,u.size()); - assertEquals(0,u.iterator().next().getRatings().size()); + template.clear(); - u = template.loadAllByProperties(User.class, filters,2); - assertEquals(2,u.size()); - assertNotNull(u.iterator().next().getRatings().iterator().next().getMovie().getRatings()); - } + User u = template.loadByProperty(User.class, "name", "Harmanpreet Singh", 0); + assertEquals(0, u.getRatings().size()); - @Transactional - public void saveUsers3() { - User user = new User("Harmanpreet Singh"); - user.setMiddleName("A"); - User user2 = new User("Harmanpreet Singh"); - user2.setMiddleName("A"); - TempMovie bollywood = new TempMovie("Desi Boyz"); - TempMovie hollywood = new TempMovie("Mission Impossible"); - template.save(user.rate(bollywood, 1, "Bakwaas")); - template.save(user.rate(hollywood, 4, "Pretty good")); - template.save(user2); - } + u = template.loadByProperty(User.class, "name", "Harmanpreet Singh", 2); + assertEquals(2, u.getRatings().size()); + assertNotNull(u.getRatings().iterator().next().getMovie().getRatings()); + } - @Test - public void shouldExecuteArbitraryUpdateQuery() { - assertTrue("There shouldn't be any genres in the database", this.template.loadAll(Genre.class).isEmpty()); + /** + * @see DATAGRAPH-685 + */ + @Test + public void shouldRetrieveAllEntitiesByMatchingPropertyAndDepth() { + saveUsers(); - this.template.query("CREATE (:Genre {name:'Comedy'}), (:Genre {name:'Action'})", Collections.EMPTY_MAP); + Collection m = template.loadAllByProperty(TempMovie.class, "name", "Desi Boyz", 0); + assertEquals(2, m.size()); + assertEquals(0, m.iterator().next().getRatings().size()); - Iterator genres = this.template.loadAll(Genre.class, 0).iterator(); - assertEquals("There weren't any genres created", 2, Utils.size(genres)); - } + m = template.loadAllByProperty(TempMovie.class, "name", "Desi Boyz", 1); + assertEquals(2, m.size()); + assertEquals(1, m.iterator().next().getRatings().size()); + } - /** - * @see DATAGRAPH-607 - */ - @Test(expected = java.lang.RuntimeException.class) - @Ignore // review 2.0 - public void shouldThrowExceptionForExecuteQueryThatReturnsResults() { - this.template.query("CREATE (g1:Genre {name:'Comedy'}), (g2:Genre {name:'Action'}) return g1", Collections.EMPTY_MAP); - } + @Transactional + public void saveUsers() { + User user = new User("Harmanpreet Singh"); + TempMovie bollywood = new TempMovie("Desi Boyz"); + TempMovie hollywood = new TempMovie("Desi Boyz"); + template.save(user.rate(bollywood, 1, "Bakwaas")); + template.save(user.rate(hollywood, 4, "Pretty good")); + } - @Test - public void shouldCountNumberOfEntitiesOfParticularTypeInGraphDatabase() { - GraphDatabaseService database = graphDatabaseService; - try (Transaction tx = database.beginTx()) { - // create test entities where label matches simple name - Label genreTypeLabel = DynamicLabel.label(Genre.class.getSimpleName()); - for (int i = 0; i < 5; i++) { - database.createNode(genreTypeLabel); - } + /** + * @see DATAGRAPH-685 + */ + @Test + public void shouldRetrieveEntitiesByMatchingPropertiesAndDepth() { + saveUsers2(); - // create test entities where label's controlled by annotations - Label filmTypeLabel = DynamicLabel.label(TempMovie.class.getAnnotation(NodeEntity.class).label()); - for (int i = 0; i < 3; i++) { - database.createNode(filmTypeLabel); - } + Filter nameFilter = new Filter("name", "Harmanpreet Singh"); + Filter middleNameFilter = new Filter("middleName", "A"); + middleNameFilter.setBooleanOperator(BooleanOperator.AND); + Filters filters = new Filters(); + filters.add(nameFilter, middleNameFilter); - // throw in a User to check it doesn't confuse things - database.createNode(DynamicLabel.label(User.class.getSimpleName())); + User u = template.loadByProperties(User.class, filters, 0); + assertEquals(0, u.getRatings().size()); - tx.success(); - } + u = template.loadByProperties(User.class, filters, 2); + assertEquals(2, u.getRatings().size()); + assertNotNull(u.getRatings().iterator().next().getMovie().getRatings()); + } - assertEquals(5, this.template.count(Genre.class)); - assertEquals(3, this.template.count(TempMovie.class)); - } + @Transactional + public void saveUsers2() { + User user = new User("Harmanpreet Singh"); + user.setMiddleName("A"); + User user2 = new User("Harmanpreet Singh"); + user2.setMiddleName("B"); + TempMovie bollywood = new TempMovie("Desi Boyz"); + TempMovie hollywood = new TempMovie("Mission Impossible"); + template.save(user.rate(bollywood, 1, "Bakwaas")); + template.save(user.rate(hollywood, 4, "Pretty good")); + template.save(user2); + } - @Test - public void shouldDeleteExistingEntitiesByGraphId() { - Long genreId = graphDatabaseService.execute("CREATE (t:Genre {name:'Thriller'}), (r:Genre {name:'RomCom'}) RETURN id(r) AS gid") - .columnAs("gid").next(); + /** + * @see DATAGRAPH-685 + */ + @Test + public void shouldRetrieveAllEntitiesByMatchingPropertiesAndDepth() { + saveUsers3(); - Genre entity = this.template.load(Genre.class, genreId); - assertEquals("RomCom", entity.getName()); - this.template.delete(entity); + Filter nameFilter = new Filter("name", "Harmanpreet Singh"); + Filter middleNameFilter = new Filter("middleName", "A"); + middleNameFilter.setBooleanOperator(BooleanOperator.AND); + Filters filters = new Filters(); + filters.add(nameFilter, middleNameFilter); - Collection allGenres = this.template.loadAll(Genre.class, 0); - assertEquals("The genre wasn't deleted", 1, allGenres.size()); - assertEquals("The wrong genre was deleted", "Thriller", allGenres.iterator().next().getName()); - } + Collection u = template.loadAllByProperties(User.class, filters, 0); + assertEquals(2, u.size()); + assertEquals(0, u.iterator().next().getRatings().size()); - /** - * @see DATAGRAPH-738 - */ - @Test(expected = InvalidDataAccessApiUsageException.class) - public void shouldConvertOGMExceptionsToPersistenceExceptions() { - this.template.loadAll(Rating.class, 0); - } + u = template.loadAllByProperties(User.class, filters, 2); + assertEquals(2, u.size()); + assertNotNull(u.iterator().next().getRatings().iterator().next().getMovie().getRatings()); + } - /** - * @see DATAGRAPH-604, DATAGRAPH-738 - */ - @Test(expected = Exception.class) - public void shouldHandleErrorsOnExecute() { - this.template.query("CREAT (node:NODE)", Collections.EMPTY_MAP); - } + @Transactional + public void saveUsers3() { + User user = new User("Harmanpreet Singh"); + user.setMiddleName("A"); + User user2 = new User("Harmanpreet Singh"); + user2.setMiddleName("A"); + TempMovie bollywood = new TempMovie("Desi Boyz"); + TempMovie hollywood = new TempMovie("Mission Impossible"); + template.save(user.rate(bollywood, 1, "Bakwaas")); + template.save(user.rate(hollywood, 4, "Pretty good")); + template.save(user2); + } - /** - * @see DATAGRAPH-607 - */ - @Test - public void shouldReturnQueryStats() { - QueryStatistics stats = this.template.query("CREATE (a:Actor {name:'Keanu Reeves'}) CREATE (m:Movie {title:'The Matrix'}) " + - "CREATE (a)-[:ACTED_IN {role:'Neo'}]->(m)", Collections.EMPTY_MAP).queryStatistics(); + @Test + public void shouldExecuteArbitraryUpdateQuery() { + assertTrue("There shouldn't be any genres in the database", this.template.loadAll(Genre.class).isEmpty()); - assertEquals(2, stats.getNodesCreated()); - assertEquals(3, stats.getPropertiesSet()); - assertEquals(1, stats.getRelationshipsCreated()); - assertEquals(2, stats.getLabelsAdded()); + this.template.query("CREATE (:Genre {name:'Comedy'}), (:Genre {name:'Action'})", Collections.EMPTY_MAP); - stats = this.template.query("MATCH (a:Actor)-->(m:Movie) REMOVE a:Actor SET m.title=null", Collections.EMPTY_MAP).queryStatistics(); - assertTrue(stats.containsUpdates()); - assertEquals(1, stats.getLabelsRemoved()); - assertEquals(1, stats.getPropertiesSet()); + Iterator genres = this.template.loadAll(Genre.class, 0).iterator(); + assertEquals("There weren't any genres created", 2, Utils.size(genres)); + } - stats = this.template.query("MATCH (n)-[r]-(m:Movie) delete n,r,m",Collections.EMPTY_MAP).queryStatistics(); - assertTrue(stats.containsUpdates()); - assertEquals(2, stats.getNodesDeleted()); - assertEquals(1, stats.getRelationshipsDeleted()); - } + /** + * @see DATAGRAPH-607 + */ + @Test(expected = java.lang.RuntimeException.class) + @Ignore // review 2.0 + public void shouldThrowExceptionForExecuteQueryThatReturnsResults() { + this.template.query("CREATE (g1:Genre {name:'Comedy'}), (g2:Genre {name:'Action'}) return g1", + Collections.EMPTY_MAP); + } - /** - * @see DATAGRAPH-607 - */ - @Test - public void shouldReturnSchemaQueryStats() { - QueryStatistics stats = this.template.query("CREATE INDEX ON :Actor(name)", Collections.EMPTY_MAP).queryStatistics(); - assertEquals(1, stats.getIndexesAdded()); + @Test + public void shouldCountNumberOfEntitiesOfParticularTypeInGraphDatabase() { + GraphDatabaseService database = graphDatabaseService; + try (Transaction tx = database.beginTx()) { + // create test entities where label matches simple name + Label genreTypeLabel = DynamicLabel.label(Genre.class.getSimpleName()); + for (int i = 0; i < 5; i++) { + database.createNode(genreTypeLabel); + } - stats = this.template.query("CREATE CONSTRAINT ON (movie:Movie) ASSERT movie.title IS UNIQUE", Collections.EMPTY_MAP).queryStatistics(); - assertEquals(1, stats.getConstraintsAdded()); + // create test entities where label's controlled by annotations + Label filmTypeLabel = DynamicLabel.label(TempMovie.class.getAnnotation(NodeEntity.class).label()); + for (int i = 0; i < 3; i++) { + database.createNode(filmTypeLabel); + } - stats = this.template.query("DROP CONSTRAINT ON (movie:Movie) ASSERT movie.title is UNIQUE", Collections.EMPTY_MAP).queryStatistics(); - assertEquals(1, stats.getConstraintsRemoved()); + // throw in a User to check it doesn't confuse things + database.createNode(DynamicLabel.label(User.class.getSimpleName())); - stats = this.template.query("DROP INDEX ON :Actor(name)", Collections.EMPTY_MAP).queryStatistics(); - assertEquals(1, stats.getIndexesRemoved()); - } + tx.success(); + } - /** - * @see DATAGRAPH-607 - */ - @Test - public void shouldReturnQueryStatsForQueryWithParams() { - QueryStatistics stats = this.template.query("CREATE (a:Actor {name:{actorName}}) CREATE (m:Movie {title:{movieTitle}}) " + - "CREATE (a)-[:ACTED_IN {role:'Neo'}]->(m)", map("actorName", "Keanu Reeves", "movieTitle", "THe Matrix")).queryStatistics(); - assertTrue(stats.containsUpdates()); - assertEquals(2, stats.getNodesCreated()); - assertEquals(3, stats.getPropertiesSet()); - assertEquals(1, stats.getRelationshipsCreated()); - assertEquals(2, stats.getLabelsAdded()); + assertEquals(5, this.template.count(Genre.class)); + assertEquals(3, this.template.count(TempMovie.class)); + } - stats = this.template.query("MATCH (a:Actor)-->(m:Movie) REMOVE a:Actor SET m.title=null", Collections.EMPTY_MAP).queryStatistics(); - assertTrue(stats.containsUpdates()); - assertEquals(1, stats.getLabelsRemoved()); - assertEquals(1, stats.getPropertiesSet()); + @Test + public void shouldDeleteExistingEntitiesByGraphId() { + Long genreId = graphDatabaseService + .execute("CREATE (t:Genre {name:'Thriller'}), (r:Genre {name:'RomCom'}) RETURN id(r) AS gid") + . columnAs("gid").next(); - stats = this.template.query("MATCH (n)-[r]-(m:Movie) delete n,r,m", Collections.EMPTY_MAP).queryStatistics(); - assertTrue(stats.containsUpdates()); - assertEquals(2, stats.getNodesDeleted()); - assertEquals(1, stats.getRelationshipsDeleted()); - } + Genre entity = this.template.load(Genre.class, genreId); + assertEquals("RomCom", entity.getName()); + this.template.delete(entity); - /** - * @see DATAGRAPH-629 - */ - @Test - public void shouldRetrieveEntitiesByMatchingProperties() { - this.template.save(new Cinema("Ritzy", 5000)); - this.template.save(new Cinema("Picturehouse", 7500)); + Collection allGenres = this.template.loadAll(Genre.class, 0); + assertEquals("The genre wasn't deleted", 1, allGenres.size()); + assertEquals("The wrong genre was deleted", "Thriller", allGenres.iterator().next().getName()); + } - Filter name = new Filter("name", "Ritzy"); - Cinema loadedCinema = this.template.loadByProperties(Cinema.class, new Filters().add(name)); - assertNotNull("No cinema was loaded", loadedCinema); - assertEquals("Ritzy", loadedCinema.getName()); + /** + * @see DATAGRAPH-738 + */ + @Test(expected = InvalidDataAccessApiUsageException.class) + public void shouldConvertOGMExceptionsToPersistenceExceptions() { + this.template.loadAll(Rating.class, 0); + } - Filter capacity = new Filter("capacity", 1000); - capacity.setComparisonOperator(ComparisonOperator.GREATER_THAN); - Collection loadedCinemas = this.template.loadAllByProperties(Cinema.class, new Filters().add(capacity)); - assertNotNull(loadedCinemas); - assertEquals(2, loadedCinemas.size()); - assertTrue(loadedCinemas.contains(new Cinema("Ritzy", 5000))); - assertTrue(loadedCinemas.contains(new Cinema("Picturehouse", 7500))); - } + /** + * @see DATAGRAPH-604, DATAGRAPH-738 + */ + @Test(expected = Exception.class) + public void shouldHandleErrorsOnExecute() { + this.template.query("CREAT (node:NODE)", Collections.EMPTY_MAP); + } - /** - * @see DATAGRAPH-697 - */ - @Test - public void shouldAllowResultsToBeReturnedFromModifyingQueries() { - Result results = this.template.query( - "CREATE (a:Actor {name:{actorName}}) CREATE (m:Movie {title:{movieTitle}}) " + - "CREATE (a)-[:ACTED_IN {role:'Neo'}]->(m) return a.name as actorName, m.title as movieName", map("actorName", "Keanu Reeves", "movieTitle", "The Matrix")); + /** + * @see DATAGRAPH-607 + */ + @Test + public void shouldReturnQueryStats() { + QueryStatistics stats = this.template + .query("CREATE (a:Actor {name:'Keanu Reeves'}) CREATE (m:Movie {title:'The Matrix'}) " + + "CREATE (a)-[:ACTED_IN {role:'Neo'}]->(m)", Collections.EMPTY_MAP) + .queryStatistics(); - QueryStatistics stats = results.queryStatistics(); - assertEquals(2, stats.getNodesCreated()); - assertEquals(3, stats.getPropertiesSet()); - assertEquals(1, stats.getRelationshipsCreated()); - assertEquals(2, stats.getLabelsAdded()); + assertEquals(2, stats.getNodesCreated()); + assertEquals(3, stats.getPropertiesSet()); + assertEquals(1, stats.getRelationshipsCreated()); + assertEquals(2, stats.getLabelsAdded()); - Iterable> iterableResults = results.queryResults(); - assertNotNull(iterableResults); - for(Map row : iterableResults) { - assertEquals("Keanu Reeves",row.get("actorName")); - assertEquals("The Matrix", row.get("movieName")); - } - } + stats = this.template.query("MATCH (a:Actor)-->(m:Movie) REMOVE a:Actor SET m.title=null", Collections.EMPTY_MAP) + .queryStatistics(); + assertTrue(stats.containsUpdates()); + assertEquals(1, stats.getLabelsRemoved()); + assertEquals(1, stats.getPropertiesSet()); - /** - * @see DATAGRAPH-863 - */ - @Test - public void shouldAllowDeletionOfNodeEntityAgainstEmptyDatabase() { - try { - clearDatabase(); - this.template.deleteAll(Movie.class); - } catch (Exception e) { - fail("Should not have thrown exception: " + e.getLocalizedMessage()); - } - } + stats = this.template.query("MATCH (n)-[r]-(m:Movie) delete n,r,m", Collections.EMPTY_MAP).queryStatistics(); + assertTrue(stats.containsUpdates()); + assertEquals(2, stats.getNodesDeleted()); + assertEquals(1, stats.getRelationshipsDeleted()); + } - /** - * @see DATAGRAPH-863 - */ - @Test - public void shouldAllowDeletionOfRelationshipEntityAgainstEmptyDatabase() { - try { - clearDatabase(); - this.template.deleteAll(Rating.class); - } catch (Exception e) { - fail("Should not have thrown exception: " + e.getLocalizedMessage()); - } - } + /** + * @see DATAGRAPH-607 + */ + @Test + public void shouldReturnSchemaQueryStats() { + QueryStatistics stats = this.template.query("CREATE INDEX ON :Actor(name)", Collections.EMPTY_MAP) + .queryStatistics(); + assertEquals(1, stats.getIndexesAdded()); + + stats = this.template + .query("CREATE CONSTRAINT ON (movie:Movie) ASSERT movie.title IS UNIQUE", Collections.EMPTY_MAP) + .queryStatistics(); + assertEquals(1, stats.getConstraintsAdded()); + + stats = this.template.query("DROP CONSTRAINT ON (movie:Movie) ASSERT movie.title is UNIQUE", Collections.EMPTY_MAP) + .queryStatistics(); + assertEquals(1, stats.getConstraintsRemoved()); + + stats = this.template.query("DROP INDEX ON :Actor(name)", Collections.EMPTY_MAP).queryStatistics(); + assertEquals(1, stats.getIndexesRemoved()); + } + + /** + * @see DATAGRAPH-607 + */ + @Test + public void shouldReturnQueryStatsForQueryWithParams() { + QueryStatistics stats = this.template + .query( + "CREATE (a:Actor {name:{actorName}}) CREATE (m:Movie {title:{movieTitle}}) " + + "CREATE (a)-[:ACTED_IN {role:'Neo'}]->(m)", + map("actorName", "Keanu Reeves", "movieTitle", "THe Matrix")) + .queryStatistics(); + assertTrue(stats.containsUpdates()); + assertEquals(2, stats.getNodesCreated()); + assertEquals(3, stats.getPropertiesSet()); + assertEquals(1, stats.getRelationshipsCreated()); + assertEquals(2, stats.getLabelsAdded()); + + stats = this.template.query("MATCH (a:Actor)-->(m:Movie) REMOVE a:Actor SET m.title=null", Collections.EMPTY_MAP) + .queryStatistics(); + assertTrue(stats.containsUpdates()); + assertEquals(1, stats.getLabelsRemoved()); + assertEquals(1, stats.getPropertiesSet()); + + stats = this.template.query("MATCH (n)-[r]-(m:Movie) delete n,r,m", Collections.EMPTY_MAP).queryStatistics(); + assertTrue(stats.containsUpdates()); + assertEquals(2, stats.getNodesDeleted()); + assertEquals(1, stats.getRelationshipsDeleted()); + } + + /** + * @see DATAGRAPH-629 + */ + @Test + public void shouldRetrieveEntitiesByMatchingProperties() { + this.template.save(new Cinema("Ritzy", 5000)); + this.template.save(new Cinema("Picturehouse", 7500)); + + Filter name = new Filter("name", "Ritzy"); + Cinema loadedCinema = this.template.loadByProperties(Cinema.class, new Filters().add(name)); + assertNotNull("No cinema was loaded", loadedCinema); + assertEquals("Ritzy", loadedCinema.getName()); + + Filter capacity = new Filter("capacity", 1000); + capacity.setComparisonOperator(ComparisonOperator.GREATER_THAN); + Collection loadedCinemas = this.template.loadAllByProperties(Cinema.class, new Filters().add(capacity)); + assertNotNull(loadedCinemas); + assertEquals(2, loadedCinemas.size()); + assertTrue(loadedCinemas.contains(new Cinema("Ritzy", 5000))); + assertTrue(loadedCinemas.contains(new Cinema("Picturehouse", 7500))); + } + + /** + * @see DATAGRAPH-697 + */ + @Test + public void shouldAllowResultsToBeReturnedFromModifyingQueries() { + Result results = this.template.query( + "CREATE (a:Actor {name:{actorName}}) CREATE (m:Movie {title:{movieTitle}}) " + + "CREATE (a)-[:ACTED_IN {role:'Neo'}]->(m) return a.name as actorName, m.title as movieName", + map("actorName", "Keanu Reeves", "movieTitle", "The Matrix")); + + QueryStatistics stats = results.queryStatistics(); + assertEquals(2, stats.getNodesCreated()); + assertEquals(3, stats.getPropertiesSet()); + assertEquals(1, stats.getRelationshipsCreated()); + assertEquals(2, stats.getLabelsAdded()); + + Iterable> iterableResults = results.queryResults(); + assertNotNull(iterableResults); + for (Map row : iterableResults) { + assertEquals("Keanu Reeves", row.get("actorName")); + assertEquals("The Matrix", row.get("movieName")); + } + } + + /** + * @see DATAGRAPH-863 + */ + @Test + public void shouldAllowDeletionOfNodeEntityAgainstEmptyDatabase() { + try { + clearDatabase(); + this.template.deleteAll(Movie.class); + } catch (Exception e) { + fail("Should not have thrown exception: " + e.getLocalizedMessage()); + } + } + + /** + * @see DATAGRAPH-863 + */ + @Test + public void shouldAllowDeletionOfRelationshipEntityAgainstEmptyDatabase() { + try { + clearDatabase(); + this.template.deleteAll(Rating.class); + } catch (Exception e) { + fail("Should not have thrown exception: " + e.getLocalizedMessage()); + } + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/TemplateApplicationEventIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/TemplateApplicationEventIT.java index 7eeacc2b2..4a0e77fc9 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/TemplateApplicationEventIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/TemplateApplicationEventIT.java @@ -37,11 +37,9 @@ import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) public class TemplateApplicationEventIT extends MultiDriverTestClass { - @Autowired - private Session session; + @Autowired private Session session; - @Autowired - private Neo4jModificationEventListener eventListener; + @Autowired private Neo4jModificationEventListener eventListener; @Test @Transactional diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/TestNeo4jEventListener.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/TestNeo4jEventListener.java index 43ec6eea6..b52b8a071 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/TestNeo4jEventListener.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/template/TestNeo4jEventListener.java @@ -17,9 +17,9 @@ import org.neo4j.ogm.session.event.Event; import org.springframework.data.neo4j.events.ModificationEvent; /** - * Spring {@code ApplicationListener} used to capture {@link Event}s that occur during a test run. - * Note that this is abstract because you're supposed to create an anonymous subclass to handle event type 'E' when you - * use it. This ensures Spring doesn't just send {@link Event}s to everything regardless. + * Spring {@code ApplicationListener} used to capture {@link Event}s that occur during a test run. Note that this is + * abstract because you're supposed to create an anonymous subclass to handle event type 'E' when you use it. This + * ensures Spring doesn't just send {@link Event}s to everything regardless. * * @author Adam George */ diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/Neo4jTransactionManagerTests.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/Neo4jTransactionManagerTests.java index d23f9237b..4f7acdb08 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/Neo4jTransactionManagerTests.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/Neo4jTransactionManagerTests.java @@ -37,7 +37,6 @@ public class Neo4jTransactionManagerTests { private TransactionTemplate tt; - @Before public void setUp() throws Exception { sf = mock(SessionFactory.class); @@ -72,25 +71,28 @@ public class Neo4jTransactionManagerTests { Result res = mock(Result.class); - given(session.query("some query string", Collections.emptyMap())).willReturn(res); + given(session.query("some query string", Collections. emptyMap())).willReturn(res); given(res.queryResults()).willReturn(list); - assertTrue("Transaction Synchronization already has a thread bound session", !TransactionSynchronizationManager.hasResource(sf)); + assertTrue("Transaction Synchronization already has a thread bound session", + !TransactionSynchronizationManager.hasResource(sf)); assertTrue("Synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue("Transaction Synchronization doesn't have a thread bound session", TransactionSynchronizationManager.hasResource(sf)); + assertTrue("Transaction Synchronization doesn't have a thread bound session", + TransactionSynchronizationManager.hasResource(sf)); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); Session session = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession(); - return session.query("some query string", Collections.emptyMap()).queryResults(); + return session.query("some query string", Collections. emptyMap()).queryResults(); } }); assertTrue("Incorrect result list", result == list); - assertTrue("Transaction Synchronization still has a thread bound session", !TransactionSynchronizationManager.hasResource(sf)); + assertTrue("Transaction Synchronization still has a thread bound session", + !TransactionSynchronizationManager.hasResource(sf)); assertTrue("Synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); verify(session).beginTransaction(); @@ -101,14 +103,16 @@ public class Neo4jTransactionManagerTests { @Test public void testTransactionRollback() throws Exception { - assertTrue("Transaction Synchronization already has a thread bound session", !TransactionSynchronizationManager.hasResource(sf)); + assertTrue("Transaction Synchronization already has a thread bound session", + !TransactionSynchronizationManager.hasResource(sf)); assertTrue("Synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); try { tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue("Transaction Synchronization doesn't have a thread bound session", TransactionSynchronizationManager.hasResource(sf)); + assertTrue("Transaction Synchronization doesn't have a thread bound session", + TransactionSynchronizationManager.hasResource(sf)); throw new RuntimeException("application exception"); } }); @@ -117,7 +121,8 @@ public class Neo4jTransactionManagerTests { // expected } - assertTrue("Transaction Synchronization still has a thread bound session", !TransactionSynchronizationManager.hasResource(sf)); + assertTrue("Transaction Synchronization still has a thread bound session", + !TransactionSynchronizationManager.hasResource(sf)); assertTrue("Synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); verify(session).beginTransaction(); @@ -128,18 +133,21 @@ public class Neo4jTransactionManagerTests { @Test public void testTransactionRollbackOnly() throws Exception { - assertTrue("Transaction Synchronization already has a thread bound session", !TransactionSynchronizationManager.hasResource(sf)); + assertTrue("Transaction Synchronization already has a thread bound session", + !TransactionSynchronizationManager.hasResource(sf)); tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue("Transaction Synchronization doesn't have a thread bound session", TransactionSynchronizationManager.hasResource(sf)); + assertTrue("Transaction Synchronization doesn't have a thread bound session", + TransactionSynchronizationManager.hasResource(sf)); status.setRollbackOnly(); return null; } }); - assertTrue("Transaction Synchronization still has a thread bound session", !TransactionSynchronizationManager.hasResource(sf)); + assertTrue("Transaction Synchronization still has a thread bound session", + !TransactionSynchronizationManager.hasResource(sf)); verify(session).beginTransaction(); verify(tx).rollback(); @@ -221,193 +229,193 @@ public class Neo4jTransactionManagerTests { verify(tx).close(); } -// -// @Test -// public void testTransactionCommitWithPreBound() throws Exception { -// tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); -// final List l = new ArrayList(); -// l.add("test"); -// assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); -// TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); -// assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); -// -// Object result = tt.execute(new TransactionCallback() { -// @Override -// public Object doInTransaction(TransactionStatus status) { -// assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); -// SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); -// assertTrue("Has thread transaction", sessionHolder.getSession().getTransaction() != null); -// Session sess = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession(); -// assertEquals(session, sess); -// return l; -// } -// }); -// assertTrue("Correct result list", result == l); -// -// assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); -// SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); -// assertTrue("Hasn't thread transaction", sessionHolder.getSession().getTransaction() == null); -// TransactionSynchronizationManager.unbindResource(sf); -// assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); -// -// verify(tx).commit(); -// } -// -// @Test -// public void testTransactionRollbackWithPreBound() throws Exception { -// -// final Transaction tx1 = mock(Transaction.class); -// final Transaction tx2 = mock(Transaction.class); -// -// given(session.beginTransaction()).willReturn(tx1, tx2); -// -// tm.setSessionFactory(sf); -// assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); -// TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); -// assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); -// -// try { -// tt.execute(new TransactionCallbackWithoutResult() { -// @Override -// public void doInTransactionWithoutResult(TransactionStatus status) { -// assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); -// SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); -// assertEquals(tx1, sessionHolder.getSession().getTransaction()); -// tt.execute(new TransactionCallbackWithoutResult() { -// @Override -// public void doInTransactionWithoutResult(TransactionStatus status) { -// status.setRollbackOnly(); -// Session sess = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession(); -// assertEquals(session, sess); -// } -// }); -// } -// }); -// fail("Should have thrown UnexpectedRollbackException"); -// } -// catch (UnexpectedRollbackException ex) { -// // expected -// } -// -// assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); -// SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); -// assertTrue("Hasn't thread transaction", sessionHolder.getSession().getTransaction() == null); -// assertTrue("Not marked rollback-only", !sessionHolder.isRollbackOnly()); -// -// tt.execute(new TransactionCallbackWithoutResult() { -// @Override -// public void doInTransactionWithoutResult(TransactionStatus status) { -// assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); -// SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); -// assertEquals(tx2, sessionHolder.getSession().getTransaction()); -// Session sess = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession(); -// assertEquals(session, sess); -// } -// }); -// -// assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); -// assertTrue("Hasn't thread transaction", sessionHolder.getSession().getTransaction() == null); -// TransactionSynchronizationManager.unbindResource(sf); -// assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); -// -// verify(tx1).rollback(); -// verify(tx2).commit(); -// InOrder ordered = inOrder(session); -// ordered.verify(session).clear(); -// } -// -// -// @Test -// public void testTransactionCommitWithNonExistingDatabase() throws Exception { -// tm.setSessionFactory(sf); -// tm.afterPropertiesSet(); -// TransactionTemplate tt = new TransactionTemplate(tm); -// tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); -// tt.setTimeout(10); -// assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); -// assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); -// -// try { -// tt.execute(new TransactionCallback() { -// @Override -// public Object doInTransaction(TransactionStatus status) { -// assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); -// Session session = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession(); -// return session.query("from java.lang.Object", Collections.emptyMap()).queryResults(); -// } -// }); -// fail("Should have thrown CannotCreateTransactionException"); -// } -// catch (CannotCreateTransactionException ex) { -// // expected -// } -// -// assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); -// assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); -// } -// -// @Test -// public void testTransactionCommitWithPreBoundSessionAndNonExistingDatabase() throws Exception { -// tm.setSessionFactory(sf); -// tm.afterPropertiesSet(); -// tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); -// tt.setTimeout(10); -// assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); -// assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); -// -// Session session = sf.openSession(); -// TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); -// try { -// tt.execute(new TransactionCallback() { -// @Override -// public Object doInTransaction(TransactionStatus status) { -// assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); -// Session session = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession(); -// return session.query("from java.lang.Object", Collections.emptyMap()).queryResults(); -// } -// }); -// fail("Should have thrown CannotCreateTransactionException"); -// } -// catch (CannotCreateTransactionException ex) { -// // expected -// SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); -// assertFalse(holder.isSynchronizedWithTransaction()); -// } -// finally { -// TransactionSynchronizationManager.unbindResource(sf); -// } -// -// assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); -// assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); -// } -// -// -// @Test -// public void testTransactionCommitWithRollbackException() { -// willThrow(new RuntimeException()).given(tx).commit(); -// -// final List l = new ArrayList<>(); -// l.add("test"); -// -// assertTrue(!TransactionSynchronizationManager.hasResource(sf)); -// assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); -// -// try { -// Object result = tt.execute(new TransactionCallback() { -// @Override -// public Object doInTransaction(TransactionStatus status) { -// assertTrue(TransactionSynchronizationManager.hasResource(sf)); -// return l; -// } -// }); -// assertSame(l, result); -// } catch (TransactionSystemException tse) { -// // expected -// assertTrue(tse.getCause() instanceof RuntimeException); -// } -// -// assertTrue(!TransactionSynchronizationManager.hasResource(sf)); -// assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); -// } -// + // + // @Test + // public void testTransactionCommitWithPreBound() throws Exception { + // tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + // final List l = new ArrayList(); + // l.add("test"); + // assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + // TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + // assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + // + // Object result = tt.execute(new TransactionCallback() { + // @Override + // public Object doInTransaction(TransactionStatus status) { + // assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + // SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); + // assertTrue("Has thread transaction", sessionHolder.getSession().getTransaction() != null); + // Session sess = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession(); + // assertEquals(session, sess); + // return l; + // } + // }); + // assertTrue("Correct result list", result == l); + // + // assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + // SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); + // assertTrue("Hasn't thread transaction", sessionHolder.getSession().getTransaction() == null); + // TransactionSynchronizationManager.unbindResource(sf); + // assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + // + // verify(tx).commit(); + // } + // + // @Test + // public void testTransactionRollbackWithPreBound() throws Exception { + // + // final Transaction tx1 = mock(Transaction.class); + // final Transaction tx2 = mock(Transaction.class); + // + // given(session.beginTransaction()).willReturn(tx1, tx2); + // + // tm.setSessionFactory(sf); + // assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + // TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + // assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + // + // try { + // tt.execute(new TransactionCallbackWithoutResult() { + // @Override + // public void doInTransactionWithoutResult(TransactionStatus status) { + // assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + // SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); + // assertEquals(tx1, sessionHolder.getSession().getTransaction()); + // tt.execute(new TransactionCallbackWithoutResult() { + // @Override + // public void doInTransactionWithoutResult(TransactionStatus status) { + // status.setRollbackOnly(); + // Session sess = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession(); + // assertEquals(session, sess); + // } + // }); + // } + // }); + // fail("Should have thrown UnexpectedRollbackException"); + // } + // catch (UnexpectedRollbackException ex) { + // // expected + // } + // + // assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + // SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); + // assertTrue("Hasn't thread transaction", sessionHolder.getSession().getTransaction() == null); + // assertTrue("Not marked rollback-only", !sessionHolder.isRollbackOnly()); + // + // tt.execute(new TransactionCallbackWithoutResult() { + // @Override + // public void doInTransactionWithoutResult(TransactionStatus status) { + // assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + // SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); + // assertEquals(tx2, sessionHolder.getSession().getTransaction()); + // Session sess = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession(); + // assertEquals(session, sess); + // } + // }); + // + // assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + // assertTrue("Hasn't thread transaction", sessionHolder.getSession().getTransaction() == null); + // TransactionSynchronizationManager.unbindResource(sf); + // assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + // + // verify(tx1).rollback(); + // verify(tx2).commit(); + // InOrder ordered = inOrder(session); + // ordered.verify(session).clear(); + // } + // + // + // @Test + // public void testTransactionCommitWithNonExistingDatabase() throws Exception { + // tm.setSessionFactory(sf); + // tm.afterPropertiesSet(); + // TransactionTemplate tt = new TransactionTemplate(tm); + // tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + // tt.setTimeout(10); + // assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); + // assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + // + // try { + // tt.execute(new TransactionCallback() { + // @Override + // public Object doInTransaction(TransactionStatus status) { + // assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + // Session session = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession(); + // return session.query("from java.lang.Object", Collections.emptyMap()).queryResults(); + // } + // }); + // fail("Should have thrown CannotCreateTransactionException"); + // } + // catch (CannotCreateTransactionException ex) { + // // expected + // } + // + // assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); + // assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + // } + // + // @Test + // public void testTransactionCommitWithPreBoundSessionAndNonExistingDatabase() throws Exception { + // tm.setSessionFactory(sf); + // tm.afterPropertiesSet(); + // tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + // tt.setTimeout(10); + // assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); + // assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + // + // Session session = sf.openSession(); + // TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + // try { + // tt.execute(new TransactionCallback() { + // @Override + // public Object doInTransaction(TransactionStatus status) { + // assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + // Session session = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession(); + // return session.query("from java.lang.Object", Collections.emptyMap()).queryResults(); + // } + // }); + // fail("Should have thrown CannotCreateTransactionException"); + // } + // catch (CannotCreateTransactionException ex) { + // // expected + // SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); + // assertFalse(holder.isSynchronizedWithTransaction()); + // } + // finally { + // TransactionSynchronizationManager.unbindResource(sf); + // } + // + // assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); + // assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + // } + // + // + // @Test + // public void testTransactionCommitWithRollbackException() { + // willThrow(new RuntimeException()).given(tx).commit(); + // + // final List l = new ArrayList<>(); + // l.add("test"); + // + // assertTrue(!TransactionSynchronizationManager.hasResource(sf)); + // assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + // + // try { + // Object result = tt.execute(new TransactionCallback() { + // @Override + // public Object doInTransaction(TransactionStatus status) { + // assertTrue(TransactionSynchronizationManager.hasResource(sf)); + // return l; + // } + // }); + // assertSame(l, result); + // } catch (TransactionSystemException tse) { + // // expected + // assertTrue(tse.getCause() instanceof RuntimeException); + // } + // + // assertTrue(!TransactionSynchronizationManager.hasResource(sf)); + // assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + // } + // } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/SessionFactoryUtilsTests.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/SessionFactoryUtilsTests.java index 796d2f09e..306f141a0 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/SessionFactoryUtilsTests.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/SessionFactoryUtilsTests.java @@ -47,7 +47,8 @@ public class SessionFactoryUtilsTests { @Test public void translateToDataIntegrityException() { - CypherException ce = new CypherException("Cypher Exception caused by:", "Neo.ClientError.Schema.ConstraintValidationFailed", "The reason"); + CypherException ce = new CypherException("Cypher Exception caused by:", + "Neo.ClientError.Schema.ConstraintValidationFailed", "The reason"); DataAccessException translatedException = SessionFactoryUtils.convertOgmAccessException(ce); expectExceptionWithCauseMessage(translatedException, DataIntegrityViolationException.class, null); } @@ -69,14 +70,13 @@ public class SessionFactoryUtilsTests { assertThat(SessionFactoryUtils.convertOgmAccessException(exception), is(nullValue())); } - private static void expectExceptionWithCauseMessage(NestedRuntimeException e, - Class type) { + Class type) { expectExceptionWithCauseMessage(e, type, null); } private static void expectExceptionWithCauseMessage(NestedRuntimeException e, - Class type, String message) { + Class type, String message) { assertThat(e, is(instanceOf(type))); diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/SharedSessionCreatorTests.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/SharedSessionCreatorTests.java index 640dd0c34..5b5f404f9 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/SharedSessionCreatorTests.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/SharedSessionCreatorTests.java @@ -28,7 +28,6 @@ import org.neo4j.ogm.session.SessionFactory; */ public class SharedSessionCreatorTests { - @Test public void proxyingWorksIfInfoReturnsNullSessionInterface() { SessionFactory sessionFactory = mock(SessionFactory.class); diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/TransactionalEventListenerTests.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/TransactionalEventListenerTests.java index 969925d9a..9fc3b1aa6 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/TransactionalEventListenerTests.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transaction/TransactionalEventListenerTests.java @@ -7,7 +7,11 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; import org.junit.Before; import org.junit.Rule; @@ -27,14 +31,20 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.event.TransactionalEventListener; import org.springframework.transaction.event.TransactionalEventListenerFactory; -import org.springframework.transaction.support.*; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionCallback; +import org.springframework.transaction.support.TransactionSynchronizationAdapter; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; /** - * These tests are copied from - * the spring framework transactional event listener tests - * and modified to work with a version of the Neo4jTransactionManager. + * These tests are copied from the + * spring framework transactional event listener tests and modified to work with a version of the + * Neo4jTransactionManager. * * @author Mark Angrish * @see DATAGRAPH-883 @@ -47,9 +57,7 @@ public class TransactionalEventListenerTests { private TransactionTemplate transactionTemplate = new TransactionTemplate(new CallCountingTransactionManager()); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - + @Rule public final ExpectedException thrown = ExpectedException.none(); @Before public void closeContext() { @@ -58,7 +66,6 @@ public class TransactionalEventListenerTests { } } - @Test public void immediately() { load(ImmediateTestListener.class); @@ -255,8 +262,7 @@ public class TransactionalEventListenerTests { @Test public void noTransaction() { - load(BeforeCommitTestListener.class, AfterCompletionTestListener.class, - AfterCompletionExplicitTestListener.class); + load(BeforeCommitTestListener.class, AfterCompletionTestListener.class, AfterCompletionExplicitTestListener.class); this.context.publishEvent("test"); getEventCollector().assertTotalEventsCount(0); } @@ -315,7 +321,6 @@ public class TransactionalEventListenerTests { getEventCollector().assertNoEventReceived(); } - protected EventCollector getEventCollector() { return eventCollector; } @@ -336,7 +341,6 @@ public class TransactionalEventListenerTests { this.eventCollector = this.context.getBean(EventCollector.class); } - @Configuration static class BasicConfiguration { @@ -361,7 +365,6 @@ public class TransactionalEventListenerTests { } } - static class EventCollector { public static final String IMMEDIATELY = "IMMEDIATELY"; @@ -374,7 +377,7 @@ public class TransactionalEventListenerTests { public static final String AFTER_ROLLBACK = "AFTER_ROLLBACK"; - public static final String[] ALL_PHASES = {IMMEDIATELY, BEFORE_COMMIT, AFTER_COMMIT, AFTER_ROLLBACK}; + public static final String[] ALL_PHASES = { IMMEDIATELY, BEFORE_COMMIT, AFTER_COMMIT, AFTER_ROLLBACK }; private final MultiValueMap events = new LinkedMultiValueMap<>(); @@ -384,9 +387,7 @@ public class TransactionalEventListenerTests { public List getEvents(String phase) { List v; - return (((v = events.get(phase)) != null) || events.containsKey(phase)) - ? v - : Collections.emptyList(); + return (((v = events.get(phase)) != null) || events.containsKey(phase)) ? v : Collections.emptyList(); } public void assertNoEventReceived(String... phases) { @@ -395,8 +396,8 @@ public class TransactionalEventListenerTests { } for (String phase : phases) { List eventsForPhase = getEvents(phase); - assertEquals("Expected no events for phase '" + phase + "' " + - "but got " + eventsForPhase + ":", 0, eventsForPhase.size()); + assertEquals("Expected no events for phase '" + phase + "' " + "but got " + eventsForPhase + ":", 0, + eventsForPhase.size()); } } @@ -413,18 +414,15 @@ public class TransactionalEventListenerTests { for (Map.Entry> entry : this.events.entrySet()) { size += entry.getValue().size(); } - assertEquals("Wrong number of total events (" + this.events.size() + ") " + - "registered phase(s)", number, size); + assertEquals("Wrong number of total events (" + this.events.size() + ") " + "registered phase(s)", number, size); } } - static abstract class BaseTransactionalTestListener { static final String FAIL_MSG = "FAIL"; - @Autowired - private EventCollector eventCollector; + @Autowired private EventCollector eventCollector; public void handleEvent(String phase, String data) { this.eventCollector.addEvent(phase, data); @@ -434,7 +432,6 @@ public class TransactionalEventListenerTests { } } - @Component static class ImmediateTestListener extends BaseTransactionalTestListener { @@ -444,7 +441,6 @@ public class TransactionalEventListenerTests { } } - @Component static class AfterCompletionTestListener extends BaseTransactionalTestListener { @@ -454,7 +450,6 @@ public class TransactionalEventListenerTests { } } - @Component static class AfterCompletionExplicitTestListener extends BaseTransactionalTestListener { @@ -469,7 +464,6 @@ public class TransactionalEventListenerTests { } } - @Transactional @Component static interface TransactionalComponentTestListenerInterface { @@ -479,9 +473,8 @@ public class TransactionalEventListenerTests { void handleAfterCommit(String data); } - - static class TransactionalComponentTestListener extends BaseTransactionalTestListener implements - TransactionalComponentTestListenerInterface { + static class TransactionalComponentTestListener extends BaseTransactionalTestListener + implements TransactionalComponentTestListenerInterface { @Override public void handleAfterCommit(String data) { @@ -489,7 +482,6 @@ public class TransactionalEventListenerTests { } } - @Component static class BeforeCommitTestListener extends BaseTransactionalTestListener { @@ -500,7 +492,6 @@ public class TransactionalEventListenerTests { } } - @Component static class FallbackExecutionTestListener extends BaseTransactionalTestListener { @@ -525,7 +516,6 @@ public class TransactionalEventListenerTests { } } - @TransactionalEventListener(phase = AFTER_COMMIT, condition = "!'SKIP'.equals(#p0)") @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @@ -533,7 +523,6 @@ public class TransactionalEventListenerTests { } - @Component static class AfterCommitMetaAnnotationTestListener extends BaseTransactionalTestListener { @@ -543,7 +532,6 @@ public class TransactionalEventListenerTests { } } - static class EventTransactionSynchronization extends TransactionSynchronizationAdapter { private final int order; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/ApplicationConfig.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/ApplicationConfig.java index caa100547..16b510054 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/ApplicationConfig.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/ApplicationConfig.java @@ -21,7 +21,6 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; import org.springframework.data.neo4j.transaction.Neo4jTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.annotation.TransactionManagementConfigurer; /** * @author Vince Bickers @@ -34,7 +33,7 @@ import org.springframework.transaction.annotation.TransactionManagementConfigure public class ApplicationConfig { @Bean - public PlatformTransactionManager transactionManager() { + public PlatformTransactionManager transactionManager() { return new Neo4jTransactionManager(sessionFactory()); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/ExtendedTransactionsIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/ExtendedTransactionsIT.java index 8e4f76764..0a86cec00 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/ExtendedTransactionsIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/ExtendedTransactionsIT.java @@ -34,18 +34,15 @@ import org.springframework.transaction.annotation.Transactional; * @see http://stackoverflow.com/questions/17224887/java-spring-transactional-method-not-rolling-back-as-expected * @see DATAGRAPH-602 */ -@ContextConfiguration(classes = {ApplicationConfig.class}) +@ContextConfiguration(classes = { ApplicationConfig.class }) @RunWith(SpringJUnit4ClassRunner.class) public class ExtendedTransactionsIT extends MultiDriverTestClass { - @Autowired - ServiceA serviceA; + @Autowired ServiceA serviceA; - @Autowired - ServiceB serviceB; + @Autowired ServiceB serviceB; - @Autowired - WrapperService wrapperService; + @Autowired WrapperService wrapperService; @Test public void shouldRollbackSuccessThenFail() { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/TransactionIntegrationIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/TransactionIntegrationIT.java index 3321090cc..59634a319 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/TransactionIntegrationIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/TransactionIntegrationIT.java @@ -28,25 +28,22 @@ import org.springframework.data.neo4j.examples.movies.repo.UserRepository; import org.springframework.data.neo4j.examples.movies.service.UserService; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.annotation.Transactional; /** * @author Michal Bachman */ -@ContextConfiguration(classes = {MoviesContext.class}) +@ContextConfiguration(classes = { MoviesContext.class }) @RunWith(SpringJUnit4ClassRunner.class) public class TransactionIntegrationIT extends MultiDriverTestClass { private static GraphDatabaseService graphDatabaseService; - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; - @Autowired - private UserService userService; + @Autowired private UserService userService; @BeforeClass - public static void beforeClass(){ + public static void beforeClass() { graphDatabaseService = getGraphDatabaseService(); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/domain/User.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/domain/User.java index cedcd21dc..946a35581 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/domain/User.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/domain/User.java @@ -20,37 +20,34 @@ import org.neo4j.ogm.annotation.Transient; */ public class User { - private Long id; - private String name; - @Transient - private String species; + private Long id; + private String name; + @Transient private String species; - public User() { - } + public User() {} - public Long id() { - return this.id; - } + public Long id() { + return this.id; + } - public User(String name) { - this.name = name; - } + public User(String name) { + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } + public String getSpecies() { + return species; + } - public String getSpecies() { - return species; - } - - public void setSpecies(String species) { - this.species = species; - } + public void setSpecies(String species) { + this.species = species; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/repo/UserRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/repo/UserRepository.java index 46dad4780..9efbd623b 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/repo/UserRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/repo/UserRepository.java @@ -25,5 +25,5 @@ import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends GraphRepository { - Collection findUserByName(String name); + Collection findUserByName(String name); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/BusinessService.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/BusinessService.java index 8b406b956..7b3e3b49b 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/BusinessService.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/BusinessService.java @@ -28,31 +28,30 @@ import org.springframework.transaction.annotation.Transactional; @Component public class BusinessService { - @Autowired - private Session session; + @Autowired private Session session; - @Transactional - public void successMethodInTransaction() { - insert(); - } + @Transactional + public void successMethodInTransaction() { + insert(); + } - @Transactional // throws unchecked exception - public void failMethodInTransaction() { - insert(); - throw new RuntimeException("Deliberately throwing exception"); - } + @Transactional // throws unchecked exception + public void failMethodInTransaction() { + insert(); + throw new RuntimeException("Deliberately throwing exception"); + } - // transactional only from service wrapper, throws checked exception - public void throwsException() throws Exception { - insert(); - throw new Exception("Deliberately throwing exception"); - } + // transactional only from service wrapper, throws checked exception + public void throwsException() throws Exception { + insert(); + throw new Exception("Deliberately throwing exception"); + } - public void insert() { - session.query("CREATE (node {name: 'n'})", Collections.EMPTY_MAP); - } + public void insert() { + session.query("CREATE (node {name: 'n'})", Collections.EMPTY_MAP); + } - public Iterable> fetch() { - return session.query("MATCH (n) RETURN n.name", new HashMap()); - } + public Iterable> fetch() { + return session.query("MATCH (n) RETURN n.name", new HashMap()); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/ServiceA.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/ServiceA.java index 930d9d74a..f6289373e 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/ServiceA.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/ServiceA.java @@ -17,7 +17,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.neo4j.transactions.domain.User; import org.springframework.data.neo4j.transactions.repo.UserRepository; import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** @@ -26,19 +25,17 @@ import org.springframework.transaction.annotation.Transactional; @Component public class ServiceA { - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; - @Autowired - private ServiceB serviceB; + @Autowired private ServiceB serviceB; - @Transactional(rollbackFor = Exception.class) - public void run() throws Exception { - saveBilbo(); - serviceB.update(); - } + @Transactional(rollbackFor = Exception.class) + public void run() throws Exception { + saveBilbo(); + serviceB.update(); + } - public User saveBilbo() { - return userRepository.save(new User("Bilbo baggins")); - } + public User saveBilbo() { + return userRepository.save(new User("Bilbo baggins")); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/ServiceB.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/ServiceB.java index a077d83c4..c43a0e4ca 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/ServiceB.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/ServiceB.java @@ -19,7 +19,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.neo4j.transactions.domain.User; import org.springframework.data.neo4j.transactions.repo.UserRepository; import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** @@ -28,20 +27,19 @@ import org.springframework.transaction.annotation.Transactional; @Component public class ServiceB { - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; - @Transactional(rollbackFor = Exception.class) - public void update() throws Exception { - getBilbo(); - throw new Exception(); - } + @Transactional(rollbackFor = Exception.class) + public void update() throws Exception { + getBilbo(); + throw new Exception(); + } - public User getBilbo() { - Collection userList = userRepository.findUserByName("Bilbo Baggins"); - if (userList.iterator().hasNext()) { - return userList.iterator().next(); - } - return null; - } + public User getBilbo() { + Collection userList = userRepository.findUserByName("Bilbo Baggins"); + if (userList.iterator().hasNext()) { + return userList.iterator().next(); + } + return null; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/WrapperService.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/WrapperService.java index 812690aba..31f738b1b 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/WrapperService.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/transactions/service/WrapperService.java @@ -24,40 +24,39 @@ import org.springframework.transaction.annotation.Transactional; @Component public class WrapperService { - @Autowired - BusinessService businessService; + @Autowired BusinessService businessService; - @Transactional - public void composeSuccessThenFail() { - businessService.successMethodInTransaction(); - businessService.failMethodInTransaction(); - } + @Transactional + public void composeSuccessThenFail() { + businessService.successMethodInTransaction(); + businessService.failMethodInTransaction(); + } - @Transactional - public void composeSuccessThenSuccess() { - businessService.successMethodInTransaction(); - businessService.successMethodInTransaction(); - } + @Transactional + public void composeSuccessThenSuccess() { + businessService.successMethodInTransaction(); + businessService.successMethodInTransaction(); + } - @Transactional - public void composeFailThenSuccess() { - businessService.failMethodInTransaction(); - businessService.successMethodInTransaction(); - } + @Transactional + public void composeFailThenSuccess() { + businessService.failMethodInTransaction(); + businessService.successMethodInTransaction(); + } - @Transactional - public void composeFailThenFail() { - businessService.failMethodInTransaction(); - businessService.failMethodInTransaction(); - } + @Transactional + public void composeFailThenFail() { + businessService.failMethodInTransaction(); + businessService.failMethodInTransaction(); + } - @Transactional(rollbackFor=Exception.class) - public void rollbackWithCheckedException() throws Exception { - businessService.throwsException(); - } + @Transactional(rollbackFor = Exception.class) + public void rollbackWithCheckedException() throws Exception { + businessService.throwsException(); + } - @Transactional(readOnly = true) - public Iterable> fetch() { - return businessService.fetch(); - } + @Transactional(readOnly = true) + public Iterable> fetch() { + return businessService.fetch(); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/util/IterableUtilsIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/util/IterableUtilsIT.java index bbb9ec86f..6c05f1be7 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/util/IterableUtilsIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/util/IterableUtilsIT.java @@ -36,7 +36,7 @@ public class IterableUtilsIT extends MultiDriverTestClass { private static GraphDatabaseService database; @BeforeClass - public static void beforeClass(){ + public static void beforeClass() { database = getGraphDatabaseService(); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/WebIntegrationIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/WebIntegrationIT.java index b79157c59..47ae20b60 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/WebIntegrationIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/WebIntegrationIT.java @@ -20,8 +20,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -47,19 +45,16 @@ import org.springframework.web.context.WebApplicationContext; * @author Michal Bachman * @author Mark Angrish */ -@ContextConfiguration(classes = {WebAppContext.class}) +@ContextConfiguration(classes = { WebAppContext.class }) @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) public class WebIntegrationIT extends MultiDriverTestClass { - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; - @Autowired - private WebApplicationContext wac; + @Autowired private WebApplicationContext wac; - @Autowired - PlatformTransactionManager transactionManager; + @Autowired PlatformTransactionManager transactionManager; private MockMvc mockMvc; @@ -97,15 +92,12 @@ public class WebIntegrationIT extends MultiDriverTestClass { userRepository.save(adam); } - @Test public void shouldNotShareSessionBetweenRequestsWithDifferentSession() throws Exception { - mockMvc.perform(get("/user/{uuid}/friends", adam.getUuid())) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/friends", adam.getUuid())).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Daniela")); - mockMvc.perform(get("/user/{uuid}/friends", vince.getUuid())) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/friends", vince.getUuid())).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Michal")); } @@ -113,24 +105,19 @@ public class WebIntegrationIT extends MultiDriverTestClass { public void shouldShareSessionBetweenRequestsDuringSameSession() throws Exception { MockHttpSession session = new MockHttpSession(); - mockMvc.perform(get("/user/{uuid}/immediateFriends", adam.getUuid()).session(session)) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/immediateFriends", adam.getUuid()).session(session)).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Daniela")); - mockMvc.perform(get("/user/{uuid}/immediateFriends", daniela.getUuid()).session(session)) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/immediateFriends", daniela.getUuid()).session(session)).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Adam Michal")); - mockMvc.perform(get("/user/{uuid}/immediateFriends", michal.getUuid()).session(session)) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/immediateFriends", michal.getUuid()).session(session)).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Daniela Vince")); - mockMvc.perform(get("/user/{uuid}/immediateFriends", vince.getUuid()).session(session)) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/immediateFriends", vince.getUuid()).session(session)).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Michal")); } - @Test public void shouldNotShareSessionBetweenMultiThreadedRequests() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(10); @@ -141,8 +128,7 @@ public class WebIntegrationIT extends MultiDriverTestClass { public void run() { if (j % 2 == 0) { try { - mockMvc.perform(get("/user/{uuid}/friends", adam.getUuid())) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/friends", adam.getUuid())).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Daniela")); } catch (Exception e) { throw new RuntimeException(e); @@ -150,8 +136,7 @@ public class WebIntegrationIT extends MultiDriverTestClass { } else { try { - mockMvc.perform(get("/user/{uuid}/friends", vince.getUuid())) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/friends", vince.getUuid())).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Michal")); } catch (Exception e) { throw new RuntimeException(e); diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/XmlApplicationContextWebIntegrationIT.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/XmlApplicationContextWebIntegrationIT.java index bb5487c4c..d59f6b9f4 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/XmlApplicationContextWebIntegrationIT.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/XmlApplicationContextWebIntegrationIT.java @@ -25,13 +25,11 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.neo4j.ogm.testutil.MultiDriverTestClass; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.neo4j.web.context.WebAppContext; import org.springframework.data.neo4j.web.domain.User; import org.springframework.data.neo4j.web.repo.UserRepository; import org.springframework.mock.web.MockHttpSession; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @@ -51,14 +49,11 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) public class XmlApplicationContextWebIntegrationIT extends MultiDriverTestClass { - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; - @Autowired - private WebApplicationContext wac; + @Autowired private WebApplicationContext wac; - @Autowired - PlatformTransactionManager transactionManager; + @Autowired PlatformTransactionManager transactionManager; private MockMvc mockMvc; @@ -96,15 +91,12 @@ public class XmlApplicationContextWebIntegrationIT extends MultiDriverTestClass userRepository.save(adam); } - @Test public void shouldNotShareSessionBetweenRequestsWithDifferentSession() throws Exception { - mockMvc.perform(get("/user/{uuid}/friends", adam.getUuid())) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/friends", adam.getUuid())).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Daniela")); - mockMvc.perform(get("/user/{uuid}/friends", vince.getUuid())) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/friends", vince.getUuid())).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Michal")); } @@ -112,24 +104,19 @@ public class XmlApplicationContextWebIntegrationIT extends MultiDriverTestClass public void shouldShareSessionBetweenRequestsDuringSameSession() throws Exception { MockHttpSession session = new MockHttpSession(); - mockMvc.perform(get("/user/{uuid}/immediateFriends", adam.getUuid()).session(session)) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/immediateFriends", adam.getUuid()).session(session)).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Daniela")); - mockMvc.perform(get("/user/{uuid}/immediateFriends", daniela.getUuid()).session(session)) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/immediateFriends", daniela.getUuid()).session(session)).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Adam Michal")); - mockMvc.perform(get("/user/{uuid}/immediateFriends", michal.getUuid()).session(session)) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/immediateFriends", michal.getUuid()).session(session)).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Daniela Vince")); - mockMvc.perform(get("/user/{uuid}/immediateFriends", vince.getUuid()).session(session)) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/immediateFriends", vince.getUuid()).session(session)).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Michal")); } - @Test public void shouldNotShareSessionBetweenMultiThreadedRequests() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(10); @@ -140,8 +127,7 @@ public class XmlApplicationContextWebIntegrationIT extends MultiDriverTestClass public void run() { if (j % 2 == 0) { try { - mockMvc.perform(get("/user/{uuid}/friends", adam.getUuid())) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/friends", adam.getUuid())).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Daniela")); } catch (Exception e) { throw new RuntimeException(e); @@ -149,8 +135,7 @@ public class XmlApplicationContextWebIntegrationIT extends MultiDriverTestClass } else { try { - mockMvc.perform(get("/user/{uuid}/friends", vince.getUuid())) - .andExpect(status().isOk()) + mockMvc.perform(get("/user/{uuid}/friends", vince.getUuid())).andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Michal")); } catch (Exception e) { throw new RuntimeException(e); diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/context/WebAppContext.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/context/WebAppContext.java index 2da84fe01..431d1c751 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/context/WebAppContext.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/context/WebAppContext.java @@ -33,7 +33,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter */ @Configuration @EnableWebMvc -@ComponentScan({"org.springframework.data.neo4j.web.controller", "org.springframework.data.neo4j.web.service"}) +@ComponentScan({ "org.springframework.data.neo4j.web.controller", "org.springframework.data.neo4j.web.service" }) @EnableNeo4jRepositories("org.springframework.data.neo4j.web.repo") @EnableTransactionManagement public class WebAppContext extends WebMvcConfigurerAdapter { diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/controller/UserController.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/controller/UserController.java index 74e8d97ee..47f50bcfd 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/controller/UserController.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/controller/UserController.java @@ -13,6 +13,13 @@ package org.springframework.data.neo4j.web.controller; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +import javax.servlet.http.HttpSession; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.neo4j.web.domain.User; import org.springframework.data.neo4j.web.service.UserService; @@ -22,12 +29,6 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; -import javax.servlet.http.HttpSession; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.UUID; - /** * @author Michal Bachman * @author Mark ANgrish @@ -35,47 +36,46 @@ import java.util.UUID; @Controller public class UserController { - @Autowired - private UserService userService; + @Autowired private UserService userService; - @RequestMapping(value = "/user/{uuid}/friends") - @ResponseBody - @Transactional - public String listFriends(@PathVariable UUID uuid, HttpSession session) { - User user = userService.getUserByUuid(uuid); + @RequestMapping(value = "/user/{uuid}/friends") + @ResponseBody + @Transactional + public String listFriends(@PathVariable UUID uuid, HttpSession session) { + User user = userService.getUserByUuid(uuid); - if (user == null) { - return "No such user!"; - } + if (user == null) { + return "No such user!"; + } - StringBuilder result = new StringBuilder(); - for (User friend : userService.getNetwork(user)) { - result.append(friend.getName()).append(" "); - } + StringBuilder result = new StringBuilder(); + for (User friend : userService.getNetwork(user)) { + result.append(friend.getName()).append(" "); + } - return result.toString().trim(); - } + return result.toString().trim(); + } - @RequestMapping(value = "/user/{uuid}/immediateFriends") - @ResponseBody - @Transactional - public String listImmediateFriends(@PathVariable UUID uuid, HttpSession session) { - User user = userService.getUserByUuid(uuid); + @RequestMapping(value = "/user/{uuid}/immediateFriends") + @ResponseBody + @Transactional + public String listImmediateFriends(@PathVariable UUID uuid, HttpSession session) { + User user = userService.getUserByUuid(uuid); - if (user == null) { - return "No such user!"; - } + if (user == null) { + return "No such user!"; + } - List friends = new ArrayList<>(); - for (User friend : user.getFriends()) { - friends.add(friend.getName()); - } - Collections.sort(friends); + List friends = new ArrayList<>(); + for (User friend : user.getFriends()) { + friends.add(friend.getName()); + } + Collections.sort(friends); - StringBuilder result = new StringBuilder(); - for(String friend : friends) { - result.append(friend).append(" "); - } - return result.toString().trim(); - } + StringBuilder result = new StringBuilder(); + for (String friend : friends) { + result.append(friend).append(" "); + } + return result.toString().trim(); + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/Cinema.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/Cinema.java index 2f68995f9..f4f6c2d9c 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/Cinema.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/Cinema.java @@ -13,6 +13,10 @@ package org.springframework.data.neo4j.web.domain; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + import org.neo4j.ogm.annotation.GraphId; import org.neo4j.ogm.annotation.Index; import org.neo4j.ogm.annotation.NodeEntity; @@ -20,10 +24,6 @@ import org.neo4j.ogm.annotation.Relationship; import org.neo4j.ogm.annotation.typeconversion.Convert; import org.neo4j.ogm.typeconversion.UuidStringConverter; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - /** * @author Michal Bachman * @author Mark Angrish @@ -31,32 +31,27 @@ import java.util.UUID; @NodeEntity public class Cinema { - @GraphId - private Long id; + @GraphId private Long id; - @Convert(UuidStringConverter.class) - @Index(unique = true, primary = true) - private UUID uuid; + @Convert(UuidStringConverter.class) @Index(unique = true, primary = true) private UUID uuid; - private String name; + private String name; - @Relationship(direction = Relationship.INCOMING) - private Set visited; + @Relationship(direction = Relationship.INCOMING) private Set visited; - public Cinema() { - } + public Cinema() {} - public Cinema(String name) { - this.visited = new HashSet<>(); - this.uuid = UUID.randomUUID(); - this.name = name; - } + public Cinema(String name) { + this.visited = new HashSet<>(); + this.uuid = UUID.randomUUID(); + this.name = name; + } - public void addVisitor(User user) { - visited.add(user); - } + public void addVisitor(User user) { + visited.add(user); + } - public String getName() { - return name; - } + public String getName() { + return name; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/Genre.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/Genre.java index 21a4397f5..68561bb9d 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/Genre.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/Genre.java @@ -28,32 +28,28 @@ import org.neo4j.ogm.typeconversion.UuidStringConverter; @NodeEntity public class Genre { - @GraphId - private Long id; + @GraphId private Long id; - @Convert(UuidStringConverter.class) - @Index(unique = true, primary = true) - private UUID uuid; + @Convert(UuidStringConverter.class) @Index(unique = true, primary = true) private UUID uuid; - private String name; + private String name; - public Genre() { - } + public Genre() {} - public Genre(String name) { - this.uuid = UUID.randomUUID(); - this.name = name; - } + public Genre(String name) { + this.uuid = UUID.randomUUID(); + this.name = name; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/User.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/User.java index b644b22f0..0b5109663 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/User.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/domain/User.java @@ -13,6 +13,11 @@ package org.springframework.data.neo4j.web.domain; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + import org.neo4j.ogm.annotation.GraphId; import org.neo4j.ogm.annotation.Index; import org.neo4j.ogm.annotation.NodeEntity; @@ -20,11 +25,6 @@ import org.neo4j.ogm.annotation.Relationship; import org.neo4j.ogm.annotation.typeconversion.Convert; import org.neo4j.ogm.typeconversion.UuidStringConverter; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - /** * @author Michal Bachman * @author Mark Angrish @@ -32,60 +32,55 @@ import java.util.UUID; @NodeEntity public class User { - @GraphId - private Long id; + @GraphId private Long id; - @Convert(UuidStringConverter.class) - @Index(unique = true, primary = true) - private UUID uuid; + @Convert(UuidStringConverter.class) @Index(unique = true, primary = true) private UUID uuid; - private String name; + private String name; - private Collection interested; + private Collection interested; - @Relationship(type = "FRIEND_OF", direction = Relationship.UNDIRECTED) - private Set friends; + @Relationship(type = "FRIEND_OF", direction = Relationship.UNDIRECTED) private Set friends; - public User() { - } + public User() {} - public User(String name) { - this.interested = new HashSet<>(); - this.friends = new HashSet<>(); - this.uuid = UUID.randomUUID(); - this.name = name; - } + public User(String name) { + this.interested = new HashSet<>(); + this.friends = new HashSet<>(); + this.uuid = UUID.randomUUID(); + this.name = name; + } - public void interestedIn(Genre genre) { - interested.add(genre); - } + public void interestedIn(Genre genre) { + interested.add(genre); + } - public void notInterestedIn(Genre genre) { - interested.remove(genre); - } + public void notInterestedIn(Genre genre) { + interested.remove(genre); + } - public void befriend(User user) { - friends.add(user); - } + public void befriend(User user) { + friends.add(user); + } - //this doesn't need to be part of the domain, but this class is for testing - public Long getId() { - return id; - } + // this doesn't need to be part of the domain, but this class is for testing + public Long getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Collection getFriends() { - return friends; - } + public Collection getFriends() { + return friends; + } - public UUID getUuid() { - return uuid; - } + public UUID getUuid() { + return uuid; + } } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/repo/UserRepository.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/repo/UserRepository.java index 6b6a3807e..4c9d0b342 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/repo/UserRepository.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/repo/UserRepository.java @@ -15,7 +15,6 @@ package org.springframework.data.neo4j.web.repo; import java.util.UUID; -import org.springframework.data.neo4j.repository.GraphRepository; import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.data.neo4j.web.domain.User; import org.springframework.stereotype.Repository; diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/service/UserService.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/service/UserService.java index 99340d519..5662c51a9 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/service/UserService.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/service/UserService.java @@ -13,17 +13,17 @@ package org.springframework.data.neo4j.web.service; -import org.springframework.data.neo4j.web.domain.User; - import java.util.Collection; import java.util.UUID; +import org.springframework.data.neo4j.web.domain.User; + /** * @author Michal Bachman */ public interface UserService { - User getUserByUuid(UUID uuid); + User getUserByUuid(UUID uuid); - Collection getNetwork(User user); + Collection getNetwork(User user); } diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/service/UserServiceImpl.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/service/UserServiceImpl.java index 75f0a7a9d..d37893913 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/service/UserServiceImpl.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/service/UserServiceImpl.java @@ -13,7 +13,11 @@ package org.springframework.data.neo4j.web.service; -import java.util.*; +import java.util.Collection; +import java.util.Comparator; +import java.util.Set; +import java.util.TreeSet; +import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.neo4j.web.domain.User; @@ -27,12 +31,11 @@ import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; @Override public User getUserByUuid(UUID uuid) { - return userRepository.findOne(uuid); + return userRepository.findOne(uuid); } @Override diff --git a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/support/OpenSessionInViewTests.java b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/support/OpenSessionInViewTests.java index df2e87956..4abe2bca5 100644 --- a/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/support/OpenSessionInViewTests.java +++ b/spring-data-neo4j/src/test/java/org/springframework/data/neo4j/web/support/OpenSessionInViewTests.java @@ -1,23 +1,31 @@ package org.springframework.data.neo4j.web.support; - import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; -import javax.servlet.*; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; +import javax.servlet.AsyncEvent; +import javax.servlet.AsyncListener; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + import org.junit.After; import org.junit.Before; import org.junit.Test; import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; import org.springframework.core.task.SimpleAsyncTaskExecutor; -import org.springframework.data.neo4j.web.support.OpenSessionInViewFilter; -import org.springframework.data.neo4j.web.support.OpenSessionInViewInterceptor; -import org.springframework.mock.web.*; +import org.springframework.mock.web.MockAsyncContext; +import org.springframework.mock.web.MockFilterConfig; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockServletContext; +import org.springframework.mock.web.PassThroughFilterChain; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.ServletWebRequest; @@ -42,7 +50,6 @@ public class OpenSessionInViewTests { private ServletWebRequest webRequest; - @Before public void setUp() throws Exception { sessionFactory = mock(SessionFactory.class);