diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0577e65c..b3a8e51e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,10 +19,12 @@ At the time of writing this is JDK7 (binary compatibility) but at compile time J ## Code Style -A dedicated and holistic code style is not yet defined. -Changes to existing classes should follow the style that is found in that specific class. +Google's Java code style is followed available [here](https://github.com/google/styleguide). -In gernal, the Google Code style should be followed. +The proper formatting is checked during compile time. To easily follow the style use **one** of those options: +1. Use [Eclipse Formatter](https://help.eclipse.org/neon/topic/org.eclipse.jdt.doc.user/reference/preferences/java/codestyle/ref-preferences-formatter.htm) with the `src/eclipse-java-google-style.xml` file. +1. Use [IntelliJ Formatter](https://blog.jetbrains.com/idea/2014/01/intellij-idea-13-importing-code-formatter-settings-from-eclipse/) with the `src/eclipse-java-google-style.xml` file. +1. Use `mvn formatter:format` to apply the style to the source files. ## Merging diff --git a/pom.xml b/pom.xml index efe159ef..a568d861 100755 --- a/pom.xml +++ b/pom.xml @@ -197,6 +197,11 @@ + + net.revelc.code.formatter + formatter-maven-plugin + 2.7.2 + org.apache.maven.plugins maven-enforcer-plugin @@ -286,6 +291,7 @@ src/test/resources/** src/main/resources/** **/*.psd + src/eclipse-java-google-style.xml @@ -353,6 +359,20 @@ + + net.revelc.code.formatter + formatter-maven-plugin + + ${project.basedir}/eclipse-formatter-config.xml + + + + + validate + + + + org.apache.maven.plugins maven-checkstyle-plugin diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 24e54f29..9f49ef39 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -52,6 +52,9 @@ Add support for DynamoDBTypeConverted annotations on hash key + + Fixed NullPointerException for findAllByOrderByProperty queries + diff --git a/src/eclipse-java-google-style.xml b/src/eclipse-java-google-style.xml new file mode 100644 index 00000000..56e50792 --- /dev/null +++ b/src/eclipse-java-google-style.xml @@ -0,0 +1,337 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/config/AbstractDynamoDBConfiguration.java b/src/main/java/org/socialsignin/spring/data/dynamodb/config/AbstractDynamoDBConfiguration.java index 6869fbe5..ebac053c 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/config/AbstractDynamoDBConfiguration.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/config/AbstractDynamoDBConfiguration.java @@ -40,75 +40,83 @@ @Configuration public abstract class AbstractDynamoDBConfiguration { - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDynamoDBConfiguration.class); - - public abstract AmazonDynamoDB amazonDynamoDB(); - - public abstract AWSCredentials amazonAWSCredentials(); - - /** - * Return the base packages to scan for mapped {@link DynamoDBTable}s. Will return the package name of the configuration - * class' (the concrete class, not this one here) by default. So if you have a {@code com.acme.AppConfig} extending - * {@link AbstractDynamoDBConfiguration} the base package will be considered {@code com.acme} unless the method is - * overriden to implement alternate behaviour. - * - * @return the base package to scan for mapped {@link DynamoDBTable} classes or {@literal null} to not enable scanning for - * entities. - */ - protected String[] getMappingBasePackages() { - - Package mappingBasePackage = getClass().getPackage(); - String basePackage = mappingBasePackage == null ? null : mappingBasePackage.getName(); - - return new String[]{basePackage}; - } - - /** - * Creates a {@link DynamoDBMappingContext} equipped with entity classes scanned from the mapping base package. - * - * @see #getMappingBasePackages() - * @return A newly created {@link DynamoDBMappingContext} - * @throws ClassNotFoundException if the class with {@link DynamoDBTable} annotation can't be loaded - */ - @Bean - public DynamoDBMappingContext dynamoDBMappingContext() throws ClassNotFoundException { - - DynamoDBMappingContext mappingContext = new DynamoDBMappingContext(); - mappingContext.setInitialEntitySet(getInitialEntitySet()); - - return mappingContext; - } - - /** - * Scans the mapping base package for classes annotated with {@link DynamoDBTable}. - * - * @see #getMappingBasePackages() - * @return All classes with {@link DynamoDBTable} annotation - * @throws ClassNotFoundException if the class with {@link DynamoDBTable} annotation can't be loaded - */ - protected Set> getInitialEntitySet() throws ClassNotFoundException { - - Set> initialEntitySet = new HashSet<>(); - - String[] basePackages = getMappingBasePackages(); - - for (String basePackage:basePackages) { - LOGGER.trace("getInitialEntitySet. basePackage: {}", basePackage); - - if (StringUtils.hasText(basePackage)) { - ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider( - false); - componentProvider.addIncludeFilter(new AnnotationTypeFilter(DynamoDBTable.class)); - - for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) { - LOGGER.trace("getInitialEntitySet. candidate: {}", candidate.getBeanClassName()); - initialEntitySet.add(ClassUtils.forName(candidate.getBeanClassName(), - AbstractDynamoDBConfiguration.class.getClassLoader())); - } - } - } - - return initialEntitySet; - } + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDynamoDBConfiguration.class); + + public abstract AmazonDynamoDB amazonDynamoDB(); + + public abstract AWSCredentials amazonAWSCredentials(); + + /** + * Return the base packages to scan for mapped {@link DynamoDBTable}s. Will + * return the package name of the configuration class' (the concrete class, not + * this one here) by default. So if you have a {@code com.acme.AppConfig} + * extending {@link AbstractDynamoDBConfiguration} the base package will be + * considered {@code com.acme} unless the method is overriden to implement + * alternate behaviour. + * + * @return the base package to scan for mapped {@link DynamoDBTable} classes or + * {@literal null} to not enable scanning for entities. + */ + protected String[] getMappingBasePackages() { + + Package mappingBasePackage = getClass().getPackage(); + String basePackage = mappingBasePackage == null ? null : mappingBasePackage.getName(); + + return new String[]{basePackage}; + } + + /** + * Creates a {@link DynamoDBMappingContext} equipped with entity classes scanned + * from the mapping base package. + * + * @see #getMappingBasePackages() + * @return A newly created {@link DynamoDBMappingContext} + * @throws ClassNotFoundException + * if the class with {@link DynamoDBTable} annotation can't be + * loaded + */ + @Bean + public DynamoDBMappingContext dynamoDBMappingContext() throws ClassNotFoundException { + + DynamoDBMappingContext mappingContext = new DynamoDBMappingContext(); + mappingContext.setInitialEntitySet(getInitialEntitySet()); + + return mappingContext; + } + + /** + * Scans the mapping base package for classes annotated with + * {@link DynamoDBTable}. + * + * @see #getMappingBasePackages() + * @return All classes with {@link DynamoDBTable} annotation + * @throws ClassNotFoundException + * if the class with {@link DynamoDBTable} annotation can't be + * loaded + */ + protected Set> getInitialEntitySet() throws ClassNotFoundException { + + Set> initialEntitySet = new HashSet<>(); + + String[] basePackages = getMappingBasePackages(); + + for (String basePackage : basePackages) { + LOGGER.trace("getInitialEntitySet. basePackage: {}", basePackage); + + if (StringUtils.hasText(basePackage)) { + ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider( + false); + componentProvider.addIncludeFilter(new AnnotationTypeFilter(DynamoDBTable.class)); + + for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) { + LOGGER.trace("getInitialEntitySet. candidate: {}", candidate.getBeanClassName()); + initialEntitySet.add(ClassUtils.forName(candidate.getBeanClassName(), + AbstractDynamoDBConfiguration.class.getClassLoader())); + } + } + } + + return initialEntitySet; + } } \ No newline at end of file diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/config/BeanNames.java b/src/main/java/org/socialsignin/spring/data/dynamodb/config/BeanNames.java index aa1b69d5..3743ae5e 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/config/BeanNames.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/config/BeanNames.java @@ -22,6 +22,6 @@ */ public abstract class BeanNames { - public static final String MAPPING_CONTEXT_BEAN_NAME = "dynamoDBMappingContext"; + public static final String MAPPING_CONTEXT_BEAN_NAME = "dynamoDBMappingContext"; } \ No newline at end of file diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingBeanDefinitionParser.java b/src/main/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingBeanDefinitionParser.java index b9b76a74..787acb36 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingBeanDefinitionParser.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingBeanDefinitionParser.java @@ -30,56 +30,68 @@ import static org.springframework.data.config.ParsingUtils.getObjectFactoryBeanDefinition; /** - * {@link org.springframework.beans.factory.xml.BeanDefinitionParser} to register a {@link AuditingEventListener} to transparently set auditing information on - * an entity. + * {@link org.springframework.beans.factory.xml.BeanDefinitionParser} to + * register a {@link AuditingEventListener} to transparently set auditing + * information on an entity. * * @author Vito Limandibhrata */ public class DynamoDBAuditingBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { - /* - * (non-Javadoc) - * @see org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser#getBeanClass(org.w3c.dom.Element) - */ - @Override - protected Class getBeanClass(Element element) { - return AuditingEventListener.class; - } + /* + * (non-Javadoc) + * + * @see + * org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser# + * getBeanClass(org.w3c.dom.Element) + */ + @Override + protected Class getBeanClass(Element element) { + return AuditingEventListener.class; + } - /* - * (non-Javadoc) - * @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#shouldGenerateId() - */ - @Override - protected boolean shouldGenerateId() { - return true; - } + /* + * (non-Javadoc) + * + * @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser# + * shouldGenerateId() + */ + @Override + protected boolean shouldGenerateId() { + return true; + } - /* - * (non-Javadoc) - * @see org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser#doParse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext, org.springframework.beans.factory.support.BeanDefinitionBuilder) - */ - @Override - protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser# + * doParse(org.w3c.dom.Element, + * org.springframework.beans.factory.xml.ParserContext, + * org.springframework.beans.factory.support.BeanDefinitionBuilder) + */ + @Override + protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { - String mappingContextRef = element.getAttribute("mapping-context-ref"); + String mappingContextRef = element.getAttribute("mapping-context-ref"); - if (!StringUtils.hasText(mappingContextRef)) { + if (!StringUtils.hasText(mappingContextRef)) { - BeanDefinitionRegistry registry = parserContext.getRegistry(); + BeanDefinitionRegistry registry = parserContext.getRegistry(); - if (!registry.containsBeanDefinition(MAPPING_CONTEXT_BEAN_NAME)) { - registry.registerBeanDefinition(MAPPING_CONTEXT_BEAN_NAME, new RootBeanDefinition(DynamoDBMappingContext.class)); - } + if (!registry.containsBeanDefinition(MAPPING_CONTEXT_BEAN_NAME)) { + registry.registerBeanDefinition(MAPPING_CONTEXT_BEAN_NAME, + new RootBeanDefinition(DynamoDBMappingContext.class)); + } - mappingContextRef = MAPPING_CONTEXT_BEAN_NAME; - } + mappingContextRef = MAPPING_CONTEXT_BEAN_NAME; + } - IsNewAwareAuditingHandlerBeanDefinitionParser parser = new IsNewAwareAuditingHandlerBeanDefinitionParser( - mappingContextRef); - parser.parse(element, parserContext); + IsNewAwareAuditingHandlerBeanDefinitionParser parser = new IsNewAwareAuditingHandlerBeanDefinitionParser( + mappingContextRef); + parser.parse(element, parserContext); - builder.addConstructorArgValue(getObjectFactoryBeanDefinition(parser.getResolvedBeanName(), - parserContext.extractSource(element))); - } + builder.addConstructorArgValue( + getObjectFactoryBeanDefinition(parser.getResolvedBeanName(), parserContext.extractSource(element))); + } } \ No newline at end of file diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingRegistrar.java b/src/main/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingRegistrar.java index fa3658b1..24942a96 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingRegistrar.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingRegistrar.java @@ -36,97 +36,119 @@ import static org.springframework.beans.factory.config.BeanDefinition.ROLE_INFRASTRUCTURE; /** - * {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar} to enable {@link EnableDynamoDBAuditing} annotation. + * {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar} + * to enable {@link EnableDynamoDBAuditing} annotation. * * @author Vito Limandibhrata */ class DynamoDBAuditingRegistrar extends AuditingBeanDefinitionRegistrarSupport { - private static Logger LOGGER = LoggerFactory.getLogger(DynamoDBAuditingRegistrar.class); - - /* - * (non-Javadoc) - * @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#getAnnotation() - */ - @Override - protected Class getAnnotation() { - return EnableDynamoDBAuditing.class; - } - - /* - * (non-Javadoc) - * @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#getAuditingHandlerBeanName() - */ - @Override - protected String getAuditingHandlerBeanName() { - return "dynamoDBAuditingHandler"; - } - - /* - * (non-Javadoc) - * @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#registerBeanDefinitions(org.springframework.core.type.AnnotationMetadata, org.springframework.beans.factory.support.BeanDefinitionRegistry) - */ - @Override - public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { - LOGGER.trace("registerBeanDefinitions"); - Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!"); - Assert.notNull(registry, "BeanDefinitionRegistry must not be null!"); - - defaultDependenciesIfNecessary(registry, annotationMetadata); - super.registerBeanDefinitions(annotationMetadata, registry); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#getAuditHandlerBeanDefinitionBuilder(org.springframework.data.auditing.config.AuditingConfiguration) - */ - @Override - protected BeanDefinitionBuilder getAuditHandlerBeanDefinitionBuilder(AuditingConfiguration configuration) { - LOGGER.trace("getAuditHandlerBeanDefinitionBuilder"); - Assert.notNull(configuration, "AuditingConfiguration must not be null!"); - - BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(IsNewAwareAuditingHandler.class); - builder.addConstructorArgReference(MAPPING_CONTEXT_BEAN_NAME); - return configureDefaultAuditHandlerAttributes(configuration, builder); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#registerAuditListener(org.springframework.beans.factory.config.BeanDefinition, org.springframework.beans.factory.support.BeanDefinitionRegistry) - */ - @Override - protected void registerAuditListenerBeanDefinition(BeanDefinition auditingHandlerDefinition, - BeanDefinitionRegistry registry) { - LOGGER.trace("registerAuditListenerBeanDefinition"); - Assert.notNull(auditingHandlerDefinition, "BeanDefinition must not be null!"); - Assert.notNull(registry, "BeanDefinitionRegistry must not be null!"); - - BeanDefinitionBuilder listenerBeanDefinitionBuilder = BeanDefinitionBuilder - .rootBeanDefinition(AuditingEventListener.class); - listenerBeanDefinitionBuilder.addConstructorArgValue(ParsingUtils.getObjectFactoryBeanDefinition( - getAuditingHandlerBeanName(), registry)); - - registerInfrastructureBeanWithId(listenerBeanDefinitionBuilder.getBeanDefinition(), - AuditingEventListener.class.getName(), registry); - } - - /** - * Register default bean definitions for a {@link DynamoDBMappingContext} and an {@link org.springframework.data.support.IsNewStrategyFactory} in case we - * don't find beans with the assumed names in the registry. - * - * @param registry the {@link BeanDefinitionRegistry} to use to register the components into. - * @param source the source which the registered components shall be registered with - */ - private void defaultDependenciesIfNecessary(BeanDefinitionRegistry registry, Object source) { - LOGGER.trace("defaultDependenciesIfNecessary. source:{}", source); - LOGGER.trace("is registry.containsBeanDefinition {} {}", MAPPING_CONTEXT_BEAN_NAME, registry.containsBeanDefinition(MAPPING_CONTEXT_BEAN_NAME)); - if (!registry.containsBeanDefinition(MAPPING_CONTEXT_BEAN_NAME)) { - - RootBeanDefinition definition = new RootBeanDefinition(DynamoDBMappingContext.class); - definition.setRole(ROLE_INFRASTRUCTURE); - definition.setSource(source); - - registry.registerBeanDefinition(MAPPING_CONTEXT_BEAN_NAME, definition); - } - } + private static Logger LOGGER = LoggerFactory.getLogger(DynamoDBAuditingRegistrar.class); + + /* + * (non-Javadoc) + * + * @see org.springframework.data.auditing.config. + * AuditingBeanDefinitionRegistrarSupport#getAnnotation() + */ + @Override + protected Class getAnnotation() { + return EnableDynamoDBAuditing.class; + } + + /* + * (non-Javadoc) + * + * @see org.springframework.data.auditing.config. + * AuditingBeanDefinitionRegistrarSupport#getAuditingHandlerBeanName() + */ + @Override + protected String getAuditingHandlerBeanName() { + return "dynamoDBAuditingHandler"; + } + + /* + * (non-Javadoc) + * + * @see org.springframework.data.auditing.config. + * AuditingBeanDefinitionRegistrarSupport#registerBeanDefinitions(org. + * springframework.core.type.AnnotationMetadata, + * org.springframework.beans.factory.support.BeanDefinitionRegistry) + */ + @Override + public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { + LOGGER.trace("registerBeanDefinitions"); + Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!"); + Assert.notNull(registry, "BeanDefinitionRegistry must not be null!"); + + defaultDependenciesIfNecessary(registry, annotationMetadata); + super.registerBeanDefinitions(annotationMetadata, registry); + } + + /* + * (non-Javadoc) + * + * @see org.springframework.data.auditing.config. + * AuditingBeanDefinitionRegistrarSupport#getAuditHandlerBeanDefinitionBuilder( + * org.springframework.data.auditing.config.AuditingConfiguration) + */ + @Override + protected BeanDefinitionBuilder getAuditHandlerBeanDefinitionBuilder(AuditingConfiguration configuration) { + LOGGER.trace("getAuditHandlerBeanDefinitionBuilder"); + Assert.notNull(configuration, "AuditingConfiguration must not be null!"); + + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(IsNewAwareAuditingHandler.class); + builder.addConstructorArgReference(MAPPING_CONTEXT_BEAN_NAME); + return configureDefaultAuditHandlerAttributes(configuration, builder); + } + + /* + * (non-Javadoc) + * + * @see org.springframework.data.auditing.config. + * AuditingBeanDefinitionRegistrarSupport#registerAuditListener(org. + * springframework.beans.factory.config.BeanDefinition, + * org.springframework.beans.factory.support.BeanDefinitionRegistry) + */ + @Override + protected void registerAuditListenerBeanDefinition(BeanDefinition auditingHandlerDefinition, + BeanDefinitionRegistry registry) { + LOGGER.trace("registerAuditListenerBeanDefinition"); + Assert.notNull(auditingHandlerDefinition, "BeanDefinition must not be null!"); + Assert.notNull(registry, "BeanDefinitionRegistry must not be null!"); + + BeanDefinitionBuilder listenerBeanDefinitionBuilder = BeanDefinitionBuilder + .rootBeanDefinition(AuditingEventListener.class); + listenerBeanDefinitionBuilder.addConstructorArgValue( + ParsingUtils.getObjectFactoryBeanDefinition(getAuditingHandlerBeanName(), registry)); + + registerInfrastructureBeanWithId(listenerBeanDefinitionBuilder.getBeanDefinition(), + AuditingEventListener.class.getName(), registry); + } + + /** + * Register default bean definitions for a {@link DynamoDBMappingContext} and an + * {@link org.springframework.data.support.IsNewStrategyFactory} in case we + * don't find beans with the assumed names in the registry. + * + * @param registry + * the {@link BeanDefinitionRegistry} to use to register the + * components into. + * @param source + * the source which the registered components shall be registered + * with + */ + private void defaultDependenciesIfNecessary(BeanDefinitionRegistry registry, Object source) { + LOGGER.trace("defaultDependenciesIfNecessary. source:{}", source); + LOGGER.trace("is registry.containsBeanDefinition {} {}", MAPPING_CONTEXT_BEAN_NAME, + registry.containsBeanDefinition(MAPPING_CONTEXT_BEAN_NAME)); + if (!registry.containsBeanDefinition(MAPPING_CONTEXT_BEAN_NAME)) { + + RootBeanDefinition definition = new RootBeanDefinition(DynamoDBMappingContext.class); + definition.setRole(ROLE_INFRASTRUCTURE); + definition.setSource(source); + + registry.registerBeanDefinition(MAPPING_CONTEXT_BEAN_NAME, definition); + } + } } \ No newline at end of file diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/config/EnableDynamoDBAuditing.java b/src/main/java/org/socialsignin/spring/data/dynamodb/config/EnableDynamoDBAuditing.java index 38e73661..521313ee 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/config/EnableDynamoDBAuditing.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/config/EnableDynamoDBAuditing.java @@ -36,24 +36,29 @@ @Import(DynamoDBAuditingRegistrar.class) public @interface EnableDynamoDBAuditing { - /** - * @return Configures the {@link org.springframework.data.domain.AuditorAware} bean to be used to lookup the current principal. - */ - String auditorAwareRef() default ""; + /** + * @return Configures the {@link org.springframework.data.domain.AuditorAware} + * bean to be used to lookup the current principal. + */ + String auditorAwareRef() default ""; - /** - * @return Configures whether the creation and modification dates are set. Defaults to {@literal true}. - */ - boolean setDates() default true; + /** + * @return Configures whether the creation and modification dates are set. + * Defaults to {@literal true}. + */ + boolean setDates() default true; - /** - * @return Configures whether the entity shall be marked as modified on creation. Defaults to {@literal true}. - */ - boolean modifyOnCreate() default true; + /** + * @return Configures whether the entity shall be marked as modified on + * creation. Defaults to {@literal true}. + */ + boolean modifyOnCreate() default true; - /** - * @return Configures a {@link org.springframework.data.auditing.DateTimeProvider} bean name that allows customizing the {@link org.joda.time.DateTime} to be - * used for setting creation and modification dates. - */ - String dateTimeProviderRef() default ""; + /** + * @return Configures a + * {@link org.springframework.data.auditing.DateTimeProvider} bean name + * that allows customizing the {@link org.joda.time.DateTime} to be used + * for setting creation and modification dates. + */ + String dateTimeProviderRef() default ""; } \ No newline at end of file diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBOperations.java b/src/main/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBOperations.java index b4e0bc6f..b0ef9d6c 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBOperations.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBOperations.java @@ -36,29 +36,31 @@ public interface DynamoDBOperations { int count(Class domainClass, DynamoDBScanExpression scanExpression); int count(Class clazz, QueryRequest mutableQueryRequest); - PaginatedQueryList query(Class clazz, QueryRequest queryRequest); PaginatedQueryList query(Class domainClass, DynamoDBQueryExpression queryExpression); PaginatedScanList scan(Class domainClass, DynamoDBScanExpression scanExpression); - T load(Class domainClass,Object hashKey, Object rangeKey); - T load(Class domainClass,Object hashKey); + T load(Class domainClass, Object hashKey, Object rangeKey); + T load(Class domainClass, Object hashKey); Map> batchLoad(Map, List> itemsToGet); T save(T entity); List batchSave(Iterable entities); T delete(T entity); - List batchDelete(Iterable entities); + List batchDelete(Iterable entities); String getOverriddenTableName(Class domainClass, String tableName); - /** - * Provides access to the DynamoDB mapper table model of the underlying domain type. - * - * @param The type of the domain type itself - * @param domainClass A domain type - * @return Corresponding DynamoDB table model - */ - DynamoDBMapperTableModel getTableModel(Class domainClass); + /** + * Provides access to the DynamoDB mapper table model of the underlying domain + * type. + * + * @param + * The type of the domain type itself + * @param domainClass + * A domain type + * @return Corresponding DynamoDB table model + */ + DynamoDBMapperTableModel getTableModel(Class domainClass); } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplate.java b/src/main/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplate.java index 77f18570..71a81ca5 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplate.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplate.java @@ -55,39 +55,59 @@ public class DynamoDBTemplate implements DynamoDBOperations, ApplicationContextA private final AmazonDynamoDB amazonDynamoDB; private final DynamoDBMapperConfig dynamoDBMapperConfig; private ApplicationEventPublisher eventPublisher; - - /** Convenient constructor to use the default {@link DynamoDBMapper#DynamoDBMapper(AmazonDynamoDB)} - * @param amazonDynamoDB The AWS SDK instance to talk to DynamoDB - * @param dynamoDBMapperConfig The config to use - * */ - public DynamoDBTemplate(AmazonDynamoDB amazonDynamoDB, DynamoDBMapperConfig dynamoDBMapperConfig) - { - this(amazonDynamoDB, dynamoDBMapperConfig, null); + + /** + * Convenient constructor to use the default + * {@link DynamoDBMapper#DynamoDBMapper(AmazonDynamoDB)} + * + * @param amazonDynamoDB + * The AWS SDK instance to talk to DynamoDB + * @param dynamoDBMapperConfig + * The config to use + */ + public DynamoDBTemplate(AmazonDynamoDB amazonDynamoDB, DynamoDBMapperConfig dynamoDBMapperConfig) { + this(amazonDynamoDB, dynamoDBMapperConfig, null); + } + + /** + * Convenient constructor to use the {@link DynamoDBMapperConfig#DEFAULT} + * + * @param amazonDynamoDB + * The AWS SDK instance to talk to DynamoDB + * @param dynamoDBMapper + * The Mapper to use + */ + public DynamoDBTemplate(AmazonDynamoDB amazonDynamoDB, DynamoDBMapper dynamoDBMapper) { + this(amazonDynamoDB, null, dynamoDBMapper); + } + + /** + * Convenient construcotr to thse the {@link DynamoDBMapperConfig#DEFAULT} and + * default {@link DynamoDBMapper#DynamoDBMapper(AmazonDynamoDB)} + * + * @param amazonDynamoDB + * The AWS SDK instance to talk to DynamoDB + */ + public DynamoDBTemplate(AmazonDynamoDB amazonDynamoDB) { + this(amazonDynamoDB, null, null); } - - /** Convenient constructor to use the {@link DynamoDBMapperConfig#DEFAULT} - * @param amazonDynamoDB The AWS SDK instance to talk to DynamoDB - * @param dynamoDBMapper The Mapper to use - * */ - public DynamoDBTemplate(AmazonDynamoDB amazonDynamoDB, DynamoDBMapper dynamoDBMapper) - { - this(amazonDynamoDB, null, dynamoDBMapper); - } - - /** Convenient construcotr to thse the {@link DynamoDBMapperConfig#DEFAULT} and default {@link DynamoDBMapper#DynamoDBMapper(AmazonDynamoDB)} - * @param amazonDynamoDB The AWS SDK instance to talk to DynamoDB - * */ - public DynamoDBTemplate(AmazonDynamoDB amazonDynamoDB) - { - this(amazonDynamoDB, null, null); - } - - /** Initializes a new {@code DynamoDBTemplate}. - * The following combinations are valid: - * @param amazonDynamoDB must not be {@code null} - * @param dynamoDBMapperConfig can be {@code null} - {@link DynamoDBMapperConfig#DEFAULT} is used if {@code null} is passed in - * @param dynamoDBMapper can be {@code null} - {@link DynamoDBMapper#DynamoDBMapper(AmazonDynamoDB, DynamoDBMapperConfig)} is used if {@code null} is passed in */ - public DynamoDBTemplate(AmazonDynamoDB amazonDynamoDB, DynamoDBMapperConfig dynamoDBMapperConfig, DynamoDBMapper dynamoDBMapper) { + + /** + * Initializes a new {@code DynamoDBTemplate}. The following combinations are + * valid: + * + * @param amazonDynamoDB + * must not be {@code null} + * @param dynamoDBMapperConfig + * can be {@code null} - {@link DynamoDBMapperConfig#DEFAULT} is used + * if {@code null} is passed in + * @param dynamoDBMapper + * can be {@code null} - + * {@link DynamoDBMapper#DynamoDBMapper(AmazonDynamoDB, DynamoDBMapperConfig)} + * is used if {@code null} is passed in + */ + public DynamoDBTemplate(AmazonDynamoDB amazonDynamoDB, DynamoDBMapperConfig dynamoDBMapperConfig, + DynamoDBMapper dynamoDBMapper) { Assert.notNull(amazonDynamoDB, "amazonDynamoDB must not be null!"); this.amazonDynamoDB = amazonDynamoDB; @@ -99,18 +119,22 @@ public DynamoDBTemplate(AmazonDynamoDB amazonDynamoDB, DynamoDBMapperConfig dyna // Trying to fix half-initialized DynamoDBMapperConfigs here. // The old documentation advised to start with an empty builder. Therefore we // try here to set required fields to their defaults - - // As the documentation at https://github.com/derjust/spring-data-dynamodb/wiki/Alter-table-name-during-runtime (same as https://git.io/DynamoDBMapperConfig) + // As the documentation at + // https://github.com/derjust/spring-data-dynamodb/wiki/Alter-table-name-during-runtime + // (same as https://git.io/DynamoDBMapperConfig) // now does: Start with #DEFAULT and add what's required DynamoDBMapperConfig.Builder emptyBuilder = DynamoDBMapperConfig.builder(); // empty (!) builder if (dynamoDBMapperConfig.getConversionSchema() == null) { - LOGGER.warn("No ConversionSchema set in the provided dynamoDBMapperConfig! Merging with DynamoDBMapperConfig.DEFAULT - Please see https://git.io/DynamoDBMapperConfig"); - // DynamoDBMapperConfig#DEFAULT comes with a ConversionSchema + LOGGER.warn( + "No ConversionSchema set in the provided dynamoDBMapperConfig! Merging with DynamoDBMapperConfig.DEFAULT - Please see https://git.io/DynamoDBMapperConfig"); + // DynamoDBMapperConfig#DEFAULT comes with a ConversionSchema emptyBuilder.withConversionSchema(DynamoDBMapperConfig.DEFAULT.getConversionSchema()); } if (dynamoDBMapperConfig.getTypeConverterFactory() == null) { - LOGGER.warn("No TypeConverterFactory set in the provided dynamoDBMapperConfig! Merging with DynamoDBMapperConfig.DEFAULT - Please see https://git.io/DynamoDBMapperConfig"); + LOGGER.warn( + "No TypeConverterFactory set in the provided dynamoDBMapperConfig! Merging with DynamoDBMapperConfig.DEFAULT - Please see https://git.io/DynamoDBMapperConfig"); // DynamoDBMapperConfig#DEFAULT comes with a TypeConverterFactory emptyBuilder.withTypeConverterFactory(DynamoDBMapperConfig.DEFAULT.getTypeConverterFactory()); } @@ -124,37 +148,33 @@ public DynamoDBTemplate(AmazonDynamoDB amazonDynamoDB, DynamoDBMapperConfig dyna } else { this.dynamoDBMapper = dynamoDBMapper; } - } - + } + @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.eventPublisher = applicationContext; } - + @Override - public int count(Class domainClass, - DynamoDBQueryExpression queryExpression) { + public int count(Class domainClass, DynamoDBQueryExpression queryExpression) { return dynamoDBMapper.count(domainClass, queryExpression); } @Override - public PaginatedQueryList query(Class domainClass, - DynamoDBQueryExpression queryExpression) { + public PaginatedQueryList query(Class domainClass, DynamoDBQueryExpression queryExpression) { PaginatedQueryList results = dynamoDBMapper.query(domainClass, queryExpression); maybeEmitEvent(results, AfterQueryEvent::new); return results; } @Override - public int count(Class domainClass, - DynamoDBScanExpression scanExpression) { + public int count(Class domainClass, DynamoDBScanExpression scanExpression) { return dynamoDBMapper.count(domainClass, scanExpression); } @Override public T load(Class domainClass, Object hashKey, Object rangeKey) { - T entity = dynamoDBMapper.load(domainClass, hashKey,rangeKey); + T entity = dynamoDBMapper.load(domainClass, hashKey, rangeKey); maybeEmitEvent(entity, AfterLoadEvent::new); return entity; @@ -162,15 +182,14 @@ public T load(Class domainClass, Object hashKey, Object rangeKey) { @Override public T load(Class domainClass, Object hashKey) { - T entity = dynamoDBMapper.load(domainClass, hashKey); + T entity = dynamoDBMapper.load(domainClass, hashKey); maybeEmitEvent(entity, AfterLoadEvent::new); return entity; } @Override - public PaginatedScanList scan(Class domainClass, - DynamoDBScanExpression scanExpression) { + public PaginatedScanList scan(Class domainClass, DynamoDBScanExpression scanExpression) { PaginatedScanList results = dynamoDBMapper.scan(domainClass, scanExpression); maybeEmitEvent(results, AfterScanEvent::new); return results; @@ -178,11 +197,9 @@ public PaginatedScanList scan(Class domainClass, @Override public Map> batchLoad(Map, List> itemsToGet) { - Map> results = dynamoDBMapper.batchLoad(itemsToGet); - for (List resultList : results.values()) - { - for (Object entity : resultList) - { + Map> results = dynamoDBMapper.batchLoad(itemsToGet); + for (List resultList : results.values()) { + for (Object entity : resultList) { maybeEmitEvent(entity, AfterLoadEvent::new); } } @@ -197,7 +214,7 @@ public T save(T entity) { return entity; } - + @Override public List batchSave(Iterable entities) { entities.forEach(it -> maybeEmitEvent(it, BeforeSaveEvent::new)); @@ -205,8 +222,8 @@ public List batchSave(Iterable entities) { List result = dynamoDBMapper.batchSave(entities); entities.forEach(it -> maybeEmitEvent(it, AfterSaveEvent::new)); - return result; - } + return result; + } @Override public T delete(T entity) { @@ -215,20 +232,19 @@ public T delete(T entity) { maybeEmitEvent(entity, AfterDeleteEvent::new); return entity; } - + @Override public List batchDelete(Iterable entities) { entities.forEach(it -> maybeEmitEvent(it, BeforeDeleteEvent::new)); - List result = dynamoDBMapper.batchDelete(entities); + List result = dynamoDBMapper.batchDelete(entities); entities.forEach(it -> maybeEmitEvent(it, AfterDeleteEvent::new)); return result; } @Override - public PaginatedQueryList query(Class clazz, - QueryRequest queryRequest) { + public PaginatedQueryList query(Class clazz, QueryRequest queryRequest) { QueryResult queryResult = amazonDynamoDB.query(queryRequest); return new PaginatedQueryList(dynamoDBMapper, clazz, amazonDynamoDB, queryRequest, queryResult, dynamoDBMapperConfig.getPaginationLoadingStrategy(), dynamoDBMapperConfig); @@ -238,16 +254,16 @@ public PaginatedQueryList query(Class clazz, public int count(Class clazz, QueryRequest mutableQueryRequest) { mutableQueryRequest.setSelect(Select.COUNT); - // Count queries can also be truncated for large datasets - int count = 0; - QueryResult queryResult = null; - do { - queryResult = amazonDynamoDB.query(mutableQueryRequest); - count += queryResult.getCount(); - mutableQueryRequest.setExclusiveStartKey(queryResult.getLastEvaluatedKey()); - } while (queryResult.getLastEvaluatedKey() != null); + // Count queries can also be truncated for large datasets + int count = 0; + QueryResult queryResult = null; + do { + queryResult = amazonDynamoDB.query(mutableQueryRequest); + count += queryResult.getCount(); + mutableQueryRequest.setExclusiveStartKey(queryResult.getLastEvaluatedKey()); + } while (queryResult.getLastEvaluatedKey() != null); - return count; + return count; } @Override @@ -259,23 +275,23 @@ public String getOverriddenTableName(Class domainClass, String tableName) tableName = dynamoDBMapperConfig.getTableNameOverride().getTableNamePrefix() + tableName; } } else if (dynamoDBMapperConfig.getTableNameResolver() != null) { - tableName = dynamoDBMapperConfig.getTableNameResolver().getTableName(domainClass, dynamoDBMapperConfig); + tableName = dynamoDBMapperConfig.getTableNameResolver().getTableName(domainClass, dynamoDBMapperConfig); } return tableName; } - /** - * {@inheritDoc} - */ - @Override - public DynamoDBMapperTableModel getTableModel(Class domainClass) { - return dynamoDBMapper.getTableModel(domainClass, dynamoDBMapperConfig); - } - - protected void maybeEmitEvent(@Nullable T source, Function> factory) { - if (eventPublisher != null) { - if (source != null) { + /** + * {@inheritDoc} + */ + @Override + public DynamoDBMapperTableModel getTableModel(Class domainClass) { + return dynamoDBMapper.getTableModel(domainClass, dynamoDBMapperConfig); + } + + protected void maybeEmitEvent(@Nullable T source, Function> factory) { + if (eventPublisher != null) { + if (source != null) { DynamoDBMappingEvent event = factory.apply(source); eventPublisher.publishEvent(event); diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/AbstractDynamoDBDateMarshaller.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/AbstractDynamoDBDateMarshaller.java index 60d85f09..320680e0 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/AbstractDynamoDBDateMarshaller.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/AbstractDynamoDBDateMarshaller.java @@ -24,9 +24,13 @@ /** * @author Michael Lavelle * @author Sebastian Just - * @deprecated According to {@code com.amazonaws.services.dynamodbv2.datamodeling.marshallers.CustomMarshaller.marshall(Object)} - * at some point {@link DynamoDBMarshaller} might be cached - whereas {@link DateFormat} is not thread-safe.
- * Use {@link org.socialsignin.spring.data.dynamodb.marshaller.DateDynamoDBMarshaller} instead. + * @deprecated According to + * {@code com.amazonaws.services.dynamodbv2.datamodeling.marshallers.CustomMarshaller.marshall(Object)} + * at some point {@link DynamoDBMarshaller} might be cached - + * whereas {@link DateFormat} is not thread-safe.
+ * Use + * {@link org.socialsignin.spring.data.dynamodb.marshaller.DateDynamoDBMarshaller} + * instead. * @see org.socialsignin.spring.data.dynamodb.marshaller.DateDynamoDBMarshaller */ @Deprecated diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DefaultDynamoDBDateMarshaller.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DefaultDynamoDBDateMarshaller.java index 5d79e9bb..bc885dd2 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DefaultDynamoDBDateMarshaller.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DefaultDynamoDBDateMarshaller.java @@ -21,7 +21,8 @@ /** * @author Michael Lavelle * @author Sebastian Just - * @deprecated Consider using {@link org.socialsignin.spring.data.dynamodb.marshaller.Date2IsoDynamoDBMarshaller} + * @deprecated Consider using + * {@link org.socialsignin.spring.data.dynamodb.marshaller.Date2IsoDynamoDBMarshaller} */ @Deprecated public class DefaultDynamoDBDateMarshaller extends AbstractDynamoDBDateMarshaller { diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBMappingContext.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBMappingContext.java index 06eb07cc..446feff1 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBMappingContext.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBMappingContext.java @@ -27,14 +27,17 @@ import java.lang.reflect.Method; /** - * Default implementation of a {@link org.springframework.data.mapping.context.MappingContext} for DynamoDB using - * {@link DynamoDBPersistentEntityImpl} and {@link DynamoDBPersistentProperty} - * as primary abstractions. + * Default implementation of a + * {@link org.springframework.data.mapping.context.MappingContext} for DynamoDB + * using {@link DynamoDBPersistentEntityImpl} and + * {@link DynamoDBPersistentProperty} as primary abstractions. * * @author Michael Lavelle * @author Sebastian Just */ -public class DynamoDBMappingContext extends AbstractMappingContext, DynamoDBPersistentProperty> { +public class DynamoDBMappingContext + extends + AbstractMappingContext, DynamoDBPersistentProperty> { /* * (non-Javadoc) * @@ -59,8 +62,7 @@ protected DynamoDBPersistentEntityImpl createPersistentEntity(TypeInforma */ @Override protected DynamoDBPersistentProperty createPersistentProperty(Property property, - DynamoDBPersistentEntityImpl owner, - SimpleTypeHolder simpleTypeHolder) { + DynamoDBPersistentEntityImpl owner, SimpleTypeHolder simpleTypeHolder) { return new DynamoDBPersistentPropertyImpl(property, owner, simpleTypeHolder); } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentEntityImpl.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentEntityImpl.java index 11385d1f..3351d900 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentEntityImpl.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentEntityImpl.java @@ -27,22 +27,25 @@ * @author Michael Lavelle * @author Sebastian Just */ -public class DynamoDBPersistentEntityImpl extends BasicPersistentEntity implements - DynamoDBPersistentEntity { - public DynamoDBPersistentEntityImpl(TypeInformation information, Comparator comparator) { +public class DynamoDBPersistentEntityImpl extends BasicPersistentEntity + implements + DynamoDBPersistentEntity { + public DynamoDBPersistentEntityImpl(TypeInformation information, + Comparator comparator) { super(information, comparator); } /** - * Returns the given property if it is a better candidate for the id - * property than the current id property. + * Returns the given property if it is a better candidate for the id property + * than the current id property. * * @param property * the new id property candidate, will never be {@literal null}. - * @return the given id property or {@literal null} if the given property is - * not an id property. + * @return the given id property or {@literal null} if the given property is not + * an id property. */ - protected DynamoDBPersistentProperty returnPropertyIfBetterIdPropertyCandidateOrNull(DynamoDBPersistentProperty property) { + protected DynamoDBPersistentProperty returnPropertyIfBetterIdPropertyCandidateOrNull( + DynamoDBPersistentProperty property) { if (!property.isIdProperty()) { return null; @@ -56,8 +59,10 @@ protected DynamoDBPersistentProperty returnPropertyIfBetterIdPropertyCandidateOr } else if (getIdProperty().isHashKeyProperty() && property.isCompositeIdProperty()) { return property; } else { - throw new MappingException(String.format("Attempt to add id property %s but already have property %s registered " - + "as id. Check your mapping configuration!", property.getField(), getIdProperty().getField())); + throw new MappingException(String.format( + "Attempt to add id property %s but already have property %s registered " + + "as id. Check your mapping configuration!", + property.getField(), getIdProperty().getField())); } } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentPropertyImpl.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentPropertyImpl.java index f0412fd6..55b88874 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentPropertyImpl.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentPropertyImpl.java @@ -38,8 +38,9 @@ * @author Michael Lavelle * @author Sebastian Just */ -class DynamoDBPersistentPropertyImpl extends AnnotationBasedPersistentProperty implements - DynamoDBPersistentProperty { +class DynamoDBPersistentPropertyImpl extends AnnotationBasedPersistentProperty + implements + DynamoDBPersistentProperty { private static final Collection> ASSOCIATION_ANNOTATIONS; private static final Collection> ID_ANNOTATIONS; @@ -68,7 +69,8 @@ class DynamoDBPersistentPropertyImpl extends AnnotationBasedPersistentProperty owner, SimpleTypeHolder simpleTypeHolder) { + public DynamoDBPersistentPropertyImpl(Property property, DynamoDBPersistentEntityImpl owner, + SimpleTypeHolder simpleTypeHolder) { super(property, owner, simpleTypeHolder); } @@ -77,7 +79,6 @@ public boolean isWritable() { return !isAnnotationPresent(DynamoDBIgnore.class); } - public boolean isHashKeyProperty() { return isAnnotationPresent(DynamoDBHashKey.class); } @@ -89,8 +90,7 @@ public boolean isCompositeIdProperty() { /* * (non-Javadoc) * - * @see - * org.springframework.data.mapping.model.AnnotationBasedPersistentProperty + * @see org.springframework.data.mapping.model.AnnotationBasedPersistentProperty * #isIdProperty() */ @Override @@ -109,8 +109,7 @@ public boolean isIdProperty() { * (non-Javadoc) * * @see - * org.springframework.data.mapping.model.AbstractPersistentProperty#isEntity - * () + * org.springframework.data.mapping.model.AbstractPersistentProperty#isEntity () */ // @Override @@ -129,8 +128,7 @@ public boolean isEntity() { /* * (non-Javadoc) * - * @see - * org.springframework.data.mapping.model.AnnotationBasedPersistentProperty + * @see org.springframework.data.mapping.model.AnnotationBasedPersistentProperty * #isAssociation() */ @Override @@ -151,8 +149,7 @@ public boolean isAssociation() { /* * (non-Javadoc) * - * @see - * org.springframework.data.mapping.model.AnnotationBasedPersistentProperty + * @see org.springframework.data.mapping.model.AnnotationBasedPersistentProperty * #isTransient() */ @Override diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AbstractDynamoDBEventListener.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AbstractDynamoDBEventListener.java index f879b0bd..7873d5d6 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AbstractDynamoDBEventListener.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AbstractDynamoDBEventListener.java @@ -47,19 +47,17 @@ * @author Michael Lavelle * @author Sebastian Just */ -public abstract class AbstractDynamoDBEventListener implements - ApplicationListener> { +public abstract class AbstractDynamoDBEventListener implements ApplicationListener> { - private static final Logger LOG = LoggerFactory - .getLogger(AbstractDynamoDBEventListener.class); + private static final Logger LOG = LoggerFactory.getLogger(AbstractDynamoDBEventListener.class); private final Class domainClass; /** * Creates a new {@link AbstractDynamoDBEventListener}. */ public AbstractDynamoDBEventListener() { - Class typeArgument = GenericTypeResolver.resolveTypeArgument( - this.getClass(), AbstractDynamoDBEventListener.class); + Class typeArgument = GenericTypeResolver.resolveTypeArgument(this.getClass(), + AbstractDynamoDBEventListener.class); this.domainClass = typeArgument == null ? Object.class : typeArgument; } @@ -70,26 +68,26 @@ protected Class getDomainClass() { /* * (non-Javadoc) * - * @see - * org.springframework.context.ApplicationListener#onApplicationEvent(org + * @see org.springframework.context.ApplicationListener#onApplicationEvent(org * .springframework.context.ApplicationEvent) */ @Override - public void onApplicationEvent(DynamoDBMappingEvent event) { + public void onApplicationEvent(DynamoDBMappingEvent event) { @SuppressWarnings("unchecked") E source = (E) event.getSource(); - // source can not be null as java.util.EventObject can not be constructed with null + // source can not be null as java.util.EventObject can not be constructed with + // null assert source != null; if (event instanceof AfterScanEvent) { - publishEachElement((PaginatedScanList)source, this::onAfterScan); + publishEachElement((PaginatedScanList) source, this::onAfterScan); return; } else if (event instanceof AfterQueryEvent) { - publishEachElement((PaginatedQueryList)source, this::onAfterQuery); + publishEachElement((PaginatedQueryList) source, this::onAfterQuery); return; } // Check for matching domain type and invoke callbacks @@ -117,10 +115,7 @@ else if (domainClass.isAssignableFrom(source.getClass())) { @SuppressWarnings("unchecked") private void publishEachElement(List list, Consumer publishMethod) { - list.stream() - .filter(o -> domainClass.isAssignableFrom(o.getClass())) - .map(o -> (E)o) - .forEach(publishMethod); + list.stream().filter(o -> domainClass.isAssignableFrom(o.getClass())).map(o -> (E) o).forEach(publishMethod); } public void onBeforeSave(E source) { diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterDeleteEvent.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterDeleteEvent.java index 4a053e98..6758f744 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterDeleteEvent.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterDeleteEvent.java @@ -15,7 +15,6 @@ */ package org.socialsignin.spring.data.dynamodb.mapping.event; - /** * @author Michael Lavelle * @author Sebastian Just diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterLoadEvent.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterLoadEvent.java index 0160b87f..34d714a4 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterLoadEvent.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterLoadEvent.java @@ -15,7 +15,6 @@ */ package org.socialsignin.spring.data.dynamodb.mapping.event; - /** * @author Michael Lavelle * @author Sebastian Just diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterQueryEvent.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterQueryEvent.java index 810e7162..e59502af 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterQueryEvent.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterQueryEvent.java @@ -17,7 +17,6 @@ import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedQueryList; - /** * @author Michael Lavelle * @author Sebastian Just diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterSaveEvent.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterSaveEvent.java index e7e6caf8..0c14fc61 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterSaveEvent.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterSaveEvent.java @@ -15,7 +15,6 @@ */ package org.socialsignin.spring.data.dynamodb.mapping.event; - /** * @author Michael Lavelle * @author Sebastian Just diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterScanEvent.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterScanEvent.java index 11ef4180..03acbe56 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterScanEvent.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AfterScanEvent.java @@ -17,7 +17,6 @@ import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedScanList; - /** * @author Michael Lavelle * @author Sebastian Just diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AuditingEventListener.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AuditingEventListener.java index 574915ae..a1f946f2 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AuditingEventListener.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/AuditingEventListener.java @@ -20,27 +20,31 @@ import org.springframework.util.Assert; /** - * Event listener to populate auditing related fields on an entity about to be saved. + * Event listener to populate auditing related fields on an entity about to be + * saved. * * @author Vito Limandibhrata */ public class AuditingEventListener extends AbstractDynamoDBEventListener { - private final ObjectFactory auditingHandlerFactory; + private final ObjectFactory auditingHandlerFactory; - /** - * Creates a new {@link AuditingEventListener} using the given {@link org.springframework.data.mapping.context.MappingContext} and {@link org.springframework.data.auditing.AuditingHandler} - * provided by the given {@link ObjectFactory}. - * - * @param auditingHandlerFactory must not be {@literal null}. - */ - public AuditingEventListener(ObjectFactory auditingHandlerFactory) { - Assert.notNull(auditingHandlerFactory, "IsNewAwareAuditingHandler must not be null!"); - this.auditingHandlerFactory = auditingHandlerFactory; - } + /** + * Creates a new {@link AuditingEventListener} using the given + * {@link org.springframework.data.mapping.context.MappingContext} and + * {@link org.springframework.data.auditing.AuditingHandler} provided by the + * given {@link ObjectFactory}. + * + * @param auditingHandlerFactory + * must not be {@literal null}. + */ + public AuditingEventListener(ObjectFactory auditingHandlerFactory) { + Assert.notNull(auditingHandlerFactory, "IsNewAwareAuditingHandler must not be null!"); + this.auditingHandlerFactory = auditingHandlerFactory; + } - @Override - public void onBeforeSave(Object source) { - auditingHandlerFactory.getObject().markAudited(source); - } + @Override + public void onBeforeSave(Object source) { + auditingHandlerFactory.getObject().markAudited(source); + } } \ No newline at end of file diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/BeforeDeleteEvent.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/BeforeDeleteEvent.java index af3022f4..5e790ee2 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/BeforeDeleteEvent.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/BeforeDeleteEvent.java @@ -15,7 +15,6 @@ */ package org.socialsignin.spring.data.dynamodb.mapping.event; - /** * @author Michael Lavelle * @author Sebastian Just diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/BeforeSaveEvent.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/BeforeSaveEvent.java index d6e1cf79..9eba570c 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/BeforeSaveEvent.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/BeforeSaveEvent.java @@ -15,7 +15,6 @@ */ package org.socialsignin.spring.data.dynamodb.mapping.event; - /** * @author Michael Lavelle * @author Sebastian Just diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/DynamoDBMappingEvent.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/DynamoDBMappingEvent.java index 54c0fc19..1c13ca3e 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/DynamoDBMappingEvent.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/DynamoDBMappingEvent.java @@ -29,7 +29,7 @@ public DynamoDBMappingEvent(T source) { super(source); } - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({"unchecked"}) @Override public T getSource() { return (T) super.getSource(); diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/LoggingEventListener.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/LoggingEventListener.java index 13ddf1cc..35a9c07f 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/LoggingEventListener.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/LoggingEventListener.java @@ -31,13 +31,12 @@ * limitations under the License. */ - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** - * {@link org.springframework.context.ApplicationListener} for DynamoDB mapping events logging the events. + * {@link org.springframework.context.ApplicationListener} for DynamoDB mapping + * events logging the events. * * @author Michael Lavelle * @author Sebastian Just @@ -46,10 +45,11 @@ public class LoggingEventListener extends AbstractDynamoDBEventListener private static final Logger LOGGER = LoggerFactory.getLogger(LoggingEventListener.class); - /* * (non-Javadoc) - * @see org.socialsignin.spring.data.dynamodb.mapping.event.AbstractDynamoDBEventListener#onBeforeSave(java.lang.Object) + * + * @see org.socialsignin.spring.data.dynamodb.mapping.event. + * AbstractDynamoDBEventListener#onBeforeSave(java.lang.Object) */ @Override public void onBeforeSave(Object source) { @@ -58,7 +58,9 @@ public void onBeforeSave(Object source) { /* * (non-Javadoc) - * @see org.socialsignin.spring.data.dynamodb.mapping.event.AbstractDynamoDBEventListener#onAfterSave(java.lang.Object,) + * + * @see org.socialsignin.spring.data.dynamodb.mapping.event. + * AbstractDynamoDBEventListener#onAfterSave(java.lang.Object,) */ @Override public void onAfterSave(Object source) { @@ -67,7 +69,9 @@ public void onAfterSave(Object source) { /* * (non-Javadoc) - * @see org.socialsignin.spring.data.dynamodb.mapping.event.AbstractDynamoDBEventListener#onAfterDelete(java.lang.Object,) + * + * @see org.socialsignin.spring.data.dynamodb.mapping.event. + * AbstractDynamoDBEventListener#onAfterDelete(java.lang.Object,) */ @Override public void onAfterDelete(Object source) { @@ -76,7 +80,9 @@ public void onAfterDelete(Object source) { /* * (non-Javadoc) - * @see org.socialsignin.spring.data.dynamodb.mapping.event.AbstractDynamoDBEventListener#onBeforeDelete(java.lang.Object) + * + * @see org.socialsignin.spring.data.dynamodb.mapping.event. + * AbstractDynamoDBEventListener#onBeforeDelete(java.lang.Object) */ @Override public void onBeforeDelete(Object source) { @@ -85,7 +91,9 @@ public void onBeforeDelete(Object source) { /* * (non-Javadoc) - * @see org.socialsignin.spring.data.dynamodb.mapping.event.AbstractDynamoDBEventListener#onAfterLoad(java.lang.Object) + * + * @see org.socialsignin.spring.data.dynamodb.mapping.event. + * AbstractDynamoDBEventListener#onAfterLoad(java.lang.Object) */ @Override public void onAfterLoad(Object source) { @@ -94,7 +102,9 @@ public void onAfterLoad(Object source) { /* * (non-Javadoc) - * @see org.socialsignin.spring.data.dynamodb.mapping.event.AbstractDynamoDBEventListener#onAfterScan(java.lang.Object) + * + * @see org.socialsignin.spring.data.dynamodb.mapping.event. + * AbstractDynamoDBEventListener#onAfterScan(java.lang.Object) */ @Override public void onAfterScan(Object source) { @@ -103,7 +113,9 @@ public void onAfterScan(Object source) { /* * (non-Javadoc) - * @see org.socialsignin.spring.data.dynamodb.mapping.event.AbstractDynamoDBEventListener#onAfterQuery(java.lang.Object) + * + * @see org.socialsignin.spring.data.dynamodb.mapping.event. + * AbstractDynamoDBEventListener#onAfterQuery(java.lang.Object) */ @Override public void onAfterQuery(Object source) { diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/ValidatingDynamoDBEventListener.java b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/ValidatingDynamoDBEventListener.java index 2f6c22c8..d610a957 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/ValidatingDynamoDBEventListener.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/mapping/event/ValidatingDynamoDBEventListener.java @@ -42,10 +42,10 @@ import java.util.List; import java.util.Set; - /** - * javax.validation dependant entities validator. When it is registered as Spring component its automatically invoked - * before entities are saved in database. + * javax.validation dependant entities validator. When it is registered as + * Spring component its automatically invoked before entities are saved in + * database. * * @author Michael Lavelle * @author Sebastian Just @@ -57,9 +57,11 @@ public class ValidatingDynamoDBEventListener extends AbstractDynamoDBEventListen private final Validator validator; /** - * Creates a new {@link ValidatingDynamoDBEventListener} using the given {@link Validator}. + * Creates a new {@link ValidatingDynamoDBEventListener} using the given + * {@link Validator}. * - * @param validator must not be {@literal null}. + * @param validator + * must not be {@literal null}. */ public ValidatingDynamoDBEventListener(Validator validator) { Assert.notNull(validator, "validator must not be null!"); @@ -68,13 +70,15 @@ public ValidatingDynamoDBEventListener(Validator validator) { /* * (non-Javadoc) - * @see org.socialsignin.spring.data.dynamodb.mapping.event.AbstractDynamoDBEventListener#onBeforeSave(java.lang.Object) + * + * @see org.socialsignin.spring.data.dynamodb.mapping.event. + * AbstractDynamoDBEventListener#onBeforeSave(java.lang.Object) */ @Override public void onBeforeSave(Object source) { LOG.debug("Validating object: {}", source); - + List messages = new ArrayList<>(); Set> violations = validator.validate(source); if (!violations.isEmpty()) { diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2EpocheDynamoDBMarshaller.java b/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2EpocheDynamoDBMarshaller.java index 10fbd202..e8ed42a0 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2EpocheDynamoDBMarshaller.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2EpocheDynamoDBMarshaller.java @@ -26,8 +26,7 @@ private static final class EpcoheDateFormat extends DateFormat { private static final long serialVersionUID = 2969564523817434535L; @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, - FieldPosition fieldPosition) { + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { long epoche = date.getTime(); toAppendTo.append(epoche); return toAppendTo; @@ -39,7 +38,7 @@ public Date parse(String source, ParsePosition pos) { pos.setIndex(source.length()); return new Date(epoche); } - + }; @Override diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2EpocheDynamoDBMarshaller.java b/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2EpocheDynamoDBMarshaller.java index 72b93e91..b2859e0b 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2EpocheDynamoDBMarshaller.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2EpocheDynamoDBMarshaller.java @@ -21,7 +21,10 @@ import java.time.Instant; -public class Instant2EpocheDynamoDBMarshaller implements DynamoDBTypeConverter, DynamoDBMarshaller { +public class Instant2EpocheDynamoDBMarshaller + implements + DynamoDBTypeConverter, + DynamoDBMarshaller { @Override public String convert(Instant object) { diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2IsoDynamoDBMarshaller.java b/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2IsoDynamoDBMarshaller.java index f118f1f9..eb6a9b71 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2IsoDynamoDBMarshaller.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2IsoDynamoDBMarshaller.java @@ -23,13 +23,15 @@ import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; -public class Instant2IsoDynamoDBMarshaller implements DynamoDBTypeConverter, DynamoDBMarshaller { +public class Instant2IsoDynamoDBMarshaller + implements + DynamoDBTypeConverter, + DynamoDBMarshaller { private static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; private DateTimeFormatter getDateFormat() { - return DateTimeFormatter.ofPattern(PATTERN) - .withZone(ZoneOffset.UTC); + return DateTimeFormatter.ofPattern(PATTERN).withZone(ZoneOffset.UTC); } @Override diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractMultipleEntityQuery.java b/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractMultipleEntityQuery.java index e21a7b7c..2b8ec4a8 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractMultipleEntityQuery.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractMultipleEntityQuery.java @@ -35,11 +35,12 @@ public AbstractMultipleEntityQuery(DynamoDBOperations dynamoDBOperations, Class< public T getSingleResult() { List results = getResultList(); if (results.size() > 1) { - throw new IncorrectResultSizeDataAccessException("result returns more than one elements", 1, results.size()); + throw new IncorrectResultSizeDataAccessException("result returns more than one elements", 1, + results.size()); } if (results.size() == 0) { - // return null here as Spring will convert that to Optional if nessassary - // https://jira.spring.io/browse/DATACMNS-483 + // return null here as Spring will convert that to Optional if nessassary + // https://jira.spring.io/browse/DATACMNS-483 return null; } else { return results.get(0); diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractQuery.java b/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractQuery.java index ed6b3826..a54209bc 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractQuery.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractQuery.java @@ -18,7 +18,8 @@ import org.socialsignin.spring.data.dynamodb.core.DynamoDBOperations; /** - * {@link org.socialsignin.spring.data.dynamodb.mapping.DynamoDBPersistentProperty} implementation + * {@link org.socialsignin.spring.data.dynamodb.mapping.DynamoDBPersistentProperty} + * implementation * * @author Michael Lavelle * @author Sebastian Just @@ -30,19 +31,17 @@ public abstract class AbstractQuery implements Query { protected boolean scanEnabled = false; protected boolean scanCountEnabled = false; - - public boolean isScanCountEnabled() { return scanCountEnabled; } @Override - public void setScanCountEnabled(boolean scanCountEnabled) { + public void setScanCountEnabled(boolean scanCountEnabled) { this.scanCountEnabled = scanCountEnabled; } @Override - public void setScanEnabled(boolean scanEnabled) { + public void setScanEnabled(boolean scanEnabled) { this.scanEnabled = scanEnabled; } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractSingleEntityQuery.java b/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractSingleEntityQuery.java index 93480f80..08310e7e 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractSingleEntityQuery.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/query/AbstractSingleEntityQuery.java @@ -23,7 +23,7 @@ public abstract class AbstractSingleEntityQuery extends AbstractQuery implements Query { public AbstractSingleEntityQuery(DynamoDBOperations dynamoDBOperations, Class clazz) { - super(dynamoDBOperations,clazz); + super(dynamoDBOperations, clazz); } @Override diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/query/CountByHashAndRangeKeyQuery.java b/src/main/java/org/socialsignin/spring/data/dynamodb/query/CountByHashAndRangeKeyQuery.java index d716e78f..a7743d92 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/query/CountByHashAndRangeKeyQuery.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/query/CountByHashAndRangeKeyQuery.java @@ -27,7 +27,8 @@ public class CountByHashAndRangeKeyQuery extends AbstractSingleEntityQuery entityClass; - public CountByHashAndRangeKeyQuery(DynamoDBOperations dynamoDBOperations, Class clazz, Object hashKey, Object rangeKey) { + public CountByHashAndRangeKeyQuery(DynamoDBOperations dynamoDBOperations, Class clazz, Object hashKey, + Object rangeKey) { super(dynamoDBOperations, Long.class); this.hashKey = hashKey; this.rangeKey = rangeKey; diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/query/MultipleEntityQueryRequestQuery.java b/src/main/java/org/socialsignin/spring/data/dynamodb/query/MultipleEntityQueryRequestQuery.java index 89cca4ea..8b12e7c9 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/query/MultipleEntityQueryRequestQuery.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/query/MultipleEntityQueryRequestQuery.java @@ -24,17 +24,18 @@ public class MultipleEntityQueryRequestQuery extends AbstractMultipleEntityQu private DynamoDBOperations dynamoDBOperations; private QueryRequest queryRequest; - - public MultipleEntityQueryRequestQuery(DynamoDBOperations dynamoDBOperations,Class clazz,QueryRequest queryRequest) { + + public MultipleEntityQueryRequestQuery(DynamoDBOperations dynamoDBOperations, Class clazz, + QueryRequest queryRequest) { super(null, clazz); this.queryRequest = queryRequest; this.dynamoDBOperations = dynamoDBOperations; } - + @Override public List getResultList() { - return dynamoDBOperations.query(clazz, queryRequest); + return dynamoDBOperations.query(clazz, queryRequest); } } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/query/MultipleEntityScanExpressionQuery.java b/src/main/java/org/socialsignin/spring/data/dynamodb/query/MultipleEntityScanExpressionQuery.java index 8ba75bcc..c42805fd 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/query/MultipleEntityScanExpressionQuery.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/query/MultipleEntityScanExpressionQuery.java @@ -24,8 +24,9 @@ public class MultipleEntityScanExpressionQuery extends AbstractMultipleEntityQuery { private DynamoDBScanExpression scanExpression; - - public MultipleEntityScanExpressionQuery(DynamoDBOperations dynamoDBOperations, Class clazz,DynamoDBScanExpression scanExpression) { + + public MultipleEntityScanExpressionQuery(DynamoDBOperations dynamoDBOperations, Class clazz, + DynamoDBScanExpression scanExpression) { super(dynamoDBOperations, clazz); this.scanExpression = scanExpression; } @@ -33,14 +34,13 @@ public MultipleEntityScanExpressionQuery(DynamoDBOperations dynamoDBOperations, @Override public List getResultList() { assertScanEnabled(isScanEnabled()); - return dynamoDBOperations.scan(clazz,scanExpression); + return dynamoDBOperations.scan(clazz, scanExpression); } - - public void assertScanEnabled(boolean scanEnabled) - { - Assert.isTrue(scanEnabled,"Scanning for this query is not enabled. " + - "To enable annotate your repository method with @EnableScan, or " + - "enable scanning for all repository methods by annotating your repository interface with @EnableScan"); + + public void assertScanEnabled(boolean scanEnabled) { + Assert.isTrue(scanEnabled, "Scanning for this query is not enabled. " + + "To enable annotate your repository method with @EnableScan, or " + + "enable scanning for all repository methods by annotating your repository interface with @EnableScan"); } } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/query/Query.java b/src/main/java/org/socialsignin/spring/data/dynamodb/query/Query.java index 2ee5ec37..40296c8c 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/query/Query.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/query/Query.java @@ -17,27 +17,26 @@ import java.util.List; - - public interface Query { /** - * Execute a SELECT query and return the query results - * as a List. - * @return a list of the results - * @throws IllegalStateException if called for a Java - * Persistence query language UPDATE or DELETE statement - */ - List getResultList(); - - /** - * Execute a SELECT query that returns a single result. - * @return the result - */ - T getSingleResult(); + * Execute a SELECT query and return the query results as a List. + * + * @return a list of the results + * @throws IllegalStateException + * if called for a Java Persistence query language UPDATE or DELETE + * statement + */ + List getResultList(); - - void setScanEnabled(boolean scanEnabled); - void setScanCountEnabled(boolean scanCountEnabled); + /** + * Execute a SELECT query that returns a single result. + * + * @return the result + */ + T getSingleResult(); + + void setScanEnabled(boolean scanEnabled); + void setScanCountEnabled(boolean scanCountEnabled); } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/query/QueryRequestCountQuery.java b/src/main/java/org/socialsignin/spring/data/dynamodb/query/QueryRequestCountQuery.java index 2f4fb040..f7802974 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/query/QueryRequestCountQuery.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/query/QueryRequestCountQuery.java @@ -22,13 +22,13 @@ public class QueryRequestCountQuery extends AbstractSingleEntityQuery { private final DynamoDBOperations dynamoDBOperations; private final QueryRequest queryRequest; - + public QueryRequestCountQuery(DynamoDBOperations dynamoDBOperations, QueryRequest queryRequest) { super(null, Long.class); this.queryRequest = queryRequest; this.dynamoDBOperations = dynamoDBOperations; } - + @Override public Long getSingleResult() { diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/query/ScanExpressionCountQuery.java b/src/main/java/org/socialsignin/spring/data/dynamodb/query/ScanExpressionCountQuery.java index 8c4565df..af9a4519 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/query/ScanExpressionCountQuery.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/query/ScanExpressionCountQuery.java @@ -19,15 +19,16 @@ import org.socialsignin.spring.data.dynamodb.core.DynamoDBOperations; import org.springframework.util.Assert; -public class ScanExpressionCountQuery extends AbstractSingleEntityQuery implements Query{ +public class ScanExpressionCountQuery extends AbstractSingleEntityQuery implements Query { private DynamoDBScanExpression scanExpression; - + private Class domainClass; - + private boolean pageQuery; - - public ScanExpressionCountQuery(DynamoDBOperations dynamoDBOperations, Class clazz,DynamoDBScanExpression scanExpression,boolean pageQuery) { + + public ScanExpressionCountQuery(DynamoDBOperations dynamoDBOperations, Class clazz, + DynamoDBScanExpression scanExpression, boolean pageQuery) { super(dynamoDBOperations, Long.class); this.scanExpression = scanExpression; this.domainClass = clazz; @@ -37,23 +38,19 @@ public ScanExpressionCountQuery(DynamoDBOperations dynamoDBOperations, Class @Override public Long getSingleResult() { assertScanCountEnabled(isScanCountEnabled()); - return Long.valueOf(dynamoDBOperations.count(domainClass,scanExpression)); + return Long.valueOf(dynamoDBOperations.count(domainClass, scanExpression)); } - - public void assertScanCountEnabled(boolean scanCountEnabled) - { - if (pageQuery) - { - Assert.isTrue(scanCountEnabled,"Scanning for the total counts for this query is not enabled. " + - "To enable annotate your repository method with @EnableScanCount, or " + - "enable scanning for all repository methods by annotating your repository interface with @EnableScanCount. This total count is required to serve this Page query - if total counts are not desired an alternative approach could be to replace the Page query with a Slice query "); - - } - else - { - Assert.isTrue(scanCountEnabled,"Scanning for counts for this query is not enabled. " + - "To enable annotate your repository method with @EnableScanCount, or " + - "enable scanning for all repository methods by annotating your repository interface with @EnableScanCount"); + + public void assertScanCountEnabled(boolean scanCountEnabled) { + if (pageQuery) { + Assert.isTrue(scanCountEnabled, "Scanning for the total counts for this query is not enabled. " + + "To enable annotate your repository method with @EnableScanCount, or " + + "enable scanning for all repository methods by annotating your repository interface with @EnableScanCount. This total count is required to serve this Page query - if total counts are not desired an alternative approach could be to replace the Page query with a Slice query "); + + } else { + Assert.isTrue(scanCountEnabled, "Scanning for counts for this query is not enabled. " + + "To enable annotate your repository method with @EnableScanCount, or " + + "enable scanning for all repository methods by annotating your repository interface with @EnableScanCount"); } } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/query/SingleEntityLoadByHashAndRangeKeyQuery.java b/src/main/java/org/socialsignin/spring/data/dynamodb/query/SingleEntityLoadByHashAndRangeKeyQuery.java index 5815b805..7e17543d 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/query/SingleEntityLoadByHashAndRangeKeyQuery.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/query/SingleEntityLoadByHashAndRangeKeyQuery.java @@ -26,7 +26,8 @@ public class SingleEntityLoadByHashAndRangeKeyQuery extends AbstractSingleEnt private Object hashKey; private Object rangeKey; - public SingleEntityLoadByHashAndRangeKeyQuery(DynamoDBOperations dynamoDBOperations, Class clazz, Object hashKey, Object rangeKey) { + public SingleEntityLoadByHashAndRangeKeyQuery(DynamoDBOperations dynamoDBOperations, Class clazz, Object hashKey, + Object rangeKey) { super(dynamoDBOperations, clazz); this.hashKey = hashKey; this.rangeKey = rangeKey; diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/EnableScan.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/EnableScan.java index 8a714357..3fc76e51 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/EnableScan.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/EnableScan.java @@ -26,7 +26,7 @@ * @author Sebastian Just */ @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) +@Target({ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Documented public @interface EnableScan { diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/EnableScanCount.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/EnableScanCount.java index b7888b61..09a26321 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/EnableScanCount.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/EnableScanCount.java @@ -26,7 +26,7 @@ * @author Sebastian Just */ @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) +@Target({ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Documented public @interface EnableScanCount { diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/Query.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/Query.java index bce7d398..a34bc48c 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/Query.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/Query.java @@ -26,11 +26,14 @@ @Documented public @interface Query { - /** - * A string that identifies the attributes you want. To retrieve a single attribute, specify its name. - * For multiple attributes, the names must be comma-separated. - * - * @see Projection Expressions - */ - String fields() default ""; + /** + * A string that identifies the attributes you want. To retrieve a single + * attribute, specify its name. For multiple attributes, the names must be + * comma-separated. + * + * @see Projection + * Expressions + */ + String fields() default ""; } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryBean.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryBean.java index a040cb12..ee3a0639 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryBean.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryBean.java @@ -41,7 +41,7 @@ class DynamoDBRepositoryBean extends CdiRepositoryBean { private final Bean amazonDynamoDBBean; private final Bean dynamoDBMapperConfigBean; - + private final Bean dynamoDBOperationsBean; /** @@ -59,18 +59,17 @@ class DynamoDBRepositoryBean extends CdiRepositoryBean { * must not be {@literal null}. */ DynamoDBRepositoryBean(BeanManager beanManager, Bean amazonDynamoDBBean, - Bean dynamoDBMapperConfigBean, Bean dynamoDBOperationsBean, - Set qualifiers, Class repositoryType) { + Bean dynamoDBMapperConfigBean, Bean dynamoDBOperationsBean, + Set qualifiers, Class repositoryType) { super(qualifiers, repositoryType, beanManager); - if (dynamoDBOperationsBean == null) - { + if (dynamoDBOperationsBean == null) { Assert.notNull(amazonDynamoDBBean, "amazonDynamoDBBean must not be null!"); - } - else - { - Assert.isNull(amazonDynamoDBBean,"Cannot specify both amazonDynamoDB bean and dynamoDBOperationsBean in repository configuration"); - Assert.isNull(dynamoDBMapperConfigBean,"Cannot specify both dynamoDBMapperConfigBean bean and dynamoDBOperationsBean in repository configuration"); + } else { + Assert.isNull(amazonDynamoDBBean, + "Cannot specify both amazonDynamoDB bean and dynamoDBOperationsBean in repository configuration"); + Assert.isNull(dynamoDBMapperConfigBean, + "Cannot specify both dynamoDBMapperConfigBean bean and dynamoDBOperationsBean in repository configuration"); } this.amazonDynamoDBBean = amazonDynamoDBBean; @@ -91,18 +90,18 @@ public T create(CreationalContext creationalContext, Class repositoryType) AmazonDynamoDB amazonDynamoDB = getDependencyInstance(amazonDynamoDBBean, AmazonDynamoDB.class); // Get an instance from the associated optional AmazonDynamoDB bean. - DynamoDBMapperConfig dynamoDBMapperConfig = dynamoDBMapperConfigBean == null ? null : getDependencyInstance( - dynamoDBMapperConfigBean, DynamoDBMapperConfig.class); - - DynamoDBOperations dynamoDBOperations = dynamoDBOperationsBean == null ? null - : getDependencyInstance( - dynamoDBOperationsBean, DynamoDBOperations.class); + DynamoDBMapperConfig dynamoDBMapperConfig = dynamoDBMapperConfigBean == null + ? null + : getDependencyInstance(dynamoDBMapperConfigBean, DynamoDBMapperConfig.class); - if (dynamoDBOperations == null) - { - dynamoDBOperations = new DynamoDBTemplate(amazonDynamoDB,dynamoDBMapperConfig); + DynamoDBOperations dynamoDBOperations = dynamoDBOperationsBean == null + ? null + : getDependencyInstance(dynamoDBOperationsBean, DynamoDBOperations.class); + + if (dynamoDBOperations == null) { + dynamoDBOperations = new DynamoDBTemplate(amazonDynamoDB, dynamoDBMapperConfig); } - + DynamoDBRepositoryFactory factory = new DynamoDBRepositoryFactory(dynamoDBOperations); return factory.getRepository(repositoryType); } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryExtension.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryExtension.java index 9e7df1ee..9c7c915a 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryExtension.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryExtension.java @@ -52,7 +52,6 @@ public class DynamoDBRepositoryExtension extends CdiRepositoryExtensionSupport { private final Map, Bean> dynamoDBOperationss = new HashMap, Bean>(); - private final Map, Bean> dbMapperConfigs = new HashMap, Bean>(); public DynamoDBRepositoryExtension() { @@ -60,9 +59,9 @@ public DynamoDBRepositoryExtension() { } /** - * Implementation of a an observer which checks for AmazonDynamoDBClient - * beans and stores them in {@link #amazonDynamoDBClients} for later - * association with corresponding repository beans. + * Implementation of a an observer which checks for AmazonDynamoDBClient beans + * and stores them in {@link #amazonDynamoDBClients} for later association with + * corresponding repository beans. * * @param * The type. @@ -85,7 +84,8 @@ void processBean(@Observes ProcessBean processBean) { if (type instanceof Class && DynamoDBMapperConfig.class.isAssignableFrom((Class) type)) { Set qualifiers = new HashSet(bean.getQualifiers()); if (bean.isAlternative() || !dbMapperConfigs.containsKey(qualifiers)) { - LOGGER.debug("Discovered '{}' with qualifiers {}.", DynamoDBMapperConfig.class.getName(), qualifiers); + LOGGER.debug("Discovered '{}' with qualifiers {}.", DynamoDBMapperConfig.class.getName(), + qualifiers); dbMapperConfigs.put(qualifiers, (Bean) bean); } } @@ -93,8 +93,8 @@ void processBean(@Observes ProcessBean processBean) { } /** - * Implementation of a an observer which registers beans to the CDI - * container for the detected Spring Data repositories. + * Implementation of a an observer which registers beans to the CDI container + * for the detected Spring Data repositories. *

* The repository beans are associated to the EntityManagers using their * qualifiers. @@ -127,7 +127,8 @@ void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanMan * The BeanManager instance. * @return The bean. */ - private Bean createRepositoryBean(Class repositoryType, Set qualifiers, BeanManager beanManager) { + private Bean createRepositoryBean(Class repositoryType, Set qualifiers, + BeanManager beanManager) { // Determine the amazondbclient bean which matches the qualifiers of the // repository. @@ -136,17 +137,17 @@ private Bean createRepositoryBean(Class repositoryType, Set dynamoDBMapperConfigBean = dbMapperConfigs.get(qualifiers); - + if (amazonDynamoDBBean == null) { - throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.", - AmazonDynamoDBClient.class.getName(), qualifiers)); + throw new UnsatisfiedResolutionException( + String.format("Unable to resolve a bean for '%s' with qualifiers %s.", + AmazonDynamoDBClient.class.getName(), qualifiers)); } - + Bean dynamoDBOperationsBean = dynamoDBOperationss.get(qualifiers); - - + // Construct and return the repository bean. - return new DynamoDBRepositoryBean(beanManager, amazonDynamoDBBean, dynamoDBMapperConfigBean,dynamoDBOperationsBean,qualifiers, - repositoryType); + return new DynamoDBRepositoryBean(beanManager, amazonDynamoDBBean, dynamoDBMapperConfigBean, + dynamoDBOperationsBean, qualifiers, repositoryType); } } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/package-info.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/package-info.java index e8345d0a..20b51ffa 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/package-info.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/cdi/package-info.java @@ -14,7 +14,6 @@ * limitations under the License. */ /** - * CDI support for Spring Data DynamoDB Repositories. + * CDI support for Spring Data DynamoDB Repositories. */ package org.socialsignin.spring.data.dynamodb.repository.cdi; - diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/DynamoDBRepositoryConfigExtension.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/DynamoDBRepositoryConfigExtension.java index e5a49be4..88f130bc 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/DynamoDBRepositoryConfigExtension.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/DynamoDBRepositoryConfigExtension.java @@ -35,7 +35,7 @@ public class DynamoDBRepositoryConfigExtension extends RepositoryConfigurationEx private static final String DEFAULT_AMAZON_DYNAMO_DB_BEAN_NAME = "amazonDynamoDB"; private static final String DYNAMO_DB_MAPPER_CONFIG_REF = "dynamodb-mapper-config-ref"; - + private static final String DYNAMO_DB_OPERATIONS_REF = "dynamodb-operations-ref"; private static final String AMAZON_DYNAMODB_REF = "amazon-dynamodb-ref"; @@ -49,7 +49,8 @@ public String getRepositoryFactoryBeanClassName() { public void postProcess(BeanDefinitionBuilder builder, AnnotationRepositoryConfigurationSource config) { AnnotationAttributes attributes = config.getAttributes(); - postProcess(builder, attributes.getString("amazonDynamoDBRef"), attributes.getString("dynamoDBMapperConfigRef"),attributes.getString("dynamoDBOperationsRef")); + postProcess(builder, attributes.getString("amazonDynamoDBRef"), attributes.getString("dynamoDBMapperConfigRef"), + attributes.getString("dynamoDBOperationsRef")); } @@ -59,8 +60,7 @@ public void postProcess(BeanDefinitionBuilder builder, AnnotationRepositoryConfi * @see org.springframework.data.repository.config. * RepositoryConfigurationExtensionSupport * #postProcess(org.springframework.beans - * .factory.support.BeanDefinitionBuilder, - * org.springframework.data.repository + * .factory.support.BeanDefinitionBuilder, org.springframework.data.repository * .config.XmlRepositoryConfigurationSource) */ @Override @@ -72,21 +72,22 @@ public void postProcess(BeanDefinitionBuilder builder, XmlRepositoryConfiguratio ParsingUtils.setPropertyReference(builder, element, DYNAMO_DB_MAPPER_CONFIG_REF, "dynamoDBMapperConfig"); ParsingUtils.setPropertyReference(builder, element, DYNAMO_DB_OPERATIONS_REF, "dynamoDBOperations"); - } - private void postProcess(BeanDefinitionBuilder builder, String amazonDynamoDBRef, String dynamoDBMapperConfigRef,String dynamoDBOperationsRef) { + private void postProcess(BeanDefinitionBuilder builder, String amazonDynamoDBRef, String dynamoDBMapperConfigRef, + String dynamoDBOperationsRef) { - if (StringUtils.hasText(dynamoDBOperationsRef)) - { + if (StringUtils.hasText(dynamoDBOperationsRef)) { builder.addPropertyReference("dynamoDBOperations", dynamoDBOperationsRef); - Assert.isTrue(!StringUtils.hasText(amazonDynamoDBRef),"Cannot specify both amazonDynamoDB bean and dynamoDBOperationsBean in repository configuration"); - Assert.isTrue(!StringUtils.hasText(dynamoDBMapperConfigRef),"Cannot specify both dynamoDBMapperConfigBean bean and dynamoDBOperationsBean in repository configuration"); - } - else - { - - amazonDynamoDBRef = StringUtils.hasText(amazonDynamoDBRef) ? amazonDynamoDBRef : DEFAULT_AMAZON_DYNAMO_DB_BEAN_NAME; + Assert.isTrue(!StringUtils.hasText(amazonDynamoDBRef), + "Cannot specify both amazonDynamoDB bean and dynamoDBOperationsBean in repository configuration"); + Assert.isTrue(!StringUtils.hasText(dynamoDBMapperConfigRef), + "Cannot specify both dynamoDBMapperConfigBean bean and dynamoDBOperationsBean in repository configuration"); + } else { + + amazonDynamoDBRef = StringUtils.hasText(amazonDynamoDBRef) + ? amazonDynamoDBRef + : DEFAULT_AMAZON_DYNAMO_DB_BEAN_NAME; builder.addPropertyReference("amazonDynamoDB", amazonDynamoDBRef); @@ -94,7 +95,7 @@ private void postProcess(BeanDefinitionBuilder builder, String amazonDynamoDBRef builder.addPropertyReference("dynamoDBMapperConfig", dynamoDBMapperConfigRef); } } - + } @Override diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/DynamoDBRepositoryNameSpaceHandler.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/DynamoDBRepositoryNameSpaceHandler.java index 7956f936..9900cc76 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/DynamoDBRepositoryNameSpaceHandler.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/DynamoDBRepositoryNameSpaceHandler.java @@ -39,7 +39,7 @@ public void init() { RepositoryBeanDefinitionParser repositoryBeanDefinitionParser = new RepositoryBeanDefinitionParser(extension); registerBeanDefinitionParser("repositories", repositoryBeanDefinitionParser); - registerBeanDefinitionParser("auditing", new DynamoDBAuditingBeanDefinitionParser()); + registerBeanDefinitionParser("auditing", new DynamoDBAuditingBeanDefinitionParser()); } } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/EnableDynamoDBRepositories.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/EnableDynamoDBRepositories.java index 0349da1d..332a3058 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/EnableDynamoDBRepositories.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/config/EnableDynamoDBRepositories.java @@ -46,40 +46,43 @@ * annotation declarations e.g.: * {@code @EnableDynamoDBRepositories("org.my.pkg")} instead of * {@code @EnableDynamoDBaRepositories(basePackages="org.my.pkg")}. + * * @return The package name for scanning */ String[] value() default {}; /** - * Base packages to scan for annotated components. {@link #value()} is an - * alias for (and mutually exclusive with) this attribute. Use + * 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. + * * @return The package name for scanning */ 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. + * 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. + * * @return The class to figure out the base package for scanning */ 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. + * 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. + * * @return All the include filters */ Filter[] includeFilters() default {}; /** * Specifies which types are not eligible for component scanning. + * * @return All the exclude filters */ Filter[] excludeFilters() default {}; @@ -104,16 +107,19 @@ String namedQueriesLocation() default ""; /** - * Returns the key of the {@link org.springframework.data.repository.query.QueryLookupStrategy} to be used for lookup - * queries for query methods. Defaults to {@link Key#CREATE_IF_NOT_FOUND}. + * Returns the key of the + * {@link org.springframework.data.repository.query.QueryLookupStrategy} to be + * used for lookup queries for query methods. Defaults to + * {@link Key#CREATE_IF_NOT_FOUND}. * * @return The lookup strategy */ Key queryLookupStrategy() default Key.CREATE_IF_NOT_FOUND; /** - * Returns the {@link org.springframework.beans.factory.FactoryBean} class to be used for each repository - * instance. Defaults to {@link DynamoDBRepositoryFactoryBean}. + * Returns the {@link org.springframework.beans.factory.FactoryBean} class to be + * used for each repository instance. Defaults to + * {@link DynamoDBRepositoryFactoryBean}. * * @return The repository factory bean cleass */ @@ -122,18 +128,22 @@ // DynamoDB specific configuration /** - * Returns the {@link com.amazonaws.services.dynamodbv2.AmazonDynamoDB } reference to be used for each - * repository instance + * Returns the {@link com.amazonaws.services.dynamodbv2.AmazonDynamoDB } + * reference to be used for each repository instance * - * @return The {@link com.amazonaws.services.dynamodbv2.AmazonDynamoDB} bean name + * @return The {@link com.amazonaws.services.dynamodbv2.AmazonDynamoDB} bean + * name */ String amazonDynamoDBRef() default ""; /** - * Returns the {@link com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig } reference to be used for to - * configure AmazonDynamoDB + * Returns the + * {@link com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig } + * reference to be used for to configure AmazonDynamoDB * - * @return The {@link com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig} bean name + * @return The + * {@link com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig} + * bean name */ String dynamoDBMapperConfigRef() default ""; @@ -141,9 +151,10 @@ * Returns the {@link javax.validation.Validator } reference to be used for to * validate DynamoDB entities * - * @return The {@link org.socialsignin.spring.data.dynamodb.core.DynamoDBOperations} bean name + * @return The + * {@link org.socialsignin.spring.data.dynamodb.core.DynamoDBOperations} + * bean name */ String dynamoDBOperationsRef() default ""; - } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQuery.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQuery.java index 7cbebdd9..7e171330 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQuery.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQuery.java @@ -44,13 +44,11 @@ public AbstractDynamoDBQuery(DynamoDBOperations dynamoDBOperations, DynamoDBQuer this.dynamoDBOperations = dynamoDBOperations; this.method = method; } - protected QueryExecution getExecution() { if (method.isCollectionQuery() && !isSingleEntityResultsRestriction()) { return new CollectionExecution(); - } - else if (method.isSliceQuery() && !isSingleEntityResultsRestriction()) { + } else if (method.isSliceQuery() && !isSingleEntityResultsRestriction()) { return new SlicedExecution(method.getParameters()); } else if (method.isPageQuery() && !isSingleEntityResultsRestriction()) { return new PagedExecution(method.getParameters()); @@ -70,19 +68,18 @@ else if (method.isSliceQuery() && !isSingleEntityResultsRestriction()) { protected abstract boolean isCountQuery(); protected abstract boolean isExistsQuery(); protected abstract boolean isDeleteQuery(); - + protected abstract Integer getResultsRestrictionIfApplicable(); protected abstract boolean isSingleEntityResultsRestriction(); - protected Query doCreateQueryWithPermissions(Object values[]) { Query query = doCreateQuery(values); query.setScanEnabled(method.isScanEnabled()); return query; } - + protected Query doCreateCountQueryWithPermissions(Object values[], boolean pageQuery) { - Query query = doCreateCountQuery(values,pageQuery); + Query query = doCreateCountQuery(values, pageQuery); query.setScanCountEnabled(method.isScanCountEnabled()); return query; } @@ -91,19 +88,15 @@ private interface QueryExecution { Object execute(AbstractDynamoDBQuery query, Object[] values); } - class CollectionExecution implements QueryExecution { - - @Override public Object execute(AbstractDynamoDBQuery dynamoDBQuery, Object[] values) { Query query = dynamoDBQuery.doCreateQueryWithPermissions(values); - if (getResultsRestrictionIfApplicable() != null) - { + if (getResultsRestrictionIfApplicable() != null) { return restrictMaxResultsIfNecessary(query.getResultList().iterator()); - } - else return query.getResultList(); + } else + return query.getResultList(); } private List restrictMaxResultsIfNecessary(Iterator iterator) { @@ -113,7 +106,7 @@ private List restrictMaxResultsIfNecessary(Iterator iterator) { resultsPage.add(iterator.next()); processed++; } - return resultsPage; + return resultsPage; } } @@ -142,7 +135,9 @@ private long scanThroughResults(Iterator iterator, long resultsToScan) { private List readPageOfResultsRestrictMaxResultsIfNecessary(Iterator iterator, int pageSize) { int processed = 0; - int toProcess = getResultsRestrictionIfApplicable() != null ? Math.min(pageSize,getResultsRestrictionIfApplicable()) : pageSize; + int toProcess = getResultsRestrictionIfApplicable() != null + ? Math.min(pageSize, getResultsRestrictionIfApplicable()) + : pageSize; List resultsPage = new ArrayList<>(); while (iterator.hasNext() && processed < toProcess) { resultsPage.add(iterator.next()); @@ -159,12 +154,12 @@ public Object execute(AbstractDynamoDBQuery dynamoDBQuery, Object[] value Query query = dynamoDBQuery.doCreateQueryWithPermissions(values); List results = query.getResultList(); - return createPage(results, pageable,dynamoDBQuery,values); + return createPage(results, pageable, dynamoDBQuery, values); } - private Page createPage(List allResults, Pageable pageable,AbstractDynamoDBQuery dynamoDBQuery,Object[] values) { + private Page createPage(List allResults, Pageable pageable, AbstractDynamoDBQuery dynamoDBQuery, + Object[] values) { - Iterator iterator = allResults.iterator(); if (pageable.getOffset() > 0) { long processedCount = scanThroughResults(iterator, pageable.getOffset()); @@ -172,21 +167,19 @@ private Page createPage(List allResults, Pageable pageable,AbstractDynamoD return new PageImpl<>(new ArrayList()); } List results = readPageOfResultsRestrictMaxResultsIfNecessary(iterator, pageable.getPageSize()); - - - Query countQuery = dynamoDBQuery.doCreateCountQueryWithPermissions(values,true); + + Query countQuery = dynamoDBQuery.doCreateCountQueryWithPermissions(values, true); long count = countQuery.getSingleResult(); - - if (getResultsRestrictionIfApplicable() != null) - { - count = Math.min(count,getResultsRestrictionIfApplicable()); + + if (getResultsRestrictionIfApplicable() != null) { + count = Math.min(count, getResultsRestrictionIfApplicable()); } - + return new PageImpl<>(results, pageable, count); } } - + class SlicedExecution implements QueryExecution { private final Parameters parameters; @@ -207,7 +200,9 @@ private long scanThroughResults(Iterator iterator, long resultsToScan) { private List readPageOfResultsRestrictMaxResultsIfNecessary(Iterator iterator, int pageSize) { int processed = 0; - int toProcess = getResultsRestrictionIfApplicable() != null ? Math.min(pageSize,getResultsRestrictionIfApplicable()) : pageSize; + int toProcess = getResultsRestrictionIfApplicable() != null + ? Math.min(pageSize, getResultsRestrictionIfApplicable()) + : pageSize; List resultsPage = new ArrayList<>(); while (iterator.hasNext() && processed < toProcess) { @@ -238,7 +233,9 @@ private Slice createSlice(List allResults, Pageable pageable) { List results = readPageOfResultsRestrictMaxResultsIfNecessary(iterator, pageable.getPageSize()); // Scan ahead to retrieve the next page count boolean hasMoreResults = scanThroughResults(iterator, 1) > 0; - if (getResultsRestrictionIfApplicable() != null && getResultsRestrictionIfApplicable().intValue() <= results.size()) hasMoreResults = false; + if (getResultsRestrictionIfApplicable() != null + && getResultsRestrictionIfApplicable().intValue() <= results.size()) + hasMoreResults = false; return new SliceImpl<>(results, pageable, hasMoreResults); } } @@ -257,33 +254,25 @@ class SingleEntityExecution implements QueryExecution { @Override public Object execute(AbstractDynamoDBQuery dynamoDBQuery, Object[] values) { - if (isCountQuery()) - { - return dynamoDBQuery.doCreateCountQueryWithPermissions(values,false).getSingleResult(); - } - else if (isExistsQuery()) - { + if (isCountQuery()) { + return dynamoDBQuery.doCreateCountQueryWithPermissions(values, false).getSingleResult(); + } else if (isExistsQuery()) { return !dynamoDBQuery.doCreateQueryWithPermissions(values).getResultList().isEmpty(); - } - else - { + } else { return dynamoDBQuery.doCreateQueryWithPermissions(values).getSingleResult(); - } + } } } - + class SingleEntityLimitedExecution implements QueryExecution { @Override public Object execute(AbstractDynamoDBQuery dynamoDBQuery, Object[] values) { - if (isCountQuery()) - { - return dynamoDBQuery.doCreateCountQueryWithPermissions(values,false).getSingleResult(); - } - else - { - List resultList = dynamoDBQuery.doCreateQueryWithPermissions(values).getResultList(); + if (isCountQuery()) { + return dynamoDBQuery.doCreateCountQueryWithPermissions(values, false).getSingleResult(); + } else { + List resultList = dynamoDBQuery.doCreateQueryWithPermissions(values).getResultList(); return resultList.size() == 0 ? null : resultList.get(0); } @@ -294,8 +283,7 @@ public Object execute(AbstractDynamoDBQuery dynamoDBQuery, Object[] value /* * (non-Javadoc) * - * @see - * org.springframework.data.repository.query.RepositoryQuery#execute(java + * @see org.springframework.data.repository.query.RepositoryQuery#execute(java * .lang.Object[]) */ public Object execute(Object[] parameters) { diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCreator.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCreator.java index 8fdb4dcc..5590300e 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCreator.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCreator.java @@ -39,14 +39,16 @@ * @author Michael Lavelle * @author Sebastian Just */ -public abstract class AbstractDynamoDBQueryCreator extends - AbstractQueryCreator, DynamoDBQueryCriteria> { +public abstract class AbstractDynamoDBQueryCreator + extends + AbstractQueryCreator, DynamoDBQueryCriteria> { protected final DynamoDBEntityInformation entityMetadata; protected final DynamoDBOperations dynamoDBOperations; protected final Optional projection; - public AbstractDynamoDBQueryCreator(PartTree tree, DynamoDBEntityInformation entityMetadata, Optional projection, DynamoDBOperations dynamoDBOperations) { + public AbstractDynamoDBQueryCreator(PartTree tree, DynamoDBEntityInformation entityMetadata, + Optional projection, DynamoDBOperations dynamoDBOperations) { super(tree); this.entityMetadata = entityMetadata; this.projection = projection; @@ -54,7 +56,8 @@ public AbstractDynamoDBQueryCreator(PartTree tree, DynamoDBEntityInformation entityMetadata, Optional projection, DynamoDBOperations dynamoDBOperations) { + DynamoDBEntityInformation entityMetadata, Optional projection, + DynamoDBOperations dynamoDBOperations) { super(tree, parameterAccessor); this.entityMetadata = entityMetadata; this.projection = projection; @@ -63,94 +66,95 @@ public AbstractDynamoDBQueryCreator(PartTree tree, ParameterAccessor parameterAc @Override protected DynamoDBQueryCriteria create(Part part, Iterator iterator) { - final DynamoDBMapperTableModel tableModel = dynamoDBOperations.getTableModel(entityMetadata.getJavaType()); - DynamoDBQueryCriteria criteria = entityMetadata.isRangeKeyAware() ? new DynamoDBEntityWithHashAndRangeKeyCriteria( - (DynamoDBIdIsHashAndRangeKeyEntityInformation) entityMetadata, tableModel) + final DynamoDBMapperTableModel tableModel = dynamoDBOperations.getTableModel(entityMetadata.getJavaType()); + DynamoDBQueryCriteria criteria = entityMetadata.isRangeKeyAware() + ? new DynamoDBEntityWithHashAndRangeKeyCriteria( + (DynamoDBIdIsHashAndRangeKeyEntityInformation) entityMetadata, tableModel) : new DynamoDBEntityWithHashKeyOnlyCriteria<>(entityMetadata, tableModel); return addCriteria(criteria, part, iterator); } - protected DynamoDBQueryCriteria addCriteria(DynamoDBQueryCriteria criteria, Part part, Iterator iterator) { + protected DynamoDBQueryCriteria addCriteria(DynamoDBQueryCriteria criteria, Part part, + Iterator iterator) { if (part.shouldIgnoreCase().equals(IgnoreCaseType.ALWAYS)) throw new UnsupportedOperationException("Case insensitivity not supported"); Class leafNodePropertyType = part.getProperty().getLeafProperty().getType(); - + PropertyPath leafNodePropertyPath = part.getProperty().getLeafProperty(); String leafNodePropertyName = leafNodePropertyPath.toDotPath(); - if (leafNodePropertyName.indexOf(".") != -1) - { + if (leafNodePropertyName.indexOf(".") != -1) { int index = leafNodePropertyName.lastIndexOf("."); leafNodePropertyName = leafNodePropertyName.substring(index); } - + switch (part.getType()) { - - case IN: - Object in = iterator.next(); - Assert.notNull(in, "Creating conditions on null parameters not supported: please specify a value for '" - + leafNodePropertyName + "'"); - boolean isIterable = ClassUtils.isAssignable(Iterable.class, in.getClass()); - boolean isArray = ObjectUtils.isArray(in); - Assert.isTrue(isIterable || isArray, "In criteria can only operate with Iterable or Array parameters"); - Iterable iterable = isIterable ? ((Iterable) in) : Arrays.asList(ObjectUtils.toObjectArray(in)); - return criteria.withPropertyIn(leafNodePropertyName, iterable, leafNodePropertyType); - case CONTAINING: - return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.CONTAINS, - iterator.next(), leafNodePropertyType); - case STARTING_WITH: - return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.BEGINS_WITH, - iterator.next(), leafNodePropertyType); - case BETWEEN: - Object first = iterator.next(); - Object second = iterator.next(); - return criteria.withPropertyBetween(leafNodePropertyName, first, second, leafNodePropertyType); - case AFTER: - case GREATER_THAN: - return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.GT, iterator.next(), - leafNodePropertyType); - case BEFORE: - case LESS_THAN: - return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.LT, iterator.next(), - leafNodePropertyType); - case GREATER_THAN_EQUAL: - return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.GE, iterator.next(), - leafNodePropertyType); - case LESS_THAN_EQUAL: - return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.LE, iterator.next(), - leafNodePropertyType); - case IS_NULL: - return criteria.withNoValuedCriteria(leafNodePropertyName, ComparisonOperator.NULL); - case IS_NOT_NULL: - return criteria.withNoValuedCriteria(leafNodePropertyName, ComparisonOperator.NOT_NULL); - case TRUE: - return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.EQ, Boolean.TRUE, - leafNodePropertyType); - case FALSE: - return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.EQ, Boolean.FALSE, - leafNodePropertyType); - case SIMPLE_PROPERTY: - return criteria.withPropertyEquals(leafNodePropertyName, iterator.next(), leafNodePropertyType); - case NEGATING_SIMPLE_PROPERTY: - return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.NE, iterator.next(), - leafNodePropertyType); - default: - throw new IllegalArgumentException("Unsupported keyword " + part.getType()); + + case IN : + Object in = iterator.next(); + Assert.notNull(in, "Creating conditions on null parameters not supported: please specify a value for '" + + leafNodePropertyName + "'"); + boolean isIterable = ClassUtils.isAssignable(Iterable.class, in.getClass()); + boolean isArray = ObjectUtils.isArray(in); + Assert.isTrue(isIterable || isArray, "In criteria can only operate with Iterable or Array parameters"); + Iterable iterable = isIterable ? ((Iterable) in) : Arrays.asList(ObjectUtils.toObjectArray(in)); + return criteria.withPropertyIn(leafNodePropertyName, iterable, leafNodePropertyType); + case CONTAINING : + return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.CONTAINS, + iterator.next(), leafNodePropertyType); + case STARTING_WITH : + return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.BEGINS_WITH, + iterator.next(), leafNodePropertyType); + case BETWEEN : + Object first = iterator.next(); + Object second = iterator.next(); + return criteria.withPropertyBetween(leafNodePropertyName, first, second, leafNodePropertyType); + case AFTER : + case GREATER_THAN : + return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.GT, iterator.next(), + leafNodePropertyType); + case BEFORE : + case LESS_THAN : + return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.LT, iterator.next(), + leafNodePropertyType); + case GREATER_THAN_EQUAL : + return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.GE, iterator.next(), + leafNodePropertyType); + case LESS_THAN_EQUAL : + return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.LE, iterator.next(), + leafNodePropertyType); + case IS_NULL : + return criteria.withNoValuedCriteria(leafNodePropertyName, ComparisonOperator.NULL); + case IS_NOT_NULL : + return criteria.withNoValuedCriteria(leafNodePropertyName, ComparisonOperator.NOT_NULL); + case TRUE : + return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.EQ, Boolean.TRUE, + leafNodePropertyType); + case FALSE : + return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.EQ, Boolean.FALSE, + leafNodePropertyType); + case SIMPLE_PROPERTY : + return criteria.withPropertyEquals(leafNodePropertyName, iterator.next(), leafNodePropertyType); + case NEGATING_SIMPLE_PROPERTY : + return criteria.withSingleValueCriteria(leafNodePropertyName, ComparisonOperator.NE, iterator.next(), + leafNodePropertyType); + default : + throw new IllegalArgumentException("Unsupported keyword " + part.getType()); } } @Override - protected DynamoDBQueryCriteria and(Part part, DynamoDBQueryCriteria base, Iterator iterator) { + protected DynamoDBQueryCriteria and(Part part, DynamoDBQueryCriteria base, + Iterator iterator) { return addCriteria(base, part, iterator); } @Override - protected DynamoDBQueryCriteria or(DynamoDBQueryCriteria base, DynamoDBQueryCriteria criteria) { + protected DynamoDBQueryCriteria or(DynamoDBQueryCriteria base, + DynamoDBQueryCriteria criteria) { throw new UnsupportedOperationException("Or queries not supported"); } - - } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCriteria.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCriteria.java index a18ba103..6c0ea0aa 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCriteria.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCriteria.java @@ -136,7 +136,8 @@ protected QueryRequest buildQueryRequest(String tableName, String theIndexName, return queryRequest; } - protected void applySortIfSpecified(DynamoDBQueryExpression queryExpression, List permittedPropertyNames) { + protected void applySortIfSpecified(DynamoDBQueryExpression queryExpression, + List permittedPropertyNames) { if (permittedPropertyNames.size() > 1) { throw new UnsupportedOperationException("Can only sort by at most a single range or index range key"); @@ -152,8 +153,8 @@ protected void applySortIfSpecified(DynamoDBQueryExpression queryExpression, queryExpression.setScanIndexForward(order.getDirection().equals(Direction.ASC)); sortAlreadySet = true; } else { - throw new UnsupportedOperationException("Sorting only possible by " + permittedPropertyNames - + " for the criteria specified"); + throw new UnsupportedOperationException( + "Sorting only possible by " + permittedPropertyNames + " for the criteria specified"); } } } @@ -178,16 +179,16 @@ protected void applySortIfSpecified(QueryRequest queryRequest, List perm queryRequest.setScanIndexForward(order.getDirection().equals(Direction.ASC)); sortAlreadySet = true; } else { - throw new UnsupportedOperationException("Sorting only possible by " + permittedPropertyNames - + " for the criteria specified"); + throw new UnsupportedOperationException( + "Sorting only possible by " + permittedPropertyNames + " for the criteria specified"); } } } public boolean comparisonOperatorsPermittedForQuery() { - List comparisonOperatorsPermittedForQuery = Arrays.asList(new ComparisonOperator[] { + List comparisonOperatorsPermittedForQuery = Arrays.asList(new ComparisonOperator[]{ ComparisonOperator.EQ, ComparisonOperator.LE, ComparisonOperator.LT, ComparisonOperator.GE, - ComparisonOperator.GT, ComparisonOperator.BEGINS_WITH, ComparisonOperator.BETWEEN }); + ComparisonOperator.GT, ComparisonOperator.BEGINS_WITH, ComparisonOperator.BETWEEN}); // Can only query on subset of Conditions for (Collection conditions : attributeConditions.values()) { @@ -203,11 +204,12 @@ public boolean comparisonOperatorsPermittedForQuery() { protected List getHashKeyConditions() { List hashKeyConditions = null; - if (isApplicableForGlobalSecondaryIndex() - && entityInformation.getGlobalSecondaryIndexNamesByPropertyName().keySet().contains(getHashKeyPropertyName())) { - hashKeyConditions = getHashKeyAttributeValue() == null ? null : Arrays.asList(createSingleValueCondition( - getHashKeyPropertyName(), ComparisonOperator.EQ, getHashKeyAttributeValue(), getHashKeyAttributeValue() - .getClass(), true)); + if (isApplicableForGlobalSecondaryIndex() && entityInformation.getGlobalSecondaryIndexNamesByPropertyName() + .keySet().contains(getHashKeyPropertyName())) { + hashKeyConditions = getHashKeyAttributeValue() == null + ? null + : Arrays.asList(createSingleValueCondition(getHashKeyPropertyName(), ComparisonOperator.EQ, + getHashKeyAttributeValue(), getHashKeyAttributeValue().getClass(), true)); if (hashKeyConditions == null) { if (attributeConditions.containsKey(getHashKeyAttributeName())) { hashKeyConditions = attributeConditions.get(getHashKeyAttributeName()); @@ -219,26 +221,26 @@ protected List getHashKeyConditions() { return hashKeyConditions; } - public AbstractDynamoDBQueryCriteria(DynamoDBEntityInformation dynamoDBEntityInformation, final DynamoDBMapperTableModel tableModel) { + public AbstractDynamoDBQueryCriteria(DynamoDBEntityInformation dynamoDBEntityInformation, + final DynamoDBMapperTableModel tableModel) { this.clazz = dynamoDBEntityInformation.getJavaType(); this.attributeConditions = new LinkedMultiValueMap<>(); this.propertyConditions = new LinkedMultiValueMap<>(); this.hashKeyPropertyName = dynamoDBEntityInformation.getHashKeyPropertyName(); this.entityInformation = dynamoDBEntityInformation; this.attributeNamesByPropertyName = new HashMap<>(); - // TODO consider adding the DynamoDBMapper table model to DynamoDBEntityInformation instead + // TODO consider adding the DynamoDBMapper table model to + // DynamoDBEntityInformation instead this.tableModel = tableModel; } - private String getFirstDeclaredIndexNameForAttribute(Map indexNamesByAttributeName,List indexNamesToCheck,String attributeName) - { + private String getFirstDeclaredIndexNameForAttribute(Map indexNamesByAttributeName, + List indexNamesToCheck, String attributeName) { String indexName = null; String[] declaredOrderedIndexNamesForAttribute = indexNamesByAttributeName.get(attributeName); - for (String declaredOrderedIndexNameForAttribute : declaredOrderedIndexNamesForAttribute) - { - if (indexName == null && indexNamesToCheck.contains(declaredOrderedIndexNameForAttribute)) - { - indexName = declaredOrderedIndexNameForAttribute; + for (String declaredOrderedIndexNameForAttribute : declaredOrderedIndexNamesForAttribute) { + if (indexName == null && indexNamesToCheck.contains(declaredOrderedIndexNameForAttribute)) { + indexName = declaredOrderedIndexNameForAttribute; } } @@ -247,27 +249,29 @@ private String getFirstDeclaredIndexNameForAttribute(Map indexN protected String getGlobalSecondaryIndexName() { - // Lazy evaluate the globalSecondaryIndexName if not already set - // We must have attribute conditions specified in order to use a global secondary index, otherwise return null for index name + // We must have attribute conditions specified in order to use a global + // secondary index, otherwise return null for index name // Also this method only evaluates the - if (globalSecondaryIndexName == null && attributeConditions != null && !attributeConditions.isEmpty()) - { - // Declare map of index names by attribute name which we will populate below - this will be used to determine which index to use if multiple indexes are applicable - Map indexNamesByAttributeName = new HashMap<>(); - - // Declare map of attribute lists by index name which we will populate below - this will be used to determine whether we have an exact match index for specified attribute conditions + if (globalSecondaryIndexName == null && attributeConditions != null && !attributeConditions.isEmpty()) { + // Declare map of index names by attribute name which we will populate below - + // this will be used to determine which index to use if multiple indexes are + // applicable + Map indexNamesByAttributeName = new HashMap<>(); + + // Declare map of attribute lists by index name which we will populate below - + // this will be used to determine whether we have an exact match index for + // specified attribute conditions MultiValueMap attributeListsByIndexName = new LinkedMultiValueMap<>(); // Populate the above maps - for (Entry indexNamesForPropertyNameEntry : entityInformation.getGlobalSecondaryIndexNamesByPropertyName().entrySet()) - { + for (Entry indexNamesForPropertyNameEntry : entityInformation + .getGlobalSecondaryIndexNamesByPropertyName().entrySet()) { String propertyName = indexNamesForPropertyNameEntry.getKey(); String attributeName = getAttributeName(propertyName); indexNamesByAttributeName.put(attributeName, indexNamesForPropertyNameEntry.getValue()); - for (String indexNameForPropertyName : indexNamesForPropertyNameEntry.getValue()) - { + for (String indexNameForPropertyName : indexNamesForPropertyNameEntry.getValue()) { attributeListsByIndexName.add(indexNameForPropertyName, attributeName); } } @@ -276,46 +280,36 @@ protected String getGlobalSecondaryIndexName() { List exactMatchIndexNames = new ArrayList<>(); List partialMatchIndexNames = new ArrayList<>(); - // Populate matching index name lists - an index is either an exact match ( the index attributes match all the specified criteria exactly) - // or a partial match ( the properties for the specified criteria are contained within the property set for an index ) - for (Entry> attributeListForIndexNameEntry : attributeListsByIndexName.entrySet()) - { + // Populate matching index name lists - an index is either an exact match ( the + // index attributes match all the specified criteria exactly) + // or a partial match ( the properties for the specified criteria are contained + // within the property set for an index ) + for (Entry> attributeListForIndexNameEntry : attributeListsByIndexName.entrySet()) { String indexNameForAttributeList = attributeListForIndexNameEntry.getKey(); List attributeList = attributeListForIndexNameEntry.getValue(); - if (attributeList.containsAll(attributeConditions.keySet())) - { - if (attributeConditions.keySet().containsAll(attributeList)) - { + if (attributeList.containsAll(attributeConditions.keySet())) { + if (attributeConditions.keySet().containsAll(attributeList)) { exactMatchIndexNames.add(indexNameForAttributeList); - } - else - { + } else { partialMatchIndexNames.add(indexNameForAttributeList); } } } - if (exactMatchIndexNames.size() > 1) - { - throw new RuntimeException("Multiple indexes defined on same attribute set:" + attributeConditions.keySet()); - } - else if (exactMatchIndexNames.size() == 1) - { + if (exactMatchIndexNames.size() > 1) { + throw new RuntimeException( + "Multiple indexes defined on same attribute set:" + attributeConditions.keySet()); + } else if (exactMatchIndexNames.size() == 1) { globalSecondaryIndexName = exactMatchIndexNames.get(0); - } - else if (partialMatchIndexNames.size() > 1) - { - if (attributeConditions.size() == 1) - { - globalSecondaryIndexName = getFirstDeclaredIndexNameForAttribute(indexNamesByAttributeName, partialMatchIndexNames, attributeConditions.keySet().iterator().next()); + } else if (partialMatchIndexNames.size() > 1) { + if (attributeConditions.size() == 1) { + globalSecondaryIndexName = getFirstDeclaredIndexNameForAttribute(indexNamesByAttributeName, + partialMatchIndexNames, attributeConditions.keySet().iterator().next()); } - if (globalSecondaryIndexName == null) - { + if (globalSecondaryIndexName == null) { globalSecondaryIndexName = partialMatchIndexNames.get(0); } - } - else if (partialMatchIndexNames.size() == 1) - { + } else if (partialMatchIndexNames.size() == 1) { globalSecondaryIndexName = partialMatchIndexNames.get(0); } } @@ -333,55 +327,47 @@ protected String getHashKeyAttributeName() { return getAttributeName(getHashKeyPropertyName()); } - protected boolean hasIndexHashKeyEqualCondition() - { + protected boolean hasIndexHashKeyEqualCondition() { boolean hasIndexHashKeyEqualCondition = false; - for (Map.Entry> propertyConditionList : propertyConditions.entrySet()) - { - if (entityInformation.isGlobalIndexHashKeyProperty(propertyConditionList.getKey())) - { - for (Condition condition : propertyConditionList.getValue()) - { - if ( condition.getComparisonOperator().equals(ComparisonOperator.EQ.name())) - { - hasIndexHashKeyEqualCondition = true; + for (Map.Entry> propertyConditionList : propertyConditions.entrySet()) { + if (entityInformation.isGlobalIndexHashKeyProperty(propertyConditionList.getKey())) { + for (Condition condition : propertyConditionList.getValue()) { + if (condition.getComparisonOperator().equals(ComparisonOperator.EQ.name())) { + hasIndexHashKeyEqualCondition = true; } } } } - if (hashKeyAttributeValue != null && entityInformation.isGlobalIndexHashKeyProperty(hashKeyPropertyName)) - { + if (hashKeyAttributeValue != null && entityInformation.isGlobalIndexHashKeyProperty(hashKeyPropertyName)) { hasIndexHashKeyEqualCondition = true; } return hasIndexHashKeyEqualCondition; } - protected boolean hasIndexRangeKeyCondition() - { + protected boolean hasIndexRangeKeyCondition() { boolean hasIndexRangeKeyCondition = false; - for (Map.Entry> propertyConditionList : propertyConditions.entrySet()) - { - if (entityInformation.isGlobalIndexRangeKeyProperty(propertyConditionList.getKey())) - { + for (Map.Entry> propertyConditionList : propertyConditions.entrySet()) { + if (entityInformation.isGlobalIndexRangeKeyProperty(propertyConditionList.getKey())) { hasIndexRangeKeyCondition = true; } } - if (hashKeyAttributeValue != null && entityInformation.isGlobalIndexRangeKeyProperty(hashKeyPropertyName)) - { + if (hashKeyAttributeValue != null && entityInformation.isGlobalIndexRangeKeyProperty(hashKeyPropertyName)) { hasIndexRangeKeyCondition = true; } return hasIndexRangeKeyCondition; } protected boolean isApplicableForGlobalSecondaryIndex() { boolean global = this.getGlobalSecondaryIndexName() != null; - if (global && getHashKeyAttributeValue() != null - && !entityInformation.getGlobalSecondaryIndexNamesByPropertyName().keySet().contains(getHashKeyPropertyName())) { + if (global && getHashKeyAttributeValue() != null && !entityInformation + .getGlobalSecondaryIndexNamesByPropertyName().keySet().contains(getHashKeyPropertyName())) { return false; } int attributeConditionCount = attributeConditions.keySet().size(); - boolean attributeConditionsAppropriate = hasIndexHashKeyEqualCondition() && (attributeConditionCount == 1 || (attributeConditionCount == 2 && hasIndexRangeKeyCondition())); - return global && (attributeConditionCount == 0 || attributeConditionsAppropriate) && comparisonOperatorsPermittedForQuery(); + boolean attributeConditionsAppropriate = hasIndexHashKeyEqualCondition() + && (attributeConditionCount == 1 || (attributeConditionCount == 2 && hasIndexRangeKeyCondition())); + return global && (attributeConditionCount == 0 || attributeConditionsAppropriate) + && comparisonOperatorsPermittedForQuery(); } @@ -417,9 +403,10 @@ protected String getAttributeName(String propertyName) { } @Override - public DynamoDBQueryCriteria withPropertyBetween(String propertyName, Object value1, Object value2, Class type) { - Condition condition = createCollectionCondition(propertyName, ComparisonOperator.BETWEEN, Arrays.asList(value1, value2), - type); + public DynamoDBQueryCriteria withPropertyBetween(String propertyName, Object value1, Object value2, + Class type) { + Condition condition = createCollectionCondition(propertyName, ComparisonOperator.BETWEEN, + Arrays.asList(value1, value2), type); return withCondition(propertyName, condition); } @@ -431,12 +418,13 @@ public DynamoDBQueryCriteria withPropertyIn(String propertyName, Iterable } @Override - public DynamoDBQueryCriteria withSingleValueCriteria(String propertyName, ComparisonOperator comparisonOperator, - Object value, Class propertyType) { + public DynamoDBQueryCriteria withSingleValueCriteria(String propertyName, + ComparisonOperator comparisonOperator, Object value, Class propertyType) { if (comparisonOperator.equals(ComparisonOperator.EQ)) { return withPropertyEquals(propertyName, value, propertyType); } else { - Condition condition = createSingleValueCondition(propertyName, comparisonOperator, value, propertyType, false); + Condition condition = createSingleValueCondition(propertyName, comparisonOperator, value, propertyType, + false); return withCondition(propertyName, condition); } } @@ -451,29 +439,27 @@ public Query buildQuery(DynamoDBOperations dynamoDBOperations) { } @Override - public Query buildCountQuery(DynamoDBOperations dynamoDBOperations,boolean pageQuery) { + public Query buildCountQuery(DynamoDBOperations dynamoDBOperations, boolean pageQuery) { if (isApplicableForLoad()) { return buildSingleEntityCountQuery(dynamoDBOperations); } else { - return buildFinderCountQuery(dynamoDBOperations,pageQuery); + return buildFinderCountQuery(dynamoDBOperations, pageQuery); } } - protected abstract Query buildSingleEntityLoadQuery(DynamoDBOperations dynamoDBOperations); protected abstract Query buildSingleEntityCountQuery(DynamoDBOperations dynamoDBOperations); - protected abstract Query buildFinderQuery(DynamoDBOperations dynamoDBOperations); - protected abstract Query buildFinderCountQuery(DynamoDBOperations dynamoDBOperations,boolean pageQuery); - + protected abstract Query buildFinderCountQuery(DynamoDBOperations dynamoDBOperations, boolean pageQuery); protected abstract boolean isOnlyHashKeySpecified(); @Override - public DynamoDBQueryCriteria withNoValuedCriteria(String propertyName, ComparisonOperator comparisonOperator) { + public DynamoDBQueryCriteria withNoValuedCriteria(String propertyName, + ComparisonOperator comparisonOperator) { Condition condition = createNoValueCondition(propertyName, comparisonOperator); return withCondition(propertyName, condition); @@ -486,31 +472,35 @@ public DynamoDBQueryCriteria withCondition(String propertyName, Condition return this; } - @SuppressWarnings({"deprecation", "unchecked"}) - protected Object getPropertyAttributeValue(final String propertyName, final V value) { - // TODO consider removing DynamoDBMarshaller code altogether as table model will handle accordingly - DynamoDBTypeConverter converter = (DynamoDBTypeConverter)entityInformation.getTypeConverterForProperty(propertyName); + @SuppressWarnings({"deprecation", "unchecked"}) + protected Object getPropertyAttributeValue(final String propertyName, final V value) { + // TODO consider removing DynamoDBMarshaller code altogether as table model will + // handle accordingly + DynamoDBTypeConverter converter = (DynamoDBTypeConverter) entityInformation + .getTypeConverterForProperty(propertyName); if (converter != null) { return converter.convert((V) value); } - DynamoDBMarshaller marshaller = (DynamoDBMarshaller) entityInformation.getMarshallerForProperty(propertyName); + DynamoDBMarshaller marshaller = (DynamoDBMarshaller) entityInformation + .getMarshallerForProperty(propertyName); - if (marshaller != null) { - return marshaller.marshall(value); - } else if (tableModel != null) { // purely here for testing as DynamoDBMapperTableModel cannot be mocked using Mockito + if (marshaller != null) { + return marshaller.marshall(value); + } else if (tableModel != null) { // purely here for testing as DynamoDBMapperTableModel cannot be mocked using + // Mockito String attributeName = getAttributeName(propertyName); - DynamoDBMapperFieldModel fieldModel = tableModel.field(attributeName); - if (fieldModel != null) { - return fieldModel.convert(value); - } - } + DynamoDBMapperFieldModel fieldModel = tableModel.field(attributeName); + if (fieldModel != null) { + return fieldModel.convert(value); + } + } - return value; - } + return value; + } protected Condition createNoValueCondition(String propertyName, ComparisonOperator comparisonOperator) { @@ -650,20 +640,21 @@ protected Condition createSingleValueCondition(String propertyName, ComparisonOp List attributeValueList = new ArrayList<>(); Object attributeValue = !alreadyMarshalledIfRequired ? getPropertyAttributeValue(propertyName, o) : o; if (ClassUtils.isAssignableValue(AttributeValue.class, attributeValue)) { - attributeValueList.add((AttributeValue) attributeValue); + attributeValueList.add((AttributeValue) attributeValue); } else { - boolean marshalled = !alreadyMarshalledIfRequired && attributeValue != o - && !entityInformation.isCompositeHashAndRangeKeyProperty(propertyName); + boolean marshalled = !alreadyMarshalledIfRequired && attributeValue != o + && !entityInformation.isCompositeHashAndRangeKeyProperty(propertyName); - Class targetPropertyType = marshalled ? String.class : propertyType; - attributeValueList = addAttributeValue(attributeValueList, attributeValue, propertyName, targetPropertyType, true); + Class targetPropertyType = marshalled ? String.class : propertyType; + attributeValueList = addAttributeValue(attributeValueList, attributeValue, propertyName, targetPropertyType, + true); } return new Condition().withComparisonOperator(comparisonOperator).withAttributeValueList(attributeValueList); } - protected Condition createCollectionCondition(String propertyName, ComparisonOperator comparisonOperator, Iterable o, - Class propertyType) { + protected Condition createCollectionCondition(String propertyName, ComparisonOperator comparisonOperator, + Iterable o, Class propertyType) { Assert.notNull(o, "Creating conditions on null property values not supported: please specify a value for '" + propertyName + "'"); @@ -671,15 +662,17 @@ protected Condition createCollectionCondition(String propertyName, ComparisonOpe boolean marshalled = false; for (Object object : o) { Object attributeValue = getPropertyAttributeValue(propertyName, object); - if (ClassUtils.isAssignableValue(AttributeValue.class, attributeValue)) { - attributeValueList.add((AttributeValue) attributeValue); - } else { - if (attributeValue != null) { - marshalled = attributeValue != object && !entityInformation.isCompositeHashAndRangeKeyProperty(propertyName); - } - Class targetPropertyType = marshalled ? String.class : propertyType; - attributeValueList = addAttributeValue(attributeValueList, attributeValue, propertyName, targetPropertyType, false); - } + if (ClassUtils.isAssignableValue(AttributeValue.class, attributeValue)) { + attributeValueList.add((AttributeValue) attributeValue); + } else { + if (attributeValue != null) { + marshalled = attributeValue != object + && !entityInformation.isCompositeHashAndRangeKeyProperty(propertyName); + } + Class targetPropertyType = marshalled ? String.class : propertyType; + attributeValueList = addAttributeValue(attributeValueList, attributeValue, propertyName, + targetPropertyType, false); + } } return new Condition().withComparisonOperator(comparisonOperator).withAttributeValueList(attributeValueList); diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBCountQueryCreator.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBCountQueryCreator.java index d5485e90..110845bc 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBCountQueryCreator.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBCountQueryCreator.java @@ -24,30 +24,27 @@ import java.util.Optional; -public class DynamoDBCountQueryCreator extends AbstractDynamoDBQueryCreator { +public class DynamoDBCountQueryCreator extends AbstractDynamoDBQueryCreator { private boolean pageQuery; - public DynamoDBCountQueryCreator(PartTree tree, - DynamoDBEntityInformation entityMetadata, - DynamoDBOperations dynamoDBOperations,boolean pageQuery) { + public DynamoDBCountQueryCreator(PartTree tree, DynamoDBEntityInformation entityMetadata, + DynamoDBOperations dynamoDBOperations, boolean pageQuery) { super(tree, entityMetadata, Optional.empty(), dynamoDBOperations); this.pageQuery = pageQuery; } - public DynamoDBCountQueryCreator(PartTree tree, - ParameterAccessor parameterAccessor, - DynamoDBEntityInformation entityMetadata, - DynamoDBOperations dynamoDBOperations,boolean pageQuery) { + public DynamoDBCountQueryCreator(PartTree tree, ParameterAccessor parameterAccessor, + DynamoDBEntityInformation entityMetadata, DynamoDBOperations dynamoDBOperations, boolean pageQuery) { super(tree, parameterAccessor, entityMetadata, Optional.empty(), dynamoDBOperations); this.pageQuery = pageQuery; } - + @Override protected Query complete(DynamoDBQueryCriteria criteria, Sort sort) { - - return criteria.buildCountQuery(dynamoDBOperations,pageQuery); + + return criteria.buildCountQuery(dynamoDBOperations, pageQuery); } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashAndRangeKeyCriteria.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashAndRangeKeyCriteria.java index 64d1afeb..2cb9bdbc 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashAndRangeKeyCriteria.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashAndRangeKeyCriteria.java @@ -69,9 +69,10 @@ protected boolean isRangeKeyProperty(String propertyName) { } public DynamoDBEntityWithHashAndRangeKeyCriteria( - DynamoDBIdIsHashAndRangeKeyEntityInformation entityInformation, DynamoDBMapperTableModel tableModel) { + DynamoDBIdIsHashAndRangeKeyEntityInformation entityInformation, + DynamoDBMapperTableModel tableModel) { - super(entityInformation, tableModel); + super(entityInformation, tableModel); this.rangeKeyPropertyName = entityInformation.getRangeKeyPropertyName(); this.indexRangeKeyPropertyNames = entityInformation.getIndexRangeKeyPropertyNames(); if (indexRangeKeyPropertyNames == null) { @@ -104,7 +105,7 @@ protected Query buildSingleEntityLoadQuery(DynamoDBOperations dynamoDBOperati return new SingleEntityLoadByHashAndRangeKeyQuery<>(dynamoDBOperations, entityInformation.getJavaType(), getHashKeyPropertyValue(), getRangeKeyPropertyValue()); } - + protected Query buildSingleEntityCountQuery(DynamoDBOperations dynamoDBOperations) { return new CountByHashAndRangeKeyQuery<>(dynamoDBOperations, entityInformation.getJavaType(), getHashKeyPropertyValue(), getRangeKeyPropertyValue()); @@ -114,15 +115,16 @@ private void checkComparisonOperatorPermittedForCompositeHashAndRangeKey(Compari if (!ComparisonOperator.EQ.equals(comparisonOperator) && !ComparisonOperator.CONTAINS.equals(comparisonOperator) && !ComparisonOperator.BEGINS_WITH.equals(comparisonOperator)) { - throw new UnsupportedOperationException("Only EQ,CONTAINS,BEGINS_WITH supported for composite id comparison"); + throw new UnsupportedOperationException( + "Only EQ,CONTAINS,BEGINS_WITH supported for composite id comparison"); } } @SuppressWarnings("unchecked") @Override - public DynamoDBQueryCriteria withSingleValueCriteria(String propertyName, ComparisonOperator comparisonOperator, - Object value, Class propertyType) { + public DynamoDBQueryCriteria withSingleValueCriteria(String propertyName, + ComparisonOperator comparisonOperator, Object value, Class propertyType) { if (entityInformation.isCompositeHashAndRangeKeyProperty(propertyName)) { checkComparisonOperatorPermittedForCompositeHashAndRangeKey(comparisonOperator); @@ -152,7 +154,7 @@ public DynamoDBQueryExpression buildQueryExpression() { Condition rangeKeyCondition = createSingleValueCondition(getRangeKeyPropertyName(), ComparisonOperator.EQ, getRangeKeyAttributeValue(), getRangeKeyAttributeValue().getClass(), true); queryExpression.withRangeKeyCondition(getRangeKeyAttributeName(), rangeKeyCondition); - applySortIfSpecified(queryExpression, Arrays.asList(new String[] { getRangeKeyPropertyName() })); + applySortIfSpecified(queryExpression, Arrays.asList(new String[]{getRangeKeyPropertyName()})); } else if (isOnlyASingleAttributeConditionAndItIsOnEitherRangeOrIndexRangeKey() || (isApplicableForGlobalSecondaryIndex())) { @@ -181,7 +183,7 @@ public DynamoDBQueryExpression buildQueryExpression() { queryExpression.setIndexName(getGlobalSecondaryIndexName()); } } else { - applySortIfSpecified(queryExpression, Arrays.asList(new String[] { getRangeKeyPropertyName() })); + applySortIfSpecified(queryExpression, Arrays.asList(new String[]{getRangeKeyPropertyName()})); } if (projection.isPresent()) { @@ -194,11 +196,12 @@ public DynamoDBQueryExpression buildQueryExpression() { protected List getRangeKeyConditions() { List rangeKeyConditions = null; - if (isApplicableForGlobalSecondaryIndex() - && entityInformation.getGlobalSecondaryIndexNamesByPropertyName().keySet().contains(getRangeKeyPropertyName())) { - rangeKeyConditions = getRangeKeyAttributeValue() == null ? null : Arrays.asList(createSingleValueCondition( - getRangeKeyPropertyName(), ComparisonOperator.EQ, getRangeKeyAttributeValue(), getRangeKeyAttributeValue() - .getClass(), true)); + if (isApplicableForGlobalSecondaryIndex() && entityInformation.getGlobalSecondaryIndexNamesByPropertyName() + .keySet().contains(getRangeKeyPropertyName())) { + rangeKeyConditions = getRangeKeyAttributeValue() == null + ? null + : Arrays.asList(createSingleValueCondition(getRangeKeyPropertyName(), ComparisonOperator.EQ, + getRangeKeyAttributeValue(), getRangeKeyAttributeValue().getClass(), true)); } return rangeKeyConditions; @@ -207,37 +210,41 @@ protected List getRangeKeyConditions() { protected Query buildFinderQuery(DynamoDBOperations dynamoDBOperations) { if (isApplicableForQuery()) { if (isApplicableForGlobalSecondaryIndex()) { - String tableName = dynamoDBOperations.getOverriddenTableName(clazz, entityInformation.getDynamoDBTableName()); + String tableName = dynamoDBOperations.getOverriddenTableName(clazz, + entityInformation.getDynamoDBTableName()); QueryRequest queryRequest = buildQueryRequest(tableName, getGlobalSecondaryIndexName(), getHashKeyAttributeName(), getRangeKeyAttributeName(), this.getRangeKeyPropertyName(), getHashKeyConditions(), getRangeKeyConditions()); - return new MultipleEntityQueryRequestQuery<>(dynamoDBOperations,entityInformation.getJavaType(), queryRequest); + return new MultipleEntityQueryRequestQuery<>(dynamoDBOperations, entityInformation.getJavaType(), + queryRequest); } else { DynamoDBQueryExpression queryExpression = buildQueryExpression(); - return new MultipleEntityQueryExpressionQuery<>(dynamoDBOperations, entityInformation.getJavaType(), queryExpression); + return new MultipleEntityQueryExpressionQuery<>(dynamoDBOperations, entityInformation.getJavaType(), + queryExpression); } } else { return new MultipleEntityScanExpressionQuery<>(dynamoDBOperations, clazz, buildScanExpression()); } } - - - protected Query buildFinderCountQuery(DynamoDBOperations dynamoDBOperations,boolean pageQuery) { + + protected Query buildFinderCountQuery(DynamoDBOperations dynamoDBOperations, boolean pageQuery) { if (isApplicableForQuery()) { if (isApplicableForGlobalSecondaryIndex()) { - String tableName = dynamoDBOperations.getOverriddenTableName(clazz, entityInformation.getDynamoDBTableName()); + String tableName = dynamoDBOperations.getOverriddenTableName(clazz, + entityInformation.getDynamoDBTableName()); QueryRequest queryRequest = buildQueryRequest(tableName, getGlobalSecondaryIndexName(), getHashKeyAttributeName(), getRangeKeyAttributeName(), this.getRangeKeyPropertyName(), getHashKeyConditions(), getRangeKeyConditions()); return new QueryRequestCountQuery(dynamoDBOperations, queryRequest); - + } else { DynamoDBQueryExpression queryExpression = buildQueryExpression(); - return new QueryExpressionCountQuery<>(dynamoDBOperations, entityInformation.getJavaType(), queryExpression); - + return new QueryExpressionCountQuery<>(dynamoDBOperations, entityInformation.getJavaType(), + queryExpression); + } } else { - return new ScanExpressionCountQuery(dynamoDBOperations, clazz, buildScanExpression(),pageQuery); + return new ScanExpressionCountQuery(dynamoDBOperations, clazz, buildScanExpression(), pageQuery); } } @@ -264,18 +271,15 @@ protected boolean isOnlyASingleAttributeConditionAndItIsOnEitherRangeOrIndexRang return isOnlyASingleAttributeConditionAndItIsOnEitherRangeOrIndexRangeKey; } - - @Override protected boolean hasIndexHashKeyEqualCondition() { - + boolean hasCondition = super.hasIndexHashKeyEqualCondition(); - if (!hasCondition) - { - if (rangeKeyAttributeValue != null && entityInformation.isGlobalIndexHashKeyProperty(rangeKeyPropertyName)) - { - hasCondition = true; + if (!hasCondition) { + if (rangeKeyAttributeValue != null + && entityInformation.isGlobalIndexHashKeyProperty(rangeKeyPropertyName)) { + hasCondition = true; } } return hasCondition; @@ -283,12 +287,11 @@ protected boolean hasIndexHashKeyEqualCondition() { @Override protected boolean hasIndexRangeKeyCondition() { - boolean hasCondition = super.hasIndexRangeKeyCondition(); - if (!hasCondition) - { - if (rangeKeyAttributeValue != null && entityInformation.isGlobalIndexRangeKeyProperty(rangeKeyPropertyName)) - { - hasCondition = true; + boolean hasCondition = super.hasIndexRangeKeyCondition(); + if (!hasCondition) { + if (rangeKeyAttributeValue != null + && entityInformation.isGlobalIndexRangeKeyProperty(rangeKeyPropertyName)) { + hasCondition = true; } } return hasCondition; @@ -296,11 +299,11 @@ protected boolean hasIndexRangeKeyCondition() { protected boolean isApplicableForGlobalSecondaryIndex() { boolean global = super.isApplicableForGlobalSecondaryIndex(); - if (global && getRangeKeyAttributeValue() != null - && !entityInformation.getGlobalSecondaryIndexNamesByPropertyName().keySet().contains(getRangeKeyPropertyName())) { + if (global && getRangeKeyAttributeValue() != null && !entityInformation + .getGlobalSecondaryIndexNamesByPropertyName().keySet().contains(getRangeKeyPropertyName())) { return false; } - + return global; } @@ -317,9 +320,10 @@ protected String getGlobalSecondaryIndexName() { // then set the index range key to be that associated with the range key if (globalSecondaryIndexName == null) { if (this.hashKeyAttributeValue == null && getRangeKeyAttributeValue() != null) { - String[] rangeKeyIndexNames = entityInformation.getGlobalSecondaryIndexNamesByPropertyName().get( - this.getRangeKeyPropertyName()); - globalSecondaryIndexName = rangeKeyIndexNames != null && rangeKeyIndexNames.length > 0 ? rangeKeyIndexNames[0] + String[] rangeKeyIndexNames = entityInformation.getGlobalSecondaryIndexNamesByPropertyName() + .get(this.getRangeKeyPropertyName()); + globalSecondaryIndexName = rangeKeyIndexNames != null && rangeKeyIndexNames.length > 0 + ? rangeKeyIndexNames[0] : null; } } @@ -329,7 +333,8 @@ protected String getGlobalSecondaryIndexName() { public boolean isApplicableForQuery() { return isOnlyHashKeySpecified() - || (isHashKeySpecified() && isOnlyASingleAttributeConditionAndItIsOnEitherRangeOrIndexRangeKey() && comparisonOperatorsPermittedForQuery()) + || (isHashKeySpecified() && isOnlyASingleAttributeConditionAndItIsOnEitherRangeOrIndexRangeKey() + && comparisonOperatorsPermittedForQuery()) || isApplicableForGlobalSecondaryIndex(); } @@ -340,16 +345,14 @@ public DynamoDBScanExpression buildScanExpression() { DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); if (isHashKeySpecified()) { - scanExpression.addFilterCondition( - getHashKeyAttributeName(), - createSingleValueCondition(getHashKeyPropertyName(), ComparisonOperator.EQ, getHashKeyAttributeValue(), - getHashKeyAttributeValue().getClass(), true)); + scanExpression.addFilterCondition(getHashKeyAttributeName(), + createSingleValueCondition(getHashKeyPropertyName(), ComparisonOperator.EQ, + getHashKeyAttributeValue(), getHashKeyAttributeValue().getClass(), true)); } if (isRangeKeySpecified()) { - scanExpression.addFilterCondition( - getRangeKeyAttributeName(), - createSingleValueCondition(getRangeKeyPropertyName(), ComparisonOperator.EQ, getRangeKeyAttributeValue(), - getRangeKeyAttributeValue().getClass(), true)); + scanExpression.addFilterCondition(getRangeKeyAttributeName(), + createSingleValueCondition(getRangeKeyPropertyName(), ComparisonOperator.EQ, + getRangeKeyAttributeValue(), getRangeKeyAttributeValue().getClass(), true)); } for (Map.Entry> conditionEntry : attributeConditions.entrySet()) { for (Condition condition : conditionEntry.getValue()) { @@ -389,7 +392,8 @@ public DynamoDBQueryCriteria withPropertyEquals(String propertyName, Obje } return this; } else { - Condition condition = createSingleValueCondition(propertyName, ComparisonOperator.EQ, value, propertyType, false); + Condition condition = createSingleValueCondition(propertyName, ComparisonOperator.EQ, value, propertyType, + false); return withCondition(propertyName, condition); } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashKeyOnlyCriteria.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashKeyOnlyCriteria.java index 6cb74209..83706f36 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashKeyOnlyCriteria.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashKeyOnlyCriteria.java @@ -42,7 +42,8 @@ public class DynamoDBEntityWithHashKeyOnlyCriteria extends AbstractDynamo private DynamoDBEntityInformation entityInformation; - public DynamoDBEntityWithHashKeyOnlyCriteria(DynamoDBEntityInformation entityInformation, DynamoDBMapperTableModel tableModel) { + public DynamoDBEntityWithHashKeyOnlyCriteria(DynamoDBEntityInformation entityInformation, + DynamoDBMapperTableModel tableModel) { super(entityInformation, tableModel); this.entityInformation = entityInformation; } @@ -50,7 +51,7 @@ public DynamoDBEntityWithHashKeyOnlyCriteria(DynamoDBEntityInformation en protected Query buildSingleEntityLoadQuery(DynamoDBOperations dynamoDBOperations) { return new SingleEntityLoadByHashKeyQuery<>(dynamoDBOperations, clazz, getHashKeyPropertyValue()); } - + protected Query buildSingleEntityCountQuery(DynamoDBOperations dynamoDBOperations) { return new CountByHashKeyQuery<>(dynamoDBOperations, clazz, getHashKeyPropertyValue()); } @@ -59,25 +60,28 @@ protected Query buildFinderQuery(DynamoDBOperations dynamoDBOperations) { if (isApplicableForGlobalSecondaryIndex()) { List hashKeyConditions = getHashKeyConditions(); - QueryRequest queryRequest = buildQueryRequest(dynamoDBOperations.getOverriddenTableName(clazz, entityInformation.getDynamoDBTableName()), + QueryRequest queryRequest = buildQueryRequest( + dynamoDBOperations.getOverriddenTableName(clazz, entityInformation.getDynamoDBTableName()), getGlobalSecondaryIndexName(), getHashKeyAttributeName(), null, null, hashKeyConditions, null); - return new MultipleEntityQueryRequestQuery<>(dynamoDBOperations,entityInformation.getJavaType(), queryRequest); + return new MultipleEntityQueryRequestQuery<>(dynamoDBOperations, entityInformation.getJavaType(), + queryRequest); } else { return new MultipleEntityScanExpressionQuery<>(dynamoDBOperations, clazz, buildScanExpression()); } } - - protected Query buildFinderCountQuery(DynamoDBOperations dynamoDBOperations,boolean pageQuery) { + + protected Query buildFinderCountQuery(DynamoDBOperations dynamoDBOperations, boolean pageQuery) { if (isApplicableForGlobalSecondaryIndex()) { List hashKeyConditions = getHashKeyConditions(); - QueryRequest queryRequest = buildQueryRequest(dynamoDBOperations.getOverriddenTableName(clazz, entityInformation.getDynamoDBTableName()), + QueryRequest queryRequest = buildQueryRequest( + dynamoDBOperations.getOverriddenTableName(clazz, entityInformation.getDynamoDBTableName()), getGlobalSecondaryIndexName(), getHashKeyAttributeName(), null, null, hashKeyConditions, null); queryRequest.setSelect(Select.COUNT); return new QueryRequestCountQuery(dynamoDBOperations, queryRequest); } else { - return new ScanExpressionCountQuery<>(dynamoDBOperations, clazz, buildScanExpression(),pageQuery); + return new ScanExpressionCountQuery<>(dynamoDBOperations, clazz, buildScanExpression(), pageQuery); } } @@ -97,10 +101,9 @@ public DynamoDBScanExpression buildScanExpression() { DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); if (isHashKeySpecified()) { - scanExpression.addFilterCondition( - getHashKeyAttributeName(), - createSingleValueCondition(getHashKeyPropertyName(), ComparisonOperator.EQ, getHashKeyAttributeValue(), - getHashKeyAttributeValue().getClass(), true)); + scanExpression.addFilterCondition(getHashKeyAttributeName(), + createSingleValueCondition(getHashKeyPropertyName(), ComparisonOperator.EQ, + getHashKeyAttributeValue(), getHashKeyAttributeValue().getClass(), true)); } for (Map.Entry> conditionEntry : attributeConditions.entrySet()) { @@ -121,7 +124,8 @@ public DynamoDBQueryCriteria withPropertyEquals(String propertyName, Obje if (isHashKeyProperty(propertyName)) { return withHashKeyEquals(value); } else { - Condition condition = createSingleValueCondition(propertyName, ComparisonOperator.EQ, value, propertyType, false); + Condition condition = createSingleValueCondition(propertyName, ComparisonOperator.EQ, value, propertyType, + false); return withCondition(propertyName, condition); } } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryCreator.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryCreator.java index 289c7e0f..ef43e37a 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryCreator.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryCreator.java @@ -24,16 +24,14 @@ import java.util.Optional; -public class DynamoDBQueryCreator extends AbstractDynamoDBQueryCreator { +public class DynamoDBQueryCreator extends AbstractDynamoDBQueryCreator { - public DynamoDBQueryCreator(PartTree tree, - ParameterAccessor parameterAccessor, - DynamoDBEntityInformation entityMetadata, - Optional projection, + public DynamoDBQueryCreator(PartTree tree, ParameterAccessor parameterAccessor, + DynamoDBEntityInformation entityMetadata, Optional projection, DynamoDBOperations dynamoDBOperations) { super(tree, parameterAccessor, entityMetadata, projection, dynamoDBOperations); } - + @Override protected Query complete(DynamoDBQueryCriteria criteria, Sort sort) { criteria.withSort(sort); diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryLookupStrategy.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryLookupStrategy.java index b69e8da3..53406444 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryLookupStrategy.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryLookupStrategy.java @@ -25,7 +25,6 @@ import java.lang.reflect.Method; - /** * @author Michael Lavelle * @author Sebastian Just @@ -40,11 +39,11 @@ private DynamoDBQueryLookupStrategy() { } /** - * Base class for {@link QueryLookupStrategy} implementations that need - * access to an {@link com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper}. + * Base class for {@link QueryLookupStrategy} implementations that need access + * to an {@link com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper}. * * @author Michael Lavelle - * @author Sebastian Just + * @author Sebastian Just */ private abstract static class AbstractQueryLookupStrategy implements QueryLookupStrategy { @@ -64,20 +63,22 @@ public AbstractQueryLookupStrategy(DynamoDBOperations dynamoDBOperations) { * org.springframework.data.repository.core.NamedQueries) */ @Override - public final RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory, NamedQueries namedQueries) { + public final RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory, + NamedQueries namedQueries) { - return createDynamoDBQuery(method, metadata, factory, metadata.getDomainType(), metadata.getIdType(), namedQueries); + return createDynamoDBQuery(method, metadata, factory, metadata.getDomainType(), metadata.getIdType(), + namedQueries); } - protected abstract RepositoryQuery createDynamoDBQuery(Method method, - RepositoryMetadata metadata, ProjectionFactory factory, Class entityClass, Class idClass, NamedQueries namedQueries); + protected abstract RepositoryQuery createDynamoDBQuery(Method method, RepositoryMetadata metadata, + ProjectionFactory factory, Class entityClass, Class idClass, NamedQueries namedQueries); } /** * {@link QueryLookupStrategy} to create a query from the method name. * * @author Michael Lavelle - * @author Sebastian Just + * @author Sebastian Just */ private static class CreateQueryLookupStrategy extends AbstractQueryLookupStrategy { @@ -87,24 +88,25 @@ public CreateQueryLookupStrategy(DynamoDBOperations dynamoDBOperations) { } @Override - protected RepositoryQuery createDynamoDBQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory, - Class entityClass, Class idClass, NamedQueries namedQueries) { + protected RepositoryQuery createDynamoDBQuery(Method method, RepositoryMetadata metadata, + ProjectionFactory factory, Class entityClass, Class idClass, NamedQueries namedQueries) { try { - return new PartTreeDynamoDBQuery(dynamoDBOperations, new DynamoDBQueryMethod(method, metadata, factory)); + return new PartTreeDynamoDBQuery(dynamoDBOperations, + new DynamoDBQueryMethod(method, metadata, factory)); } catch (IllegalArgumentException e) { - throw new IllegalArgumentException(String.format("Could not create query metamodel for method %s!", - method.toString()), e); + throw new IllegalArgumentException( + String.format("Could not create query metamodel for method %s!", method.toString()), e); } } } /** - * {@link QueryLookupStrategy} that tries to detect a declared query - * declared via {@link org.socialsignin.spring.data.dynamodb.query.Query} annotation + * {@link QueryLookupStrategy} that tries to detect a declared query declared + * via {@link org.socialsignin.spring.data.dynamodb.query.Query} annotation * * @author Michael Lavelle - * @author Sebastian Just + * @author Sebastian Just */ private static class DeclaredQueryLookupStrategy extends AbstractQueryLookupStrategy { @@ -114,8 +116,8 @@ public DeclaredQueryLookupStrategy(DynamoDBOperations dynamoDBOperations) { } @Override - protected RepositoryQuery createDynamoDBQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory, - Class entityClass, Class idClass, NamedQueries namedQueries) { + protected RepositoryQuery createDynamoDBQuery(Method method, RepositoryMetadata metadata, + ProjectionFactory factory, Class entityClass, Class idClass, NamedQueries namedQueries) { throw new UnsupportedOperationException("Declared Queries not supported at this time"); } @@ -123,11 +125,11 @@ protected RepositoryQuery createDynamoDBQuery(Method method, RepositoryM /** * {@link QueryLookupStrategy} to try to detect a declared query first ( - * {@link org.springframework.data.jpa.repository.Query}. In case none is - * found we fall back on query creation. + * {@link org.springframework.data.jpa.repository.Query}. In case none is found + * we fall back on query creation. * * @author Michael Lavelle - * @author Sebastian Just + * @author Sebastian Just */ private static class CreateIfNotFoundQueryLookupStrategy extends AbstractQueryLookupStrategy { @@ -142,12 +144,13 @@ public CreateIfNotFoundQueryLookupStrategy(DynamoDBOperations dynamoDBOperations } @Override - protected RepositoryQuery createDynamoDBQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory, - Class entityClass, Class idClass, NamedQueries namedQueries) { + protected RepositoryQuery createDynamoDBQuery(Method method, RepositoryMetadata metadata, + ProjectionFactory factory, Class entityClass, Class idClass, NamedQueries namedQueries) { try { return strategy.createDynamoDBQuery(method, metadata, factory, entityClass, idClass, namedQueries); } catch (IllegalStateException | UnsupportedOperationException e) { - return createStrategy.createDynamoDBQuery(method, metadata, factory, entityClass, idClass, namedQueries); + return createStrategy.createDynamoDBQuery(method, metadata, factory, entityClass, idClass, + namedQueries); } } @@ -155,10 +158,13 @@ protected RepositoryQuery createDynamoDBQuery(Method method, RepositoryM /** * Creates a {@link QueryLookupStrategy} for the given - * {@link com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper} and {@link Key}. + * {@link com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper} and + * {@link Key}. * - * @param dynamoDBOperations The current operation - * @param key The key of the entity + * @param dynamoDBOperations + * The current operation + * @param key + * The key of the entity * @return The created {@link QueryLookupStrategy} */ public static QueryLookupStrategy create(DynamoDBOperations dynamoDBOperations, Key key) { @@ -168,14 +174,14 @@ public static QueryLookupStrategy create(DynamoDBOperations dynamoDBOperations, } switch (key) { - case CREATE: - return new CreateQueryLookupStrategy(dynamoDBOperations); - case USE_DECLARED_QUERY: - throw new IllegalArgumentException(String.format("Unsupported query lookup strategy %s!", key)); - case CREATE_IF_NOT_FOUND: - return new CreateIfNotFoundQueryLookupStrategy(dynamoDBOperations); - default: - throw new IllegalArgumentException(String.format("Unsupported query lookup strategy %s!", key)); + case CREATE : + return new CreateQueryLookupStrategy(dynamoDBOperations); + case USE_DECLARED_QUERY : + throw new IllegalArgumentException(String.format("Unsupported query lookup strategy %s!", key)); + case CREATE_IF_NOT_FOUND : + return new CreateIfNotFoundQueryLookupStrategy(dynamoDBOperations); + default : + throw new IllegalArgumentException(String.format("Unsupported query lookup strategy %s!", key)); } } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryMethod.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryMethod.java index 04d556d5..36304f4c 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryMethod.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryMethod.java @@ -43,7 +43,8 @@ public DynamoDBQueryMethod(Method method, RepositoryMetadata metadata, Projectio super(method, metadata, factory); this.method = method; this.scanEnabledForRepository = metadata.getRepositoryInterface().isAnnotationPresent(EnableScan.class); - this.scanCountEnabledForRepository = metadata.getRepositoryInterface().isAnnotationPresent(EnableScanCount.class); + this.scanCountEnabledForRepository = metadata.getRepositoryInterface() + .isAnnotationPresent(EnableScanCount.class); Query query = method.getAnnotation(Query.class); if (query != null) { @@ -71,7 +72,7 @@ Class getReturnType() { public boolean isScanEnabled() { return scanEnabledForRepository || method.isAnnotationPresent(EnableScan.class); } - + public boolean isScanCountEnabled() { return scanCountEnabledForRepository || method.isAnnotationPresent(EnableScanCount.class); } @@ -80,11 +81,10 @@ public boolean isScanCountEnabled() { * (non-Javadoc) * * @see - * org.springframework.data.repository.query.QueryMethod#getEntityInformation - * () + * org.springframework.data.repository.query.QueryMethod#getEntityInformation () */ @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) public DynamoDBEntityInformation getEntityInformation() { return new DynamoDBEntityMetadataSupport(getDomainClass()).getEntityInformation(); } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/PartTreeDynamoDBQuery.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/PartTreeDynamoDBQuery.java index 6664b533..c0f9ded5 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/PartTreeDynamoDBQuery.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/query/PartTreeDynamoDBQuery.java @@ -41,8 +41,9 @@ protected DynamoDBQueryCreator createQueryCreator(ParametersParameterAcce return new DynamoDBQueryCreator<>(tree, accessor, getQueryMethod().getEntityInformation(), getQueryMethod().getProjectionExpression(), dynamoDBOperations); } - - protected DynamoDBCountQueryCreator createCountQueryCreator(ParametersParameterAccessor accessor,boolean pageQuery) { + + protected DynamoDBCountQueryCreator createCountQueryCreator(ParametersParameterAccessor accessor, + boolean pageQuery) { return new DynamoDBCountQueryCreator<>(tree, accessor, getQueryMethod().getEntityInformation(), dynamoDBOperations, pageQuery); } @@ -55,28 +56,30 @@ public Query doCreateQuery(Object[] values) { return queryCreator.createQuery(); } - + @Override - public Query doCreateCountQuery(Object[] values,boolean pageQuery) { + public Query doCreateCountQuery(Object[] values, boolean pageQuery) { ParametersParameterAccessor accessor = new ParametersParameterAccessor(parameters, values); - DynamoDBCountQueryCreator queryCreator = createCountQueryCreator(accessor,pageQuery); + DynamoDBCountQueryCreator queryCreator = createCountQueryCreator(accessor, pageQuery); return queryCreator.createQuery(); } - @Override - protected boolean isCountQuery() { - return tree.isCountProjection(); - } + @Override + protected boolean isCountQuery() { + return tree.isCountProjection(); + } - @Override - protected boolean isExistsQuery() { - return tree.isExistsProjection(); - } + @Override + protected boolean isExistsQuery() { + return tree.isExistsProjection(); + } - @Override - protected boolean isDeleteQuery() { return tree.isDelete(); } + @Override + protected boolean isDeleteQuery() { + return tree.isDelete(); + } @Override protected Integer getResultsRestrictionIfApplicable() { diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/CompositeIdHashAndRangeKeyExtractor.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/CompositeIdHashAndRangeKeyExtractor.java index 3830ca9e..785ae899 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/CompositeIdHashAndRangeKeyExtractor.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/CompositeIdHashAndRangeKeyExtractor.java @@ -35,12 +35,9 @@ public CompositeIdHashAndRangeKeyExtractor(Class idClass) { @Override public H getHashKey(ID id) { Method method = hashAndRangeKeyMethodExtractor.getHashKeyMethod(); - if (method != null) - { + if (method != null) { return (H) ReflectionUtils.invokeMethod(method, id); - } - else - { + } else { return (H) ReflectionUtils.getField(hashAndRangeKeyMethodExtractor.getHashKeyField(), id); } } @@ -48,13 +45,11 @@ public H getHashKey(ID id) { @Override public Object getRangeKey(ID id) { Method method = hashAndRangeKeyMethodExtractor.getRangeKeyMethod(); - if (method != null) - { + if (method != null) { return ReflectionUtils.invokeMethod(method, id); - } - else - { + } else { return ReflectionUtils.getField(hashAndRangeKeyMethodExtractor.getRangeKeyField(), id); - } } + } + } } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityInformation.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityInformation.java index 0296a63d..b117d5ef 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityInformation.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityInformation.java @@ -32,8 +32,10 @@ * @author Michael Lavelle * @author Sebastian Just */ -public interface DynamoDBEntityInformation extends EntityInformation, - DynamoDBHashKeyExtractingEntityMetadata { +public interface DynamoDBEntityInformation + extends + EntityInformation, + DynamoDBHashKeyExtractingEntityMetadata { default boolean isRangeKeyAware() { return false; diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityMetadataSupport.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityMetadataSupport.java index e37ca0e0..a1ce1458 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityMetadataSupport.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityMetadataSupport.java @@ -63,7 +63,8 @@ public String getDynamoDBTableName() { } /** - * Creates a new {@link DynamoDBEntityMetadataSupport} for the given domain type. + * Creates a new {@link DynamoDBEntityMetadataSupport} for the given domain + * type. * * @param domainType * must not be {@literal null}. @@ -80,7 +81,7 @@ public DynamoDBEntityMetadataSupport(final Class domainType) { this.globalIndexRangeKeyPropertyNames = new ArrayList<>(); ReflectionUtils.doWithMethods(domainType, new MethodCallback() { @Override - public void doWith(Method method) { + public void doWith(Method method) { if (method.getAnnotation(DynamoDBHashKey.class) != null) { hashKeyPropertyName = getPropertyNameForAccessorMethod(method); } @@ -100,7 +101,7 @@ public void doWith(Method method) { }); ReflectionUtils.doWithFields(domainType, new FieldCallback() { @Override - public void doWith(Field field) { + public void doWith(Field field) { if (field.getAnnotation(DynamoDBHashKey.class) != null) { hashKeyPropertyName = getPropertyNameForField(field); } @@ -135,8 +136,7 @@ public DynamoDBEntityInformation getEntityInformation() { /* * (non-Javadoc) * - * @see - * org.springframework.data.repository.core.EntityMetadata#getJavaType() + * @see org.springframework.data.repository.core.EntityMetadata#getJavaType() */ @Override public Class getJavaType() { @@ -144,7 +144,7 @@ public Class getJavaType() { } @Override - public boolean isHashKeyProperty(String propertyName) { + public boolean isHashKeyProperty(String propertyName) { return hashKeyPropertyName.equals(propertyName); } @@ -296,17 +296,18 @@ public DynamoDBMarshaller getMarshallerForProperty(final String propertyName) annotation = method.getAnnotation(DynamoDBMarshalling.class); } - if(annotation == null) { + if (annotation == null) { Field field = findField(propertyName); - if(field != null) { + if (field != null) { annotation = field.getAnnotation(DynamoDBMarshalling.class); } } - if(annotation != null) { + if (annotation != null) { try { return annotation.marshallerClass().getDeclaredConstructor().newInstance(); - } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { + } catch (InstantiationException | IllegalAccessException | NoSuchMethodException + | InvocationTargetException e) { throw new RuntimeException(e); } } @@ -328,7 +329,7 @@ public DynamoDBMarshaller getMarshallerForProperty(final String propertyName) if (field != null) { annotation = field.getAnnotation(DynamoDBTypeConverted.class); } - } + } if (annotation != null) { try { @@ -371,8 +372,8 @@ private void addGlobalSecondaryIndexNames(Method method, DynamoDBIndexRangeKey d && dynamoDBIndexRangeKey.globalSecondaryIndexNames().length > 0) { String propertyName = getPropertyNameForAccessorMethod(method); - globalSecondaryIndexNames.put(propertyName, method.getAnnotation(DynamoDBIndexRangeKey.class) - .globalSecondaryIndexNames()); + globalSecondaryIndexNames.put(propertyName, + method.getAnnotation(DynamoDBIndexRangeKey.class).globalSecondaryIndexNames()); globalIndexRangeKeyPropertyNames.add(propertyName); } @@ -380,7 +381,7 @@ private void addGlobalSecondaryIndexNames(Method method, DynamoDBIndexRangeKey d && dynamoDBIndexRangeKey.globalSecondaryIndexName().trim().length() > 0) { String propertyName = getPropertyNameForAccessorMethod(method); globalSecondaryIndexNames.put(propertyName, - new String[] { method.getAnnotation(DynamoDBIndexRangeKey.class).globalSecondaryIndexName() }); + new String[]{method.getAnnotation(DynamoDBIndexRangeKey.class).globalSecondaryIndexName()}); globalIndexRangeKeyPropertyNames.add(propertyName); } @@ -393,8 +394,8 @@ private void addGlobalSecondaryIndexNames(Field field, DynamoDBIndexRangeKey dyn && dynamoDBIndexRangeKey.globalSecondaryIndexNames().length > 0) { String propertyName = getPropertyNameForField(field); - globalSecondaryIndexNames.put(propertyName, field.getAnnotation(DynamoDBIndexRangeKey.class) - .globalSecondaryIndexNames()); + globalSecondaryIndexNames.put(propertyName, + field.getAnnotation(DynamoDBIndexRangeKey.class).globalSecondaryIndexNames()); globalIndexRangeKeyPropertyNames.add(propertyName); } @@ -402,7 +403,7 @@ private void addGlobalSecondaryIndexNames(Field field, DynamoDBIndexRangeKey dyn && dynamoDBIndexRangeKey.globalSecondaryIndexName().trim().length() > 0) { String propertyName = getPropertyNameForField(field); globalSecondaryIndexNames.put(propertyName, - new String[] { field.getAnnotation(DynamoDBIndexRangeKey.class).globalSecondaryIndexName() }); + new String[]{field.getAnnotation(DynamoDBIndexRangeKey.class).globalSecondaryIndexName()}); globalIndexRangeKeyPropertyNames.add(propertyName); } @@ -415,8 +416,8 @@ private void addGlobalSecondaryIndexNames(Method method, DynamoDBIndexHashKey dy && dynamoDBIndexHashKey.globalSecondaryIndexNames().length > 0) { String propertyName = getPropertyNameForAccessorMethod(method); - globalSecondaryIndexNames.put(propertyName, method.getAnnotation(DynamoDBIndexHashKey.class) - .globalSecondaryIndexNames()); + globalSecondaryIndexNames.put(propertyName, + method.getAnnotation(DynamoDBIndexHashKey.class).globalSecondaryIndexNames()); globalIndexHashKeyPropertyNames.add(propertyName); } @@ -425,7 +426,7 @@ private void addGlobalSecondaryIndexNames(Method method, DynamoDBIndexHashKey dy String propertyName = getPropertyNameForAccessorMethod(method); globalSecondaryIndexNames.put(propertyName, - new String[] { method.getAnnotation(DynamoDBIndexHashKey.class).globalSecondaryIndexName() }); + new String[]{method.getAnnotation(DynamoDBIndexHashKey.class).globalSecondaryIndexName()}); globalIndexHashKeyPropertyNames.add(propertyName); } @@ -437,8 +438,8 @@ private void addGlobalSecondaryIndexNames(Field field, DynamoDBIndexHashKey dyna && dynamoDBIndexHashKey.globalSecondaryIndexNames().length > 0) { String propertyName = getPropertyNameForField(field); - globalSecondaryIndexNames.put(propertyName, field.getAnnotation(DynamoDBIndexHashKey.class) - .globalSecondaryIndexNames()); + globalSecondaryIndexNames.put(propertyName, + field.getAnnotation(DynamoDBIndexHashKey.class).globalSecondaryIndexNames()); globalIndexHashKeyPropertyNames.add(propertyName); } @@ -447,7 +448,7 @@ private void addGlobalSecondaryIndexNames(Field field, DynamoDBIndexHashKey dyna String propertyName = getPropertyNameForField(field); globalSecondaryIndexNames.put(propertyName, - new String[] { field.getAnnotation(DynamoDBIndexHashKey.class).globalSecondaryIndexName() }); + new String[]{field.getAnnotation(DynamoDBIndexHashKey.class).globalSecondaryIndexName()}); globalIndexHashKeyPropertyNames.add(propertyName); } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyExtractingEntityMetadata.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyExtractingEntityMetadata.java index 9fb03f60..7e678c7b 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyExtractingEntityMetadata.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyExtractingEntityMetadata.java @@ -23,8 +23,9 @@ * @author Michael Lavelle * @author Sebastian Just */ -public interface DynamoDBHashAndRangeKeyExtractingEntityMetadata extends - DynamoDBHashKeyExtractingEntityMetadata { +public interface DynamoDBHashAndRangeKeyExtractingEntityMetadata + extends + DynamoDBHashKeyExtractingEntityMetadata { HashAndRangeKeyExtractor getHashAndRangeKeyExtractor(Class idClass); diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl.java index 02790dea..02dfb6b4 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl.java @@ -33,8 +33,9 @@ * @author Michael Lavelle * @author Sebastian Just */ -public class DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl extends - DynamoDBEntityMetadataSupport implements DynamoDBHashAndRangeKeyExtractingEntityMetadata { +public class DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl extends DynamoDBEntityMetadataSupport + implements + DynamoDBHashAndRangeKeyExtractingEntityMetadata { private DynamoDBHashAndRangeKeyMethodExtractor hashAndRangeKeyMethodExtractor; @@ -49,7 +50,8 @@ public void doWith(Method method) { if (method.getAnnotation(DynamoDBHashKey.class) != null) { String setterMethodName = toSetterMethodNameFromAccessorMethod(method); if (setterMethodName != null) { - hashKeySetterMethod = ReflectionUtils.findMethod(domainType, setterMethodName, method.getReturnType()); + hashKeySetterMethod = ReflectionUtils.findMethod(domainType, setterMethodName, + method.getReturnType()); } } } @@ -57,14 +59,16 @@ public void doWith(Method method) { ReflectionUtils.doWithFields(domainType, new FieldCallback() { public void doWith(Field field) { if (field.getAnnotation(DynamoDBHashKey.class) != null) { - + hashKeyField = ReflectionUtils.findField(domainType, field.getName()); - + } } }); - Assert.isTrue(hashKeySetterMethod != null || hashKeyField != null, "Unable to find hash key field or setter method on " + domainType + "!"); - Assert.isTrue(hashKeySetterMethod == null || hashKeyField == null, "Found both hash key field and setter method on " + domainType + "!"); + Assert.isTrue(hashKeySetterMethod != null || hashKeyField != null, + "Unable to find hash key field or setter method on " + domainType + "!"); + Assert.isTrue(hashKeySetterMethod == null || hashKeyField == null, + "Found both hash key field and setter method on " + domainType + "!"); } @@ -86,8 +90,9 @@ public void doWith(Method method) { if (method.getAnnotation(DynamoDBIndexRangeKey.class) != null) { if ((method.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName() != null && method .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName().trim().length() > 0) - || (method.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames() != null && method - .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames().length > 0)) { + || (method.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames() != null + && method.getAnnotation(DynamoDBIndexRangeKey.class) + .localSecondaryIndexNames().length > 0)) { propertyNames.add(getPropertyNameForAccessorMethod(method)); } } @@ -98,8 +103,9 @@ public void doWith(Field field) { if (field.getAnnotation(DynamoDBIndexRangeKey.class) != null) { if ((field.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName() != null && field .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName().trim().length() > 0) - || (field.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames() != null && field - .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames().length > 0)) { + || (field.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames() != null + && field.getAnnotation(DynamoDBIndexRangeKey.class) + .localSecondaryIndexNames().length > 0)) { propertyNames.add(getPropertyNameForField(field)); } } @@ -112,22 +118,18 @@ public T getHashKeyPropotypeEntityForHashKey(Object hashKey) { try { T entity = getJavaType().getDeclaredConstructor().newInstance(); - if (hashKeySetterMethod != null) - { + if (hashKeySetterMethod != null) { ReflectionUtils.invokeMethod(hashKeySetterMethod, entity, hashKey); - } - else - { - ReflectionUtils.setField(hashKeyField, entity, hashKey); + } else { + ReflectionUtils.setField(hashKeyField, entity, hashKey); } return entity; - } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { + } catch (InstantiationException | IllegalAccessException | NoSuchMethodException + | InvocationTargetException e) { throw new RuntimeException(e); } } - - @Override public boolean isCompositeHashAndRangeKeyProperty(String propertyName) { diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractor.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractor.java index d1a44863..4e66a88e 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractor.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractor.java @@ -29,7 +29,7 @@ public interface DynamoDBHashAndRangeKeyMethodExtractor extends EntityMetada Method getHashKeyMethod(); Method getRangeKeyMethod(); - + Field getHashKeyField(); Field getRangeKeyField(); diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractorImpl.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractorImpl.java index ff21df5d..2d271377 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractorImpl.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractorImpl.java @@ -39,7 +39,8 @@ public class DynamoDBHashAndRangeKeyMethodExtractorImpl implements DynamoDBHa private Field rangeKeyField; /** - * Creates a new {@link DynamoDBHashAndRangeKeyMethodExtractor} for the given domain type. + * Creates a new {@link DynamoDBHashAndRangeKeyMethodExtractor} for the given + * domain type. * * @param idType * must not be {@literal null}. @@ -50,10 +51,10 @@ public DynamoDBHashAndRangeKeyMethodExtractorImpl(final Class idType) { this.idType = idType; ReflectionUtils.doWithMethods(idType, new MethodCallback() { @Override - public void doWith(Method method) { + public void doWith(Method method) { if (method.getAnnotation(DynamoDBHashKey.class) != null) { - Assert.isNull(hashKeyMethod, "Multiple methods annotated by @DynamoDBHashKey within type " + idType.getName() - + "!"); + Assert.isNull(hashKeyMethod, + "Multiple methods annotated by @DynamoDBHashKey within type " + idType.getName() + "!"); ReflectionUtils.makeAccessible(method); hashKeyMethod = method; } @@ -61,10 +62,10 @@ public void doWith(Method method) { }); ReflectionUtils.doWithFields(idType, new FieldCallback() { @Override - public void doWith(Field field) { + public void doWith(Field field) { if (field.getAnnotation(DynamoDBHashKey.class) != null) { - Assert.isNull(hashKeyField, "Multiple fields annotated by @DynamoDBHashKey within type " + idType.getName() - + "!"); + Assert.isNull(hashKeyField, + "Multiple fields annotated by @DynamoDBHashKey within type " + idType.getName() + "!"); ReflectionUtils.makeAccessible(field); hashKeyField = field; @@ -73,7 +74,7 @@ public void doWith(Field field) { }); ReflectionUtils.doWithMethods(idType, new MethodCallback() { @Override - public void doWith(Method method) { + public void doWith(Method method) { if (method.getAnnotation(DynamoDBRangeKey.class) != null) { Assert.isNull(rangeKeyMethod, "Multiple methods annotated by @DynamoDBRangeKey within type " + idType.getName() + "!"); @@ -84,7 +85,7 @@ public void doWith(Method method) { }); ReflectionUtils.doWithFields(idType, new FieldCallback() { @Override - public void doWith(Field field) { + public void doWith(Field field) { if (field.getAnnotation(DynamoDBRangeKey.class) != null) { Assert.isNull(rangeKeyField, "Multiple fields annotated by @DynamoDBRangeKey within type " + idType.getName() + "!"); @@ -94,17 +95,21 @@ public void doWith(Field field) { } }); if (hashKeyMethod == null && hashKeyField == null) { - throw new IllegalArgumentException("No method or field annotated by @DynamoDBHashKey within type " + idType.getName() + "!"); - } - if (rangeKeyMethod == null && rangeKeyField == null) { - throw new IllegalArgumentException("No method or field annotated by @DynamoDBRangeKey within type " + idType.getName() + "!"); - } - if (hashKeyMethod != null && hashKeyField != null) { - throw new IllegalArgumentException("Both method and field annotated by @DynamoDBHashKey within type " + idType.getName() + "!"); - } - if(rangeKeyMethod != null && rangeKeyField != null) { - throw new IllegalArgumentException("Both method and field annotated by @DynamoDBRangeKey within type " + idType.getName() + "!"); - } + throw new IllegalArgumentException( + "No method or field annotated by @DynamoDBHashKey within type " + idType.getName() + "!"); + } + if (rangeKeyMethod == null && rangeKeyField == null) { + throw new IllegalArgumentException( + "No method or field annotated by @DynamoDBRangeKey within type " + idType.getName() + "!"); + } + if (hashKeyMethod != null && hashKeyField != null) { + throw new IllegalArgumentException( + "Both method and field annotated by @DynamoDBHashKey within type " + idType.getName() + "!"); + } + if (rangeKeyMethod != null && rangeKeyField != null) { + throw new IllegalArgumentException( + "Both method and field annotated by @DynamoDBRangeKey within type " + idType.getName() + "!"); + } } @Override diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformation.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformation.java index 1517bd3e..2ce77299 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformation.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformation.java @@ -19,7 +19,9 @@ * @author Michael Lavelle * @author Sebastian Just */ -public interface DynamoDBIdIsHashAndRangeKeyEntityInformation extends - DynamoDBHashAndRangeKeyExtractingEntityMetadata, DynamoDBEntityInformation { +public interface DynamoDBIdIsHashAndRangeKeyEntityInformation + extends + DynamoDBHashAndRangeKeyExtractingEntityMetadata, + DynamoDBEntityInformation { } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformationImpl.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformationImpl.java index c146a07e..cb72850d 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformationImpl.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformationImpl.java @@ -34,8 +34,9 @@ * @author Michael Lavelle * @author Sebastian Just */ -public class DynamoDBIdIsHashAndRangeKeyEntityInformationImpl extends - ReflectionEntityInformation implements DynamoDBIdIsHashAndRangeKeyEntityInformation { +public class DynamoDBIdIsHashAndRangeKeyEntityInformationImpl extends ReflectionEntityInformation + implements + DynamoDBIdIsHashAndRangeKeyEntityInformation { private DynamoDBHashAndRangeKeyExtractingEntityMetadata metadata; private HashAndRangeKeyExtractor hashAndRangeKeyExtractor; diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashKeyEntityInformationImpl.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashKeyEntityInformationImpl.java index 880fe350..89caad14 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashKeyEntityInformationImpl.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashKeyEntityInformationImpl.java @@ -40,14 +40,16 @@ * @author Michael Lavelle * @author Sebastian Just */ -public class DynamoDBIdIsHashKeyEntityInformationImpl extends - FieldAndGetterReflectionEntityInformation implements DynamoDBEntityInformation { +public class DynamoDBIdIsHashKeyEntityInformationImpl extends FieldAndGetterReflectionEntityInformation + implements + DynamoDBEntityInformation { private DynamoDBHashKeyExtractingEntityMetadata metadata; private HashKeyExtractor hashKeyExtractor; private Optional projection = Optional.empty(); - public DynamoDBIdIsHashKeyEntityInformationImpl(Class domainClass, DynamoDBHashKeyExtractingEntityMetadata metadata) { + public DynamoDBIdIsHashKeyEntityInformationImpl(Class domainClass, + DynamoDBHashKeyExtractingEntityMetadata metadata) { super(domainClass, DynamoDBHashKey.class); this.metadata = metadata; this.hashKeyExtractor = new HashKeyIsIdHashKeyExtractor(getIdType()); diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactory.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactory.java index 6f866944..56d72ec6 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactory.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactory.java @@ -65,8 +65,10 @@ public class DynamoDBRepositoryFactory extends RepositoryFactorySupport { System.getProperty("os.version")); if (!DEVELOPMENT.equals(thisImplVersion) && !isCompatible(springDataVersion, thisSpecVersion)) { - LOGGER.warn("This Spring Data DynamoDB implementation might not be compatible with the available Spring Data classes on the classpath!" - + System.getProperty("line.separator") + "NoDefClassFoundExceptions or similar might occur!"); + LOGGER.warn( + "This Spring Data DynamoDB implementation might not be compatible with the available Spring Data classes on the classpath!" + + System.getProperty("line.separator") + + "NoDefClassFoundExceptions or similar might occur!"); } } @@ -90,7 +92,6 @@ protected static boolean isCompatible(String spec, String impl) { return specMajor.equals(implMajor) && specMinor.equals(implMinor); } - private final DynamoDBOperations dynamoDBOperations; public DynamoDBRepositoryFactory(DynamoDBOperations dynamoDBOperations) { @@ -106,20 +107,25 @@ public DynamoDBEntityInformation getEntityInformation(final Class } @Override - protected Optional getQueryLookupStrategy(Key key, EvaluationContextProvider evaluationContextProvider) { + protected Optional getQueryLookupStrategy(Key key, + EvaluationContextProvider evaluationContextProvider) { return Optional.of(DynamoDBQueryLookupStrategy.create(dynamoDBOperations, key)); } /** - * Callback to create a {@link DynamoDBCrudRepository} instance with the given {@link RepositoryMetadata} + * Callback to create a {@link DynamoDBCrudRepository} instance with the given + * {@link RepositoryMetadata} * - * @param Type of the Entity - * @param Type of the Hash (Primary) Key - * @param metadata Metadata of the entity + * @param + * Type of the Entity + * @param + * Type of the Hash (Primary) Key + * @param metadata + * Metadata of the entity * @see #getTargetRepository(RepositoryInformation) * @return the created {@link DynamoDBCrudRepository} instance */ - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) protected DynamoDBCrudRepository getDynamoDBRepository( RepositoryMetadata metadata) { return new SimpleDynamoDBPagingAndSortingRepository(getEntityInformation(metadata.getDomainType()), diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryBean.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryBean.java index 7eab037c..bd110671 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryBean.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryBean.java @@ -40,19 +40,22 @@ * the type of the repository */ public class DynamoDBRepositoryFactoryBean, S, ID extends Serializable> - extends RepositoryFactoryBeanSupport implements ApplicationContextAware { + extends + RepositoryFactoryBeanSupport + implements + ApplicationContextAware { private DynamoDBMapperConfig dynamoDBMapperConfig; private AmazonDynamoDB amazonDynamoDB; - + private DynamoDBOperations dynamoDBOperations; private ApplicationContext applicationContext; public DynamoDBRepositoryFactoryBean(Class repositoryInterface) { - super(repositoryInterface); - } + super(repositoryInterface); + } public void setAmazonDynamoDB(AmazonDynamoDB amazonDynamoDB) { this.amazonDynamoDB = amazonDynamoDB; @@ -67,13 +70,12 @@ public void setApplicationContext(ApplicationContext applicationContext) throws @Override protected RepositoryFactorySupport createRepositoryFactory() { - if (dynamoDBOperations == null) - { + if (dynamoDBOperations == null) { /** * The ApplicationContextAware within DynamoDBTemplate is not executed as * DynamoDBTemplate is not initialized as a bean */ - DynamoDBTemplate dynamoDBTemplate = new DynamoDBTemplate(amazonDynamoDB,dynamoDBMapperConfig); + DynamoDBTemplate dynamoDBTemplate = new DynamoDBTemplate(amazonDynamoDB, dynamoDBMapperConfig); dynamoDBTemplate.setApplicationContext(applicationContext); dynamoDBOperations = dynamoDBTemplate; } @@ -83,7 +85,7 @@ protected RepositoryFactorySupport createRepositoryFactory() { public void setDynamoDBMapperConfig(DynamoDBMapperConfig dynamoDBMapperConfig) { this.dynamoDBMapperConfig = dynamoDBMapperConfig; } - + public void setDynamoDBOperations(DynamoDBOperations dynamoDBOperations) { this.dynamoDBOperations = dynamoDBOperations; setMappingContext(new DynamoDBMappingContext()); diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanAnnotationPermissions.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanAnnotationPermissions.java index f33b7f0f..d8c8a56e 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanAnnotationPermissions.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanAnnotationPermissions.java @@ -80,7 +80,8 @@ public EnableScanAnnotationPermissions(Class repositoryInterface) { continue; } - if (method.getName().equals("findAll") && Pageable.class.isAssignableFrom(method.getParameterTypes()[0])) { + if (method.getName().equals("findAll") + && Pageable.class.isAssignableFrom(method.getParameterTypes()[0])) { findAllUnpaginatedScanCountEnabled = true; continue; } @@ -94,7 +95,8 @@ public EnableScanAnnotationPermissions(Class repositoryInterface) { continue; } - if (method.getName().equals("findAll") && Pageable.class.isAssignableFrom(method.getParameterTypes()[0])) { + if (method.getName().equals("findAll") + && Pageable.class.isAssignableFrom(method.getParameterTypes()[0])) { findAllPaginatedScanEnabled = true; continue; } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanPermissions.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanPermissions.java index b887ab11..de26ddea 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanPermissions.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanPermissions.java @@ -22,9 +22,9 @@ public interface EnableScanPermissions { boolean isFindAllUnpaginatedScanEnabled(); - + boolean isFindAllPaginatedScanEnabled(); - + boolean isFindAllUnpaginatedScanCountEnabled(); boolean isDeleteAllUnpaginatedScanEnabled(); diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/FieldAndGetterReflectionEntityInformation.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/FieldAndGetterReflectionEntityInformation.java index 143be341..adff66a3 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/FieldAndGetterReflectionEntityInformation.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/FieldAndGetterReflectionEntityInformation.java @@ -25,8 +25,9 @@ import java.lang.reflect.Method; /** - * {@link org.springframework.data.repository.core.EntityInformation} implementation that inspects getters for an - * annotation and invokes this getter's value to retrieve the id. + * {@link org.springframework.data.repository.core.EntityInformation} + * implementation that inspects getters for an annotation and invokes this + * getter's value to retrieve the id. * * @author Michael Lavelle * @author Sebastian Just @@ -39,8 +40,10 @@ public class FieldAndGetterReflectionEntityInformation extends AbstractEn private Field field; /** - * Creates a new {@link org.springframework.data.repository.core.support.ReflectionEntityInformation} inspecting the given - * domain class for a getter carrying the {@link Id} annotation. + * Creates a new + * {@link org.springframework.data.repository.core.support.ReflectionEntityInformation} + * inspecting the given domain class for a getter carrying the {@link Id} + * annotation. * * @param domainClass * must not be {@literal null}. @@ -50,15 +53,16 @@ public FieldAndGetterReflectionEntityInformation(Class domainClass) { } /** - * Creates a new {@link FieldAndGetterReflectionEntityInformation} inspecting the - * given domain class for a getter carrying the given annotation. + * Creates a new {@link FieldAndGetterReflectionEntityInformation} inspecting + * the given domain class for a getter carrying the given annotation. * * @param domainClass * must not be {@literal null}. * @param annotation * must not be {@literal null}. */ - public FieldAndGetterReflectionEntityInformation(Class domainClass, final Class annotation) { + public FieldAndGetterReflectionEntityInformation(Class domainClass, + final Class annotation) { super(domainClass); Assert.notNull(annotation, "annotation must not be null!"); @@ -70,8 +74,7 @@ public FieldAndGetterReflectionEntityInformation(Class domainClass, final Cla } }); - if (method == null) - { + if (method == null) { ReflectionUtils.doWithFields(domainClass, (field) -> { if (field.getAnnotation(annotation) != null) { FieldAndGetterReflectionEntityInformation.this.field = field; @@ -80,11 +83,12 @@ public FieldAndGetterReflectionEntityInformation(Class domainClass, final Cla }); } - Assert.isTrue(this.method != null || this.field != null, String.format("No field or method annotated with %s found!", annotation.toString())); - Assert.isTrue(this.method == null || this.field == null, String.format("Both field and method annotated with %s found!", annotation.toString())); + Assert.isTrue(this.method != null || this.field != null, + String.format("No field or method annotated with %s found!", annotation.toString())); + Assert.isTrue(this.method == null || this.field == null, + String.format("Both field and method annotated with %s found!", annotation.toString())); - if (method != null) - { + if (method != null) { ReflectionUtils.makeAccessible(method); } } @@ -92,19 +96,15 @@ public FieldAndGetterReflectionEntityInformation(Class domainClass, final Cla /* * (non-Javadoc) * - * @see - * org.springframework.data.repository.core.EntityInformation#getId(java + * @see org.springframework.data.repository.core.EntityInformation#getId(java * .lang.Object) */ @Override - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public ID getId(T entity) { - if (method != null) - { + if (method != null) { return entity == null ? null : (ID) ReflectionUtils.invokeMethod(method, entity); - } - else - { + } else { return entity == null ? null : (ID) ReflectionUtils.getField(field, entity); } } @@ -112,11 +112,10 @@ public ID getId(T entity) { /* * (non-Javadoc) * - * @see - * org.springframework.data.repository.core.EntityInformation#getIdType() + * @see org.springframework.data.repository.core.EntityInformation#getIdType() */ @Override - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public Class getIdType() { return (Class) (method != null ? method.getReturnType() : field.getType()); } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/HashKeyIsIdHashKeyExtractor.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/HashKeyIsIdHashKeyExtractor.java index 02947b65..bb406dec 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/HashKeyIsIdHashKeyExtractor.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/HashKeyIsIdHashKeyExtractor.java @@ -32,7 +32,8 @@ public HashKeyIsIdHashKeyExtractor(Class idAndHashKeyType) { @Override public ID getHashKey(ID id) { Assert.isAssignable(idAndHashKeyType, id.getClass(), - "Expected ID type to be the same as the return type of the hash key method ( " + idAndHashKeyType + " ) : "); + "Expected ID type to be the same as the return type of the hash key method ( " + idAndHashKeyType + + " ) : "); return id; } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBCrudRepository.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBCrudRepository.java index e7666db9..a15c01b8 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBCrudRepository.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBCrudRepository.java @@ -45,22 +45,18 @@ * @param * the type of the entity's identifier */ -public class SimpleDynamoDBCrudRepository - implements DynamoDBCrudRepository, - SortHandler { +public class SimpleDynamoDBCrudRepository implements DynamoDBCrudRepository, SortHandler { protected DynamoDBEntityInformation entityInformation; protected Class domainType; protected EnableScanPermissions enableScanPermissions; - + protected DynamoDBOperations dynamoDBOperations; - public SimpleDynamoDBCrudRepository( - DynamoDBEntityInformation entityInformation, - DynamoDBOperations dynamoDBOperations, - EnableScanPermissions enableScanPermissions) { + public SimpleDynamoDBCrudRepository(DynamoDBEntityInformation entityInformation, + DynamoDBOperations dynamoDBOperations, EnableScanPermissions enableScanPermissions) { Assert.notNull(entityInformation, "entityInformation must not be null"); Assert.notNull(dynamoDBOperations, "dynamoDBOperations must not be null"); @@ -77,12 +73,10 @@ public Optional findById(ID id) { T result; if (entityInformation.isRangeKeyAware()) { - result = dynamoDBOperations.load(domainType, - entityInformation.getHashKey(id), + result = dynamoDBOperations.load(domainType, entityInformation.getHashKey(id), entityInformation.getRangeKey(id)); } else { - result = dynamoDBOperations.load(domainType, - entityInformation.getHashKey(id)); + result = dynamoDBOperations.load(domainType, entityInformation.getHashKey(id)); } return Optional.ofNullable(result); @@ -100,16 +94,16 @@ public List findAllById(Iterable ids) { Assert.notNull(id, "The given id at position " + idx.getAndIncrement() + " must not be null!"); if (entityInformation.isRangeKeyAware()) { - return new KeyPair().withHashKey( - entityInformation.getHashKey(id)).withRangeKey( - entityInformation.getRangeKey(id)); + return new KeyPair().withHashKey(entityInformation.getHashKey(id)) + .withRangeKey(entityInformation.getRangeKey(id)); } else { return new KeyPair().withHashKey(id); } }).collect(Collectors.toList()); - Map, List> keyPairsMap = Collections., List>singletonMap(domainType, keyPairs); - return (List)dynamoDBOperations.batchLoad(keyPairsMap) + Map, List> keyPairsMap = Collections., List>singletonMap(domainType, + keyPairs); + return (List) dynamoDBOperations.batchLoad(keyPairsMap) .get(dynamoDBOperations.getOverriddenTableName(domainType, entityInformation.getDynamoDBTableName())); } @@ -123,30 +117,30 @@ public S save(S entity) { /** * {@inheritDoc} * - * @throws BatchWriteException in case of an error during saving + * @throws BatchWriteException + * in case of an error during saving */ @Override - public Iterable saveAll(Iterable entities) throws BatchWriteException, IllegalArgumentException { + public Iterable saveAll(Iterable entities) + throws BatchWriteException, IllegalArgumentException { Assert.notNull(entities, "The given Iterable of entities not be null!"); List failedBatches = dynamoDBOperations.batchSave(entities); - + if (failedBatches.isEmpty()) { // Happy path return entities; } else { // Error handling: - Queue allExceptions = failedBatches.stream() - .map(it ->it.getException()) + Queue allExceptions = failedBatches.stream().map(it -> it.getException()) .collect(Collectors.toCollection(LinkedList::new)); // The first exception is hopefully the cause Exception cause = allExceptions.poll(); DataAccessException e = new BatchWriteException("Saving of entities failed!", cause); // and all other exceptions are 'just' follow-up exceptions - allExceptions.stream() - .forEach(e::addSuppressed); - + allExceptions.stream().forEach(e::addSuppressed); + throw e; } } @@ -159,28 +153,23 @@ public boolean existsById(ID id) { } void assertScanEnabled(boolean scanEnabled, String methodName) { - Assert.isTrue( - scanEnabled, - "Scanning for unpaginated " + methodName + "() queries is not enabled. " - + "To enable, re-implement the " + methodName - + "() method in your repository interface and annotate with @EnableScan, or " - + "enable scanning for all repository methods by annotating your repository interface with @EnableScan"); + Assert.isTrue(scanEnabled, "Scanning for unpaginated " + methodName + "() queries is not enabled. " + + "To enable, re-implement the " + methodName + + "() method in your repository interface and annotate with @EnableScan, or " + + "enable scanning for all repository methods by annotating your repository interface with @EnableScan"); } @Override public List findAll() { - assertScanEnabled( - enableScanPermissions.isFindAllUnpaginatedScanEnabled(), - "findAll"); + assertScanEnabled(enableScanPermissions.isFindAllUnpaginatedScanEnabled(), "findAll"); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); return dynamoDBOperations.scan(domainType, scanExpression); } @Override public long count() { - assertScanEnabled( - enableScanPermissions.isCountUnpaginatedScanEnabled(), "count"); + assertScanEnabled(enableScanPermissions.isCountUnpaginatedScanEnabled(), "count"); final DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); return dynamoDBOperations.count(domainType, scanExpression); } @@ -196,8 +185,8 @@ public void deleteById(ID id) { dynamoDBOperations.delete(entity.get()); } else { - throw new EmptyResultDataAccessException(String.format( - "No %s entity with id %s exists!", domainType, id), 1); + throw new EmptyResultDataAccessException(String.format("No %s entity with id %s exists!", domainType, id), + 1); } } @@ -217,9 +206,7 @@ public void deleteAll(Iterable entities) { @Override public void deleteAll() { - assertScanEnabled( - enableScanPermissions.isDeleteAllUnpaginatedScanEnabled(), - "deleteAll"); + assertScanEnabled(enableScanPermissions.isDeleteAllUnpaginatedScanEnabled(), "deleteAll"); dynamoDBOperations.batchDelete(findAll()); } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBPagingAndSortingRepository.java b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBPagingAndSortingRepository.java index 3df9abdc..3950242e 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBPagingAndSortingRepository.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBPagingAndSortingRepository.java @@ -54,12 +54,12 @@ * the type of the entity's identifier */ public class SimpleDynamoDBPagingAndSortingRepository extends SimpleDynamoDBCrudRepository - implements DynamoDBPagingAndSortingRepository { + implements + DynamoDBPagingAndSortingRepository { public SimpleDynamoDBPagingAndSortingRepository(DynamoDBEntityInformation entityInformation, DynamoDBOperations dynamoDBOperations, EnableScanPermissions enableScanPermissions) { super(entityInformation, dynamoDBOperations, enableScanPermissions); - } @@ -76,7 +76,7 @@ public Page findAll(Pageable pageable) { DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); // Scan to the end of the page after the requested page long scanTo = pageable.getOffset() + (2 * pageable.getPageSize()); - scanExpression.setLimit((int)Math.min(scanTo, Integer.MAX_VALUE)); + scanExpression.setLimit((int) Math.min(scanTo, Integer.MAX_VALUE)); PaginatedScanList paginatedScanList = dynamoDBOperations.scan(domainType, scanExpression); Iterator iterator = paginatedScanList.iterator(); if (pageable.getOffset() > 0) { @@ -86,12 +86,13 @@ public Page findAll(Pageable pageable) { } // Scan ahead to retrieve the next page count List results = readPageOfResults(iterator, pageable.getPageSize()); - + assertScanEnabled(enableScanPermissions.isFindAllPaginatedScanEnabled(), "findAll(Pageable pageable)"); - assertScanCountEnabled(enableScanPermissions.isFindAllUnpaginatedScanCountEnabled(), "findAll(Pageable pageable)"); + assertScanCountEnabled(enableScanPermissions.isFindAllUnpaginatedScanCountEnabled(), + "findAll(Pageable pageable)"); int totalCount = dynamoDBOperations.count(domainType, scanExpression); - + return new PageImpl<>(results, pageable, totalCount); } @@ -114,10 +115,10 @@ private List readPageOfResults(Iterator paginatedScanListIterator, int pag } return resultsPage; } - + public void assertScanCountEnabled(boolean countScanEnabled, String methodName) { - Assert.isTrue(countScanEnabled, "Scanning for the total counts for unpaginated " + methodName + " queries is not enabled. " - + "To enable, re-implement the " + methodName + Assert.isTrue(countScanEnabled, "Scanning for the total counts for unpaginated " + methodName + + " queries is not enabled. " + "To enable, re-implement the " + methodName + "() method in your repository interface and annotate with @EnableScanCount, or " + "enable total count scanning for all repository methods by annotating your repository interface with @EnableScanCount"); } diff --git a/src/main/java/org/socialsignin/spring/data/dynamodb/utils/SortHandler.java b/src/main/java/org/socialsignin/spring/data/dynamodb/utils/SortHandler.java index 06741629..1280101e 100644 --- a/src/main/java/org/socialsignin/spring/data/dynamodb/utils/SortHandler.java +++ b/src/main/java/org/socialsignin/spring/data/dynamodb/utils/SortHandler.java @@ -25,25 +25,29 @@ */ public interface SortHandler { - /** - * @param pageable The {@link Pageable} to check that no sort is specified - */ - default void ensureNoSort(Pageable pageable) { - Sort sort = pageable.getSort(); - ensureNoSort(sort); - } + /** + * @param pageable + * The {@link Pageable} to check that no sort is specified + */ + default void ensureNoSort(Pageable pageable) { + Sort sort = pageable.getSort(); + ensureNoSort(sort); + } - /** - * @param sort The {@link Sort} to check that no sort is specified - * @throws UnsupportedOperationException if a {@code sort} is initialized (non-null && not {@link Sort#unsorted()} - */ - default void ensureNoSort(Sort sort) throws UnsupportedOperationException { - if (!Sort.unsorted().equals(sort)) { - throwUnsupportedSortOperationException(); - } - } + /** + * @param sort + * The {@link Sort} to check that no sort is specified + * @throws UnsupportedOperationException + * if a {@code sort} is initialized (non-null && not + * {@link Sort#unsorted()} + */ + default void ensureNoSort(Sort sort) throws UnsupportedOperationException { + if (!Sort.unsorted().equals(sort)) { + throwUnsupportedSortOperationException(); + } + } - default T throwUnsupportedSortOperationException() { - throw new UnsupportedOperationException("Sorting not supported for scan expressions"); - } + default T throwUnsupportedSortOperationException() { + throw new UnsupportedOperationException("Sorting not supported for scan expressions"); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/config/AuditingViaJavaConfigRepositoriesIT.java b/src/test/java/org/socialsignin/spring/data/dynamodb/config/AuditingViaJavaConfigRepositoriesIT.java index 3293a737..91fb0dd2 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/config/AuditingViaJavaConfigRepositoriesIT.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/config/AuditingViaJavaConfigRepositoriesIT.java @@ -74,7 +74,7 @@ protected String[] getMappingBasePackages() { return new String[]{"org.socialsignin.spring.data.dynamodb.domain.sample"}; } - @Bean(name="auditorProvider") + @Bean(name = "auditorProvider") @SuppressWarnings("unchecked") public AuditorAware auditorProvider() { LOGGER.info("auditorProvider"); @@ -92,9 +92,10 @@ public AmazonDynamoDB amazonDynamoDB() { } /** - * Must return the same credential as {@link org.socialsignin.spring.data.dynamodb.core.ConfigurationTI} - * otherwise the repository will connect to different local DynamoDB instance - * hence it will return no table found + * Must return the same credential as + * {@link org.socialsignin.spring.data.dynamodb.core.ConfigurationTI} otherwise + * the repository will connect to different local DynamoDB instance hence it + * will return no table found * * @return */ @@ -110,8 +111,8 @@ public void setup() { this.auditor = auditableUserRepository.save(new AuditableUser("auditor")); assertThat(this.auditor, is(notNullValue())); - Optional auditorUser = auditableUserRepository.findById(this.auditor.getId()); - assertTrue(auditorUser.isPresent()); + Optional auditorUser = auditableUserRepository.findById(this.auditor.getId()); + assertTrue(auditorUser.isPresent()); } @@ -125,10 +126,9 @@ public void basicAuditing() { assertThat(savedUser.getCreatedAt(), is(notNullValue())); assertThat(savedUser.getCreatedBy(), is(this.auditor.getId())); - assertThat(savedUser.getLastModifiedAt(), is(notNullValue())); - assertThat(savedUser.getLastModifiedBy(), is(this.auditor.getId())); + assertThat(savedUser.getLastModifiedAt(), is(notNullValue())); + assertThat(savedUser.getLastModifiedBy(), is(this.auditor.getId())); } - } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingRegistrarUnitTests.java b/src/test/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingRegistrarUnitTests.java index 6e3c74b4..850ada3e 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingRegistrarUnitTests.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/config/DynamoDBAuditingRegistrarUnitTests.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.socialsignin.spring.data.dynamodb.config; +package org.socialsignin.spring.data.dynamodb.config; import org.junit.Test; import org.junit.runner.RunWith; @@ -22,28 +22,28 @@ import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.core.type.AnnotationMetadata; - /** - * Unit tests for {@link DynamoDBAuditingRegistrar}. - * - * @author Vito Limandibhrata - */ - @RunWith(MockitoJUnitRunner.class) - public class DynamoDBAuditingRegistrarUnitTests { +/** + * Unit tests for {@link DynamoDBAuditingRegistrar}. + * + * @author Vito Limandibhrata + */ +@RunWith(MockitoJUnitRunner.class) +public class DynamoDBAuditingRegistrarUnitTests { - DynamoDBAuditingRegistrar registrar = new DynamoDBAuditingRegistrar(); + DynamoDBAuditingRegistrar registrar = new DynamoDBAuditingRegistrar(); - @Mock - AnnotationMetadata metadata; - @Mock - BeanDefinitionRegistry registry; + @Mock + AnnotationMetadata metadata; + @Mock + BeanDefinitionRegistry registry; - @Test(expected = IllegalArgumentException.class) - public void rejectsNullAnnotationMetadata() { - registrar.registerBeanDefinitions(null, registry); - } + @Test(expected = IllegalArgumentException.class) + public void rejectsNullAnnotationMetadata() { + registrar.registerBeanDefinitions(null, registry); + } - @Test(expected = IllegalArgumentException.class) - public void rejectsNullBeanDefinitionRegistry() { - registrar.registerBeanDefinitions(metadata, null); - } - } + @Test(expected = IllegalArgumentException.class) + public void rejectsNullBeanDefinitionRegistry() { + registrar.registerBeanDefinitions(metadata, null); + } +} diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/core/ConfigurationTI.java b/src/test/java/org/socialsignin/spring/data/dynamodb/core/ConfigurationTI.java index 3be34f36..0f777f3f 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/core/ConfigurationTI.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/core/ConfigurationTI.java @@ -23,9 +23,9 @@ @Configuration public class ConfigurationTI { - @Bean - public AmazonDynamoDB amazonDynamoDB() { - AmazonDynamoDB ddb = DynamoDBEmbedded.create().amazonDynamoDB(); - return ddb; - } + @Bean + public AmazonDynamoDB amazonDynamoDB() { + AmazonDynamoDB ddb = DynamoDBEmbedded.create().amazonDynamoDB(); + return ddb; + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/core/CustomerHistoryIT.java b/src/test/java/org/socialsignin/spring/data/dynamodb/core/CustomerHistoryIT.java index a4733aa3..741ba0ee 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/core/CustomerHistoryIT.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/core/CustomerHistoryIT.java @@ -28,33 +28,32 @@ import static org.junit.Assert.assertEquals; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes={CustomerHistoryIT.TestAppConfig.class, DynamoDBResource.class}) +@ContextConfiguration(classes = {CustomerHistoryIT.TestAppConfig.class, DynamoDBResource.class}) public class CustomerHistoryIT { - @Configuration - @EnableDynamoDBRepositories(basePackages = "org.socialsignin.spring.data.dynamodb.domain.sample") - public static class TestAppConfig { - } - - @Autowired - CustomerHistoryRepository customerHistoryRepository; - - @Test - public void saveAndGSITest() { - - CustomerHistory expected = new CustomerHistory(); - expected.setId("customerId"); - expected.setCreateDt("createDTt"); - expected.setTag("2342"); - - customerHistoryRepository.save(expected); - - CustomerHistory actual = customerHistoryRepository.findByTag(expected.getTag()); - - assertEquals(expected.getId(), actual.getId()); - assertEquals(expected.getCreateDt(), actual.getCreateDt()); - assertEquals(expected.getTag(), actual.getTag()); - } + @Configuration + @EnableDynamoDBRepositories(basePackages = "org.socialsignin.spring.data.dynamodb.domain.sample") + public static class TestAppConfig { + } + + @Autowired + CustomerHistoryRepository customerHistoryRepository; + + @Test + public void saveAndGSITest() { + + CustomerHistory expected = new CustomerHistory(); + expected.setId("customerId"); + expected.setCreateDt("createDTt"); + expected.setTag("2342"); + + customerHistoryRepository.save(expected); + + CustomerHistory actual = customerHistoryRepository.findByTag(expected.getTag()); + + assertEquals(expected.getId(), actual.getId()); + assertEquals(expected.getCreateDt(), actual.getCreateDt()); + assertEquals(expected.getTag(), actual.getTag()); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplateIT.java b/src/test/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplateIT.java index 3c6de5d9..c6767f24 100755 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplateIT.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplateIT.java @@ -31,51 +31,51 @@ * Integration test that interacts with DynamoDB Local instance. */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes={DynamoDBResource.class}) +@ContextConfiguration(classes = {DynamoDBResource.class}) public class DynamoDBTemplateIT { - @Autowired - private AmazonDynamoDB amazonDynamoDB; - private DynamoDBTemplate dynamoDBTemplate; + @Autowired + private AmazonDynamoDB amazonDynamoDB; + private DynamoDBTemplate dynamoDBTemplate; - @Before - public void setUp() { - this.dynamoDBTemplate = new DynamoDBTemplate(amazonDynamoDB); - } + @Before + public void setUp() { + this.dynamoDBTemplate = new DynamoDBTemplate(amazonDynamoDB); + } - @Test - public void testUser_CRUD() { + @Test + public void testUser_CRUD() { - // Given a entity to save. - User user = new User(); - user.setName("John Doe"); - user.setNumberOfPlaylists(10); - user.setId(UUID.randomUUID().toString()); + // Given a entity to save. + User user = new User(); + user.setName("John Doe"); + user.setNumberOfPlaylists(10); + user.setId(UUID.randomUUID().toString()); - // Save it to DB. - dynamoDBTemplate.save(user); + // Save it to DB. + dynamoDBTemplate.save(user); - // Retrieve it from DB. - User retrievedUser = dynamoDBTemplate.load(User.class, user.getId()); + // Retrieve it from DB. + User retrievedUser = dynamoDBTemplate.load(User.class, user.getId()); - // Verify the details on the entity. - assert retrievedUser.getName().equals(user.getName()); - assert retrievedUser.getId().equals(user.getId()); - assert retrievedUser.getNumberOfPlaylists() == user.getNumberOfPlaylists(); + // Verify the details on the entity. + assert retrievedUser.getName().equals(user.getName()); + assert retrievedUser.getId().equals(user.getId()); + assert retrievedUser.getNumberOfPlaylists() == user.getNumberOfPlaylists(); - // Update the entity and save. - retrievedUser.setNumberOfPlaylists(20); - dynamoDBTemplate.save(retrievedUser); + // Update the entity and save. + retrievedUser.setNumberOfPlaylists(20); + dynamoDBTemplate.save(retrievedUser); - retrievedUser = dynamoDBTemplate.load(User.class, user.getId()); + retrievedUser = dynamoDBTemplate.load(User.class, user.getId()); - assert retrievedUser.getNumberOfPlaylists() == 20; + assert retrievedUser.getNumberOfPlaylists() == 20; - // Delete. - dynamoDBTemplate.delete(retrievedUser); + // Delete. + dynamoDBTemplate.delete(retrievedUser); - // Get again. - assert dynamoDBTemplate.load(User.class, user.getId()) == null; - } + // Get again. + assert dynamoDBTemplate.load(User.class, user.getId()) == null; + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplateTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplateTest.java index d314ca92..330769f0 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplateTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/core/DynamoDBTemplateTest.java @@ -67,7 +67,7 @@ public void setUp() { this.dynamoDBTemplate = new DynamoDBTemplate(dynamoDB, dynamoDBMapper); this.dynamoDBTemplate.setApplicationContext(applicationContext); } - + @Test public void testConstructorMandatory() { expectedException.expect(IllegalArgumentException.class); @@ -78,7 +78,7 @@ public void testConstructorMandatory() { @Test public void testConstructorOptionalAllNull() { dynamoDBTemplate = new DynamoDBTemplate(dynamoDB, null, null); - + // check that the defaults are properly initialized - #108 String userTableName = dynamoDBTemplate.getOverriddenTableName(User.class, "UserTable"); assertEquals("user", userTableName); @@ -101,11 +101,10 @@ public void testDelete() { } @Test - public void testBatchDelete_CallsCorrectDynamoDBMapperMethod() - { - List users = new ArrayList<>(); - dynamoDBTemplate.batchDelete(users); - verify(dynamoDBMapper).batchDelete(any(List.class)); + public void testBatchDelete_CallsCorrectDynamoDBMapperMethod() { + List users = new ArrayList<>(); + dynamoDBTemplate.batchDelete(users); + verify(dynamoDBMapper).batchDelete(any(List.class)); } @Test @@ -117,12 +116,11 @@ public void testSave() { } @Test - public void testBatchSave_CallsCorrectDynamoDBMapperMethod() - { - List users = new ArrayList<>(); - dynamoDBTemplate.batchSave(users); + public void testBatchSave_CallsCorrectDynamoDBMapperMethod() { + List users = new ArrayList<>(); + dynamoDBTemplate.batchSave(users); - verify(dynamoDBMapper).batchSave(eq(users)); + verify(dynamoDBMapper).batchSave(eq(users)); } @Test @@ -161,8 +159,8 @@ public void testGetOverriddenTableName_WithTableNameResolver_defaultConfig() { assertDynamoDBMapperConfigCompletness(tmpl); } - @Test - public void testGetOverriddenTableName_WithTableNameResolver_defaultBuilder() { + @Test + public void testGetOverriddenTableName_WithTableNameResolver_defaultBuilder() { final String overridenTableName = "someOtherTableName"; DynamoDBMapperConfig.Builder builder = new DynamoDBMapperConfig.Builder(); @@ -174,7 +172,7 @@ public void testGetOverriddenTableName_WithTableNameResolver_defaultBuilder() { String overriddenTableName = tmpl.getOverriddenTableName(User.class, "someTableName"); assertEquals(overridenTableName, overriddenTableName); assertDynamoDBMapperConfigCompletness(tmpl); - } + } @Test public void testGetOverriddenTableName_WithTableNameResolver_emptyBuilder() { @@ -199,16 +197,14 @@ private void assertDynamoDBMapperConfigCompletness(DynamoDBTemplate tmpl) { } @Test - public void testLoadByHashKey_WhenDynamoDBMapperReturnsNull() - { + public void testLoadByHashKey_WhenDynamoDBMapperReturnsNull() { User user = dynamoDBTemplate.load(User.class, "someHashKey"); Assert.assertNull(user); } - + @Test - public void testLoadByHashKeyAndRangeKey_WhenDynamoDBMapperReturnsNull() - { - Playlist playlist = dynamoDBTemplate.load(Playlist.class, "someHashKey","someRangeKey"); + public void testLoadByHashKeyAndRangeKey_WhenDynamoDBMapperReturnsNull() { + Playlist playlist = dynamoDBTemplate.load(Playlist.class, "someHashKey", "someRangeKey"); Assert.assertNull(playlist); } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/core/FeedUserIT.java b/src/test/java/org/socialsignin/spring/data/dynamodb/core/FeedUserIT.java index 607b5bd8..154dbce8 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/core/FeedUserIT.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/core/FeedUserIT.java @@ -29,21 +29,21 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes={FeedUserIT.TestAppConfig.class, DynamoDBResource.class}) +@ContextConfiguration(classes = {FeedUserIT.TestAppConfig.class, DynamoDBResource.class}) public class FeedUserIT { - @Configuration - @EnableDynamoDBRepositories(basePackages = "org.socialsignin.spring.data.dynamodb.domain.sample") - public static class TestAppConfig { - } + @Configuration + @EnableDynamoDBRepositories(basePackages = "org.socialsignin.spring.data.dynamodb.domain.sample") + public static class TestAppConfig { + } - @Autowired - FeedUserRepository feedUserRepository; + @Autowired + FeedUserRepository feedUserRepository; - @Test - public void feed_test(){ - PageRequest pageRequest = PageRequest.of(1, 10, new Sort(Direction.DESC, "usrNo")); - feedUserRepository.findByUsrNo(2, pageRequest); //runnable - feedUserRepository.findByUsrNoAndFeedOpenYn(2, true, pageRequest); //not runnable - } + @Test + public void feed_test() { + PageRequest pageRequest = PageRequest.of(1, 10, new Sort(Direction.DESC, "usrNo")); + feedUserRepository.findByUsrNo(2, pageRequest); // runnable + feedUserRepository.findByUsrNoAndFeedOpenYn(2, true, pageRequest); // not runnable + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/AuditableUser.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/AuditableUser.java index ab4c2023..d98711f0 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/AuditableUser.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/AuditableUser.java @@ -33,75 +33,76 @@ @DynamoDBTable(tableName = "auditableUser") public class AuditableUser { - @DynamoDBHashKey - @DynamoDBAutoGeneratedKey - private String id; + @DynamoDBHashKey + @DynamoDBAutoGeneratedKey + private String id; - private String firstname; + private String firstname; - @CreatedBy - private String createdBy; + @CreatedBy + private String createdBy; - @CreatedDate - private Date createdAt; + @CreatedDate + private Date createdAt; - @LastModifiedBy - private String lastModifiedBy; + @LastModifiedBy + private String lastModifiedBy; - @LastModifiedDate - private Date lastModifiedAt; + @LastModifiedDate + private Date lastModifiedAt; - public AuditableUser() {} + public AuditableUser() { + } - public AuditableUser(String firstName) { - this.firstname = firstName; - } + public AuditableUser(String firstName) { + this.firstname = firstName; + } - 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 getFirstname() { - return firstname; - } + public String getFirstname() { + return firstname; + } - public void setFirstname(String firstName) { - this.firstname = firstName; - } + public void setFirstname(String firstName) { + this.firstname = firstName; + } - public String getCreatedBy() { - return createdBy; - } + public String getCreatedBy() { + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public Date getCreatedAt() { - return createdAt; - } + public Date getCreatedAt() { + return createdAt; + } - public void setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - } + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } - public String getLastModifiedBy() { - return lastModifiedBy; - } + public String getLastModifiedBy() { + return lastModifiedBy; + } - public void setLastModifiedBy(String lastModifiedBy) { - this.lastModifiedBy = lastModifiedBy; - } + public void setLastModifiedBy(String lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } - public Date getLastModifiedAt() { - return lastModifiedAt; - } + public Date getLastModifiedAt() { + return lastModifiedAt; + } - public void setLastModifiedAt(Date lastModifiedAt) { - this.lastModifiedAt = lastModifiedAt; - } + public void setLastModifiedAt(Date lastModifiedAt) { + this.lastModifiedAt = lastModifiedAt; + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CRUDOperationsIT.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CRUDOperationsIT.java index 4e42bb28..a68c8044 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CRUDOperationsIT.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CRUDOperationsIT.java @@ -50,114 +50,111 @@ @DynamoDBCreateTable(entityClasses = {User.class}) public class CRUDOperationsIT { - @Configuration - @EnableDynamoDBRepositories(basePackages = "org.socialsignin.spring.data.dynamodb.domain.sample") - public static class TestAppConfig { - } - - @Autowired - private UserRepository userRepository; - - @Test - public void testProjection() { - String postCode = "postCode"; - String user1 = "projection1" + ThreadLocalRandom.current().nextLong(); - String user2 = "projection2" + ThreadLocalRandom.current().nextLong(); - - User u1 = new User(); - u1.setId("Id1" + ThreadLocalRandom.current().nextLong()); - u1.setName(user1); - u1.setLeaveDate(Instant.now()); - u1.setPostCode(postCode); - u1.setNumberOfPlaylists(1); - - User u2 = new User(); - u2.setId("Id2" + ThreadLocalRandom.current().nextLong()); - u2.setName(user2); - u2.setLeaveDate(Instant.now()); - u2.setPostCode(postCode + postCode); - u2.setNumberOfPlaylists(2); - - userRepository.save(u1); - userRepository.save(u2); - - - List actualList = new ArrayList<>(); - userRepository.findAll().forEach(actualList::add); - - List projectedActuals = userRepository.findByPostCode(postCode); - assertEquals(1, projectedActuals.size()); - User projectedActual = projectedActuals.get(0); - assertNull("Attribute not projected", projectedActual.getName()); - assertNull("Attribute not projected", projectedActual.getPostCode()); - assertNull("Attribute not projected", projectedActual.getNumberOfPlaylists()); - assertNull("Key not projected", projectedActual.getId()); - assertNotNull("LeaveDate is projected", projectedActual.getLeaveDate()); - - List fullActuals = userRepository.findByNameIn(Arrays.asList(user1, user2)); - assertEquals(2, fullActuals.size()); - User fullActual = fullActuals.get(0); - assertThat(Arrays.asList(user1, user2), hasItems(fullActual.getName())); - assertThat(Arrays.asList(user1, user2), hasItems(fullActuals.get(1).getName())); - assertNotNull(fullActual.getPostCode()); - assertNotNull(fullActual.getNumberOfPlaylists()); - assertNotNull(fullActual.getId()); - assertNotNull(fullActual.getLeaveDate()); - } - - @Test - public void testEmptyResult() { - - Optional actual1 = userRepository.findByNameAndPostCode("does not", "exist"); - assertFalse(actual1.isPresent()); - - User actual2 = userRepository.findByNameAndLeaveDate("does not exist", Instant.now()); - assertNull(actual2); - } - - @Test - public void testDelete() { - // Prepare - User u1 = new User(); - String name1 = "name1" + ThreadLocalRandom.current().nextLong(); - u1.setName(name1); - u1.setId("u1"); - - User u2 = new User(); - String name2 = "name1" + ThreadLocalRandom.current().nextLong(); - u2.setId("u2"); - u2.setName(name2); - - User u3 = new User(); - String name3 = "name1" + ThreadLocalRandom.current().nextLong(); - u3.setId("u3"); - u3.setName(name3); - - - userRepository.save(u1); - userRepository.save(u2); - userRepository.save(u3); - - List actualList = new ArrayList<>(); - userRepository.findAll().forEach(actualList::add); - assertEquals("Unexpected List: " + actualList, 3, actualList.size()); - actualList.clear(); - - - userRepository.findByNameIn(Arrays.asList(name1, name2)).forEach(actualList::add); - assertEquals("Unexpected List: " + actualList, 2, actualList.size()); - actualList.clear(); - - // Delete specific - userRepository.deleteById("u2"); - userRepository.findAll().forEach(actualList::add); - assertEquals("u1", actualList.get(0).getId()); - assertEquals("u3", actualList.get(1).getId()); - - //Delete conditional - userRepository.deleteByIdAndName("u1", name1); - Optional actualUser = userRepository.findById("u1"); - assertFalse("User should have been deleted!", actualUser.isPresent()); - } + @Configuration + @EnableDynamoDBRepositories(basePackages = "org.socialsignin.spring.data.dynamodb.domain.sample") + public static class TestAppConfig { + } + + @Autowired + private UserRepository userRepository; + + @Test + public void testProjection() { + String postCode = "postCode"; + String user1 = "projection1" + ThreadLocalRandom.current().nextLong(); + String user2 = "projection2" + ThreadLocalRandom.current().nextLong(); + + User u1 = new User(); + u1.setId("Id1" + ThreadLocalRandom.current().nextLong()); + u1.setName(user1); + u1.setLeaveDate(Instant.now()); + u1.setPostCode(postCode); + u1.setNumberOfPlaylists(1); + + User u2 = new User(); + u2.setId("Id2" + ThreadLocalRandom.current().nextLong()); + u2.setName(user2); + u2.setLeaveDate(Instant.now()); + u2.setPostCode(postCode + postCode); + u2.setNumberOfPlaylists(2); + + userRepository.save(u1); + userRepository.save(u2); + + List actualList = new ArrayList<>(); + userRepository.findAll().forEach(actualList::add); + + List projectedActuals = userRepository.findByPostCode(postCode); + assertEquals(1, projectedActuals.size()); + User projectedActual = projectedActuals.get(0); + assertNull("Attribute not projected", projectedActual.getName()); + assertNull("Attribute not projected", projectedActual.getPostCode()); + assertNull("Attribute not projected", projectedActual.getNumberOfPlaylists()); + assertNull("Key not projected", projectedActual.getId()); + assertNotNull("LeaveDate is projected", projectedActual.getLeaveDate()); + + List fullActuals = userRepository.findByNameIn(Arrays.asList(user1, user2)); + assertEquals(2, fullActuals.size()); + User fullActual = fullActuals.get(0); + assertThat(Arrays.asList(user1, user2), hasItems(fullActual.getName())); + assertThat(Arrays.asList(user1, user2), hasItems(fullActuals.get(1).getName())); + assertNotNull(fullActual.getPostCode()); + assertNotNull(fullActual.getNumberOfPlaylists()); + assertNotNull(fullActual.getId()); + assertNotNull(fullActual.getLeaveDate()); + } + + @Test + public void testEmptyResult() { + + Optional actual1 = userRepository.findByNameAndPostCode("does not", "exist"); + assertFalse(actual1.isPresent()); + + User actual2 = userRepository.findByNameAndLeaveDate("does not exist", Instant.now()); + assertNull(actual2); + } + + @Test + public void testDelete() { + // Prepare + User u1 = new User(); + String name1 = "name1" + ThreadLocalRandom.current().nextLong(); + u1.setName(name1); + u1.setId("u1"); + + User u2 = new User(); + String name2 = "name1" + ThreadLocalRandom.current().nextLong(); + u2.setId("u2"); + u2.setName(name2); + + User u3 = new User(); + String name3 = "name1" + ThreadLocalRandom.current().nextLong(); + u3.setId("u3"); + u3.setName(name3); + + userRepository.save(u1); + userRepository.save(u2); + userRepository.save(u3); + + List actualList = new ArrayList<>(); + userRepository.findAll().forEach(actualList::add); + assertEquals("Unexpected List: " + actualList, 3, actualList.size()); + actualList.clear(); + + userRepository.findByNameIn(Arrays.asList(name1, name2)).forEach(actualList::add); + assertEquals("Unexpected List: " + actualList, 2, actualList.size()); + actualList.clear(); + + // Delete specific + userRepository.deleteById("u2"); + userRepository.findAll().forEach(actualList::add); + assertEquals("u1", actualList.get(0).getId()); + assertEquals("u3", actualList.get(1).getId()); + + // Delete conditional + userRepository.deleteByIdAndName("u1", name1); + Optional actualUser = userRepository.findById("u1"); + assertFalse("User should have been deleted!", actualUser.isPresent()); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocument.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocument.java index de1d8a37..e8995ca9 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocument.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocument.java @@ -25,86 +25,87 @@ @DynamoDBTable(tableName = "CustomerDocuments") public class CustomerDocument { - @Id - private CustomerDocumentId customerDocumentId; + @Id + private CustomerDocumentId customerDocumentId; - @DynamoDBAttribute - private String s3Location; + @DynamoDBAttribute + private String s3Location; - public CustomerDocument() {} + public CustomerDocument() { + } - public CustomerDocument(String customerId, String documentType, String version, String s3Location) { - this.customerDocumentId = new CustomerDocumentId(customerId, documentType, version); - this.s3Location = s3Location; - } + public CustomerDocument(String customerId, String documentType, String version, String s3Location) { + this.customerDocumentId = new CustomerDocumentId(customerId, documentType, version); + this.s3Location = s3Location; + } - @DynamoDBHashKey(attributeName = "customerId|documentType") - public String getCustomerDocumentKey() { + @DynamoDBHashKey(attributeName = "customerId|documentType") + public String getCustomerDocumentKey() { - if (customerDocumentId == null) { - return null; - } + if (customerDocumentId == null) { + return null; + } - return customerDocumentId.getCustomerDocumentKey(); + return customerDocumentId.getCustomerDocumentKey(); - } + } - public void setCustomerDocumentKey(String customerDocumentKey) { + public void setCustomerDocumentKey(String customerDocumentKey) { - if (customerDocumentId == null) { - this.customerDocumentId = new CustomerDocumentId(); - } + if (customerDocumentId == null) { + this.customerDocumentId = new CustomerDocumentId(); + } - customerDocumentId.setCustomerDocumentKey(customerDocumentKey); + customerDocumentId.setCustomerDocumentKey(customerDocumentKey); - } + } - @DynamoDBRangeKey(attributeName = "version") - public String getVersion() { + @DynamoDBRangeKey(attributeName = "version") + public String getVersion() { - if (customerDocumentId == null) { - return null; - } + if (customerDocumentId == null) { + return null; + } - return customerDocumentId.getVersion(); + return customerDocumentId.getVersion(); - } + } - public void setVersion(String version) { + public void setVersion(String version) { - if (customerDocumentId == null) { - this.customerDocumentId = new CustomerDocumentId(); - } + if (customerDocumentId == null) { + this.customerDocumentId = new CustomerDocumentId(); + } - customerDocumentId.setVersion(version); + customerDocumentId.setVersion(version); - } + } - @DynamoDBIgnore - public String getCustomerId() { + @DynamoDBIgnore + public String getCustomerId() { - if (customerDocumentId == null) { - return null; - } + if (customerDocumentId == null) { + return null; + } - return customerDocumentId.getCustomerId(); + return customerDocumentId.getCustomerId(); - } + } - @DynamoDBIgnore - public String getDocumentType() { + @DynamoDBIgnore + public String getDocumentType() { - if (customerDocumentId == null) { - return null; - } + if (customerDocumentId == null) { + return null; + } - return customerDocumentId.getDocumentType(); + return customerDocumentId.getDocumentType(); - } + } - @DynamoDBIgnore - public CustomerDocumentId getCustomerDocumentId() { - return customerDocumentId; - } + @DynamoDBIgnore + public CustomerDocumentId getCustomerDocumentId() { + return customerDocumentId; + } } \ No newline at end of file diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentId.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentId.java index 58e4ef1b..737a5cc0 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentId.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentId.java @@ -26,71 +26,73 @@ public class CustomerDocumentId implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private static final Joiner PIPE_JOINER = Joiner.on("|").skipNulls(); - private static final Splitter PIPE_SPLITTER = Splitter.on('|').trimResults().omitEmptyStrings(); + private static final Joiner PIPE_JOINER = Joiner.on("|").skipNulls(); + private static final Splitter PIPE_SPLITTER = Splitter.on('|').trimResults().omitEmptyStrings(); - private String customerId; - private String documentType; + private String customerId; + private String documentType; - public CustomerDocumentId() { + public CustomerDocumentId() { - } + } - public CustomerDocumentId(String customerId, String documentType, String version) { - this.customerId = customerId; - this.documentType = documentType; - this.version = version; - } + public CustomerDocumentId(String customerId, String documentType, String version) { + this.customerId = customerId; + this.documentType = documentType; + this.version = version; + } - @DynamoDBRangeKey - private String version; + @DynamoDBRangeKey + private String version; - @DynamoDBHashKey(attributeName = "customerId|documentType") - public String getCustomerDocumentKey() { - return buildCustomerDocumentKey(customerId, documentType); - } + @DynamoDBHashKey(attributeName = "customerId|documentType") + public String getCustomerDocumentKey() { + return buildCustomerDocumentKey(customerId, documentType); + } - public void setCustomerDocumentKey(String customerDocumentKey) { + public void setCustomerDocumentKey(String customerDocumentKey) { - List keyPartList = new ArrayList<>(); - PIPE_SPLITTER.split(customerDocumentKey).forEach(keyPartList::add); + List keyPartList = new ArrayList<>(); + PIPE_SPLITTER.split(customerDocumentKey).forEach(keyPartList::add); - if (keyPartList.size() != 2) { - throw new IllegalStateException(String.format("An CustomerDocumentId was found to have the following mal-formed key: '%s'.", customerDocumentKey)); - } + if (keyPartList.size() != 2) { + throw new IllegalStateException( + String.format("An CustomerDocumentId was found to have the following mal-formed key: '%s'.", + customerDocumentKey)); + } - this.customerId = keyPartList.get(0); - this.documentType = keyPartList.get(1); + this.customerId = keyPartList.get(0); + this.documentType = keyPartList.get(1); - } + } - static String buildCustomerDocumentKey(String customerId, String documentType) { - return PIPE_JOINER.join(customerId, documentType); - } + static String buildCustomerDocumentKey(String customerId, String documentType) { + return PIPE_JOINER.join(customerId, documentType); + } - public String getCustomerId() { - return customerId; - } + public String getCustomerId() { + return customerId; + } - public void setCustomerId(String customerId) { - this.customerId = customerId; - } + public void setCustomerId(String customerId) { + this.customerId = customerId; + } - public String getDocumentType() { - return documentType; - } + public String getDocumentType() { + return documentType; + } - public void setDocumentType(String documentType) { - this.documentType = documentType; - } + public void setDocumentType(String documentType) { + this.documentType = documentType; + } - public String getVersion() { - return version; - } + public String getVersion() { + return version; + } - public void setVersion(String version) { - this.version = version; - } + public void setVersion(String version) { + this.version = version; + } } \ No newline at end of file diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentRepository.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentRepository.java index 4d60eb26..bb2a8296 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentRepository.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentRepository.java @@ -19,14 +19,12 @@ import java.util.List; - public interface CustomerDocumentRepository extends CrudRepository { - List findByCustomerDocumentKey(String customerDocumentKey); - - default List findByCustomerDocumentKey(String customerId, String downloadType) { - return findByCustomerDocumentKey(CustomerDocumentId.buildCustomerDocumentKey(customerId, downloadType)); - } + List findByCustomerDocumentKey(String customerDocumentKey); + default List findByCustomerDocumentKey(String customerId, String downloadType) { + return findByCustomerDocumentKey(CustomerDocumentId.buildCustomerDocumentKey(customerId, downloadType)); + } } \ No newline at end of file diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentTest.java index 68cb8ffe..4b635dd9 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerDocumentTest.java @@ -36,18 +36,18 @@ @DynamoDBCreateTable(entityClasses = {CustomerDocument.class}) public class CustomerDocumentTest { - @Configuration - @EnableDynamoDBRepositories(basePackages = "org.socialsignin.spring.data.dynamodb.domain.sample") - public static class TestAppConfig { - } + @Configuration + @EnableDynamoDBRepositories(basePackages = "org.socialsignin.spring.data.dynamodb.domain.sample") + public static class TestAppConfig { + } - @Autowired - private CustomerDocumentRepository customerDocumentRepository; + @Autowired + private CustomerDocumentRepository customerDocumentRepository; - @Test - public void runTest() { + @Test + public void runTest() { - customerDocumentRepository.findByCustomerDocumentKey("a", "b"); - } + customerDocumentRepository.findByCustomerDocumentKey("a", "b"); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistory.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistory.java index c8f9384e..c3ed3b80 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistory.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistory.java @@ -23,42 +23,42 @@ @DynamoDBTable(tableName = "customerhistory") public class CustomerHistory { - @Id - private CustomerHistoryId id; + @Id + private CustomerHistoryId id; - private String tag; + private String tag; - @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_global_tag") - public String getTag() { - return tag; - } + @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_global_tag") + public String getTag() { + return tag; + } - public void setTag(String tag) { - this.tag = tag; - } + public void setTag(String tag) { + this.tag = tag; + } - @DynamoDBHashKey(attributeName = "customerId") - public String getId(){ - return id != null ? id.getCustomerId() : null; - } + @DynamoDBHashKey(attributeName = "customerId") + public String getId() { + return id != null ? id.getCustomerId() : null; + } - public void setId(String customerId) { - if(this.id == null) { - this.id = new CustomerHistoryId(); - } - this.id.setCustomerId(customerId); - } + public void setId(String customerId) { + if (this.id == null) { + this.id = new CustomerHistoryId(); + } + this.id.setCustomerId(customerId); + } - @DynamoDBRangeKey(attributeName = "createDt") - public String getCreateDt() { - return id != null ? id.getCreateDt() : null; - } + @DynamoDBRangeKey(attributeName = "createDt") + public String getCreateDt() { + return id != null ? id.getCreateDt() : null; + } - public void setCreateDt(String createDt) { - if(this.id == null) { - this.id = new CustomerHistoryId(); - } + public void setCreateDt(String createDt) { + if (this.id == null) { + this.id = new CustomerHistoryId(); + } - this.id.setCreateDt(createDt); - } + this.id.setCreateDt(createDt); + } } \ No newline at end of file diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistoryId.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistoryId.java index b924fc94..74dd3908 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistoryId.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistoryId.java @@ -22,24 +22,24 @@ public class CustomerHistoryId implements Serializable { - private String customerId; - private String createDt; - - @DynamoDBHashKey(attributeName = "customerId") - public String getCustomerId() { - return customerId; - } - - public void setCustomerId(String customerId) { - this.customerId = customerId; - } - - @DynamoDBRangeKey(attributeName = "createDt") - public String getCreateDt() { - return createDt; - } - - public void setCreateDt(String createDt) { - this.createDt = createDt; - } + private String customerId; + private String createDt; + + @DynamoDBHashKey(attributeName = "customerId") + public String getCustomerId() { + return customerId; + } + + public void setCustomerId(String customerId) { + this.customerId = customerId; + } + + @DynamoDBRangeKey(attributeName = "createDt") + public String getCreateDt() { + return createDt; + } + + public void setCreateDt(String createDt) { + this.createDt = createDt; + } } \ No newline at end of file diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistoryRepository.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistoryRepository.java index c73f848d..4105481a 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistoryRepository.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/CustomerHistoryRepository.java @@ -19,6 +19,6 @@ public interface CustomerHistoryRepository extends CrudRepository { - CustomerHistory findByTag(String tag); + CustomerHistory findByTag(String tag); } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/DynamoDBYearMarshaller.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/DynamoDBYearMarshaller.java index 1be89197..54509bc3 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/DynamoDBYearMarshaller.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/DynamoDBYearMarshaller.java @@ -23,7 +23,7 @@ public class DynamoDBYearMarshaller extends DateDynamoDBMarshaller { private static final String PATTERN = "yyyy"; - + @Override public DateFormat getDateFormat() { return new SimpleDateFormat(PATTERN); diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/FeedUser.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/FeedUser.java index b5ec119d..1cea3e95 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/FeedUser.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/FeedUser.java @@ -29,69 +29,74 @@ @DynamoDBTable(tableName = "feed_user") public class FeedUser { - @Id - @DynamoDBHashKey - @DynamoDBAutoGeneratedKey - private String id; - - @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_global_usrNo_feedOpenYn") - private int usrNo; - - @DynamoDBAttribute - private String feedId; - - @DynamoDBAttribute - private Date feedRegDate; - - @DynamoDBAttribute - @DynamoDBTyped(DynamoDBAttributeType.N) // For backwards compatibility with old versions, DynamoDBMapper booleans are - // serialized using the DynamoDB N type so this is not strictly required. This - // is here purely to test the DynamoDBMapper v2 conversion schemas using new - // non-deprecated annotations. NOTE: this introduces an important change in - // *internal* behaviour where @DynamoDBNativeBoolean will no longer be translated - // to DynamoDB type N. Instead, it would be correctly mapped to type BOOL which - // would cause this test to fail given that only scalar (B, N or S) types are - // allowed key types - @DynamoDBIndexRangeKey(globalSecondaryIndexName = "idx_global_usrNo_feedOpenYn") - private boolean feedOpenYn; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public int getUsrNo() { - return usrNo; - } - - public void setUsrNo(int usrNo) { - this.usrNo = usrNo; - } - - public String getFeedId() { - return feedId; - } - - public void setFeedId(String feedId) { - this.feedId = feedId; - } - - public Date getFeedRegDate() { - return feedRegDate; - } - - public void setFeedRegDate(Date feedRegDate) { - this.feedRegDate = feedRegDate; - } - - public boolean isFeedOpenYn() { - return feedOpenYn; - } - - public void setFeedOpenYn(boolean feedOpenYn) { - this.feedOpenYn = feedOpenYn; - } + @Id + @DynamoDBHashKey + @DynamoDBAutoGeneratedKey + private String id; + + @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_global_usrNo_feedOpenYn") + private int usrNo; + + @DynamoDBAttribute + private String feedId; + + @DynamoDBAttribute + private Date feedRegDate; + + @DynamoDBAttribute + @DynamoDBTyped(DynamoDBAttributeType.N) // For backwards compatibility with old versions, DynamoDBMapper booleans + // are + // serialized using the DynamoDB N type so this is not strictly required. + // This + // is here purely to test the DynamoDBMapper v2 conversion schemas using new + // non-deprecated annotations. NOTE: this introduces an important change in + // *internal* behaviour where @DynamoDBNativeBoolean will no longer be + // translated + // to DynamoDB type N. Instead, it would be correctly mapped to type BOOL + // which + // would cause this test to fail given that only scalar (B, N or S) types + // are + // allowed key types + @DynamoDBIndexRangeKey(globalSecondaryIndexName = "idx_global_usrNo_feedOpenYn") + private boolean feedOpenYn; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getUsrNo() { + return usrNo; + } + + public void setUsrNo(int usrNo) { + this.usrNo = usrNo; + } + + public String getFeedId() { + return feedId; + } + + public void setFeedId(String feedId) { + this.feedId = feedId; + } + + public Date getFeedRegDate() { + return feedRegDate; + } + + public void setFeedRegDate(Date feedRegDate) { + this.feedRegDate = feedRegDate; + } + + public boolean isFeedOpenYn() { + return feedOpenYn; + } + + public void setFeedOpenYn(boolean feedOpenYn) { + this.feedOpenYn = feedOpenYn; + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/FeedUserRepository.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/FeedUserRepository.java index d70df3f0..75bb5c16 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/FeedUserRepository.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/FeedUserRepository.java @@ -20,7 +20,7 @@ import java.util.List; -public interface FeedUserRepository extends DynamoDBPagingAndSortingRepository{ - public List findByUsrNo(int usrNo, Pageable pageable); - public List findByUsrNoAndFeedOpenYn(int usrNo, boolean feedOpenYn, Pageable pageable); +public interface FeedUserRepository extends DynamoDBPagingAndSortingRepository { + public List findByUsrNo(int usrNo, Pageable pageable); + public List findByUsrNoAndFeedOpenYn(int usrNo, boolean feedOpenYn, Pageable pageable); } \ No newline at end of file diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/GlobalSecondaryIndexWithRangeKeyIT.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/GlobalSecondaryIndexWithRangeKeyIT.java index 701609dd..6d373084 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/GlobalSecondaryIndexWithRangeKeyIT.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/GlobalSecondaryIndexWithRangeKeyIT.java @@ -33,7 +33,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; - /** * Shows the usage of Hash+Range key combinations with global secondary indexes. */ @@ -41,40 +40,39 @@ @ContextConfiguration(classes = {DynamoDBResource.class, GlobalSecondaryIndexWithRangeKeyIT.TestAppConfig.class}) public class GlobalSecondaryIndexWithRangeKeyIT { - @Configuration - @EnableDynamoDBRepositories(basePackages = "org.socialsignin.spring.data.dynamodb.domain.sample") - public static class TestAppConfig { - } + @Configuration + @EnableDynamoDBRepositories(basePackages = "org.socialsignin.spring.data.dynamodb.domain.sample") + public static class TestAppConfig { + } - @Autowired - private InstallationRepository installationRepository; + @Autowired + private InstallationRepository installationRepository; - @Test - public void testFindBySystemIdOrderByUpdatedAtDesc() { - installationRepository.save(new Installation("systemId", createDate(10, 5, 1995))); - installationRepository.save(new Installation("systemId", createDate(20, 10, 2001))); - installationRepository.save(new Installation("systemId", createDate(28, 10, 2016))); + @Test + public void testFindBySystemIdOrderByUpdatedAtDesc() { + installationRepository.save(new Installation("systemId", createDate(10, 5, 1995))); + installationRepository.save(new Installation("systemId", createDate(20, 10, 2001))); + installationRepository.save(new Installation("systemId", createDate(28, 10, 2016))); - final List actual = installationRepository.findBySystemIdOrderByUpdatedAtDesc("systemId"); - assertNotNull(actual); - assertFalse(actual.isEmpty()); + final List actual = installationRepository.findBySystemIdOrderByUpdatedAtDesc("systemId"); + assertNotNull(actual); + assertFalse(actual.isEmpty()); - Date previousDate = null; - for (final Installation installation : actual) { - assertEquals(installation.getSystemId(), "systemId"); - if (previousDate != null && installation.getUpdatedAt().compareTo(previousDate) != -1) { - fail("Results were not returned in descending order of updated date!"); - } else { - previousDate = installation.getUpdatedAt(); - } - } - } + Date previousDate = null; + for (final Installation installation : actual) { + assertEquals(installation.getSystemId(), "systemId"); + if (previousDate != null && installation.getUpdatedAt().compareTo(previousDate) != -1) { + fail("Results were not returned in descending order of updated date!"); + } else { + previousDate = installation.getUpdatedAt(); + } + } + } - private Date createDate(final int dayOfMonth, final int month, final int year) { - final Calendar calendar = Calendar.getInstance(); - calendar.set(year, month, dayOfMonth, 0, 0, 0); - calendar.set(Calendar.MILLISECOND, 0); - return calendar.getTime(); - } + private Date createDate(final int dayOfMonth, final int month, final int year) { + final Calendar calendar = Calendar.getInstance(); + calendar.set(year, month, dayOfMonth, 0, 0, 0); + calendar.set(Calendar.MILLISECOND, 0); + return calendar.getTime(); + } } - diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/HashRangeKeyIT.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/HashRangeKeyIT.java index 797e0f1e..f94c9dd1 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/HashRangeKeyIT.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/HashRangeKeyIT.java @@ -34,8 +34,7 @@ import static org.junit.Assert.assertTrue; /** - * Show the usage of Hash+Range key as also how to use - * XML based configuration + * Show the usage of Hash+Range key as also how to use XML based configuration */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:META-INF/context/HashRangeKeyIT-context.xml"}) diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Installation.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Installation.java index 1150949b..453f5d80 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Installation.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Installation.java @@ -24,61 +24,60 @@ import java.io.Serializable; import java.util.Date; - /** - * Test for Issue 52. + * Test for Issue + * 52. */ @DynamoDBTable(tableName = "installations") public class Installation implements Serializable { - private static final long serialVersionUID = 1L; - - @DynamoDBHashKey - @DynamoDBAutoGeneratedKey - public String id; + private static final long serialVersionUID = 1L; - @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx-global-systemid") - private String systemId; + @DynamoDBHashKey + @DynamoDBAutoGeneratedKey + public String id; - @DynamoDBIndexRangeKey(globalSecondaryIndexName = "idx-global-systemid") - private Date updatedAt; + @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx-global-systemid") + private String systemId; + @DynamoDBIndexRangeKey(globalSecondaryIndexName = "idx-global-systemid") + private Date updatedAt; - public Installation() { + public Installation() { - } + } - public Installation(final String systemId, final Date updatedAt) { - this.systemId = systemId; - this.updatedAt = updatedAt; - } + public Installation(final String systemId, final Date updatedAt) { + this.systemId = systemId; + this.updatedAt = updatedAt; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(final String id) { - this.id = id; - } + public void setId(final String id) { + this.id = id; + } - public String getSystemId() { - return systemId; - } + public String getSystemId() { + return systemId; + } - public void setSystemId(final String systemId) { - this.systemId = systemId; - } + public void setSystemId(final String systemId) { + this.systemId = systemId; + } - public Date getUpdatedAt() { - return updatedAt; - } + public Date getUpdatedAt() { + return updatedAt; + } - public void setUpdatedAt(final Date updatedAt) { - this.updatedAt = updatedAt; - } + public void setUpdatedAt(final Date updatedAt) { + this.updatedAt = updatedAt; + } - @Override - public String toString() { - return "Installation [id='" + id + "', systemId='" + systemId + "', updatedAt='" + updatedAt + "']"; - } + @Override + public String toString() { + return "Installation [id='" + id + "', systemId='" + systemId + "', updatedAt='" + updatedAt + "']"; + } } - diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/InstallationRepository.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/InstallationRepository.java index 07148487..3c9bc9ca 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/InstallationRepository.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/InstallationRepository.java @@ -19,10 +19,8 @@ import java.util.List; - public interface InstallationRepository extends CrudRepository { - public List findBySystemIdOrderByUpdatedAtDesc(String systemId); + public List findBySystemIdOrderByUpdatedAtDesc(String systemId); } - diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Jdk8IT.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Jdk8IT.java index 6b806c61..8a282fe0 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Jdk8IT.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Jdk8IT.java @@ -35,8 +35,10 @@ /** * Tests JDK8 features of spring-data - * @see - * github.com/spring-projects/spring-data-examples/master/jpa/java8 + * + * @see + * github.com/spring-projects/spring-data-examples/master/jpa/java8 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {DynamoDBResource.class, Jdk8IT.TestAppConfig.class}) @@ -71,28 +73,28 @@ public void testOptionalKey() { assertEquals(savedEntity, result.get()); assertEquals(joinDate, result.get().getJoinDate()); } - + @Test public void testOptionalFilter() { - final Date joinDate = new Date(2000); - final String id = "testOptionalFilter"; - final String name = UUID.randomUUID().toString(); - Optional result = userRepository.findByName(name); + final Date joinDate = new Date(2000); + final String id = "testOptionalFilter"; + final String name = UUID.randomUUID().toString(); + Optional result = userRepository.findByName(name); - assertNotNull(result); - assertEquals(result, Optional.empty()); + assertNotNull(result); + assertEquals(result, Optional.empty()); - User newUser = new User(); - newUser.setId(id); - newUser.setName(name); - newUser.setJoinDate(joinDate); + User newUser = new User(); + newUser.setId(id); + newUser.setName(name); + newUser.setJoinDate(joinDate); - User savedEntity = userRepository.save(newUser); + User savedEntity = userRepository.save(newUser); - result = userRepository.findByName(name); - assertNotNull(result); - assertEquals(savedEntity, result.get()); - assertEquals(joinDate, result.get().getJoinDate()); + result = userRepository.findByName(name); + assertNotNull(result); + assertEquals(savedEntity, result.get()); + assertEquals(joinDate, result.get().getJoinDate()); } @Test @@ -103,10 +105,10 @@ public void testInstantQuery() { newUser.setId(UUID.randomUUID().toString()); newUser.setLeaveDate(leaveDate); userRepository.save(newUser); - + List results = userRepository.findByLeaveDate(leaveDate); assertEquals(1, results.size()); - + User result = results.get(0); assertNotNull(result.getId()); assertEquals(leaveDate, result.getLeaveDate()); diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Playlist.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Playlist.java index d9424cd7..92cc5423 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Playlist.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/Playlist.java @@ -35,7 +35,7 @@ public Playlist(PlaylistId playlistId) { this.playlistId = playlistId; } - @DynamoDBAttribute(attributeName="DisplayName") + @DynamoDBAttribute(attributeName = "DisplayName") public String getDisplayName() { return displayName; } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/PlaylistId.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/PlaylistId.java index 418e3a01..a6555acd 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/PlaylistId.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/PlaylistId.java @@ -37,7 +37,7 @@ public PlaylistId(String userName, String playlistName) { this.userName = userName; this.playlistName = playlistName; } - + @DynamoDBHashKey public String getUserName() { return userName; diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/User.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/User.java index ac8714a1..d1755d0a 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/User.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/User.java @@ -30,20 +30,20 @@ public class User { private String id; - + private String name; - + private Integer numberOfPlaylists; - + private Date joinDate; - @DynamoDBMarshalling(marshallerClass=DynamoDBYearMarshaller.class) + @DynamoDBMarshalling(marshallerClass = DynamoDBYearMarshaller.class) private Date joinYear; - + private Instant leaveDate; private String postCode; - + private Set testSet; public Set getTestSet() { @@ -61,7 +61,7 @@ public Date getJoinDate() { public void setJoinDate(Date joinDate) { this.joinDate = joinDate; } - + public Date getJoinYear() { return joinYear; } @@ -69,12 +69,12 @@ public Date getJoinYear() { public void setJoinYear(Date joinYear) { this.joinYear = joinYear; } - - @DynamoDBMarshalling(marshallerClass=Instant2IsoDynamoDBMarshaller.class) + + @DynamoDBMarshalling(marshallerClass = Instant2IsoDynamoDBMarshaller.class) public Instant getLeaveDate() { return leaveDate; } - + public void setLeaveDate(Instant leaveDate) { this.leaveDate = leaveDate; } @@ -96,7 +96,7 @@ public String getId() { public void setId(String id) { this.id = id; } - + public String getName() { return name; } @@ -119,17 +119,12 @@ public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((joinDate == null) ? 0 - : joinDate.hashCode()); - result = prime * result + ((joinYear == null) ? 0 - : joinYear.hashCode()); - result = prime * result + ((leaveDate == null) ? 0 - : leaveDate.hashCode()); + result = prime * result + ((joinDate == null) ? 0 : joinDate.hashCode()); + result = prime * result + ((joinYear == null) ? 0 : joinYear.hashCode()); + result = prime * result + ((leaveDate == null) ? 0 : leaveDate.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((numberOfPlaylists == null) ? 0 - : numberOfPlaylists.hashCode()); - result = prime * result + ((postCode == null) ? 0 - : postCode.hashCode()); + result = prime * result + ((numberOfPlaylists == null) ? 0 : numberOfPlaylists.hashCode()); + result = prime * result + ((postCode == null) ? 0 : postCode.hashCode()); result = prime * result + ((testSet == null) ? 0 : testSet.hashCode()); return result; } @@ -157,11 +152,11 @@ public boolean equals(Object obj) { if (other.joinYear != null) return false; } else if (!joinYear.equals(other.joinYear)) - if (leaveDate == null) { - if (other.leaveDate != null) + if (leaveDate == null) { + if (other.leaveDate != null) + return false; + } else if (!leaveDate.equals(other.leaveDate)) return false; - } else if (!leaveDate.equals(other.leaveDate)) - return false; if (name == null) { if (other.name != null) return false; diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/UserRepository.java b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/UserRepository.java index 307f2adf..c0b1876c 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/UserRepository.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/domain/sample/UserRepository.java @@ -50,7 +50,7 @@ public interface UserRepository extends CrudRepository { List findByPostCode(String postCode); @EnableScan - Optional findByNameAndPostCode(String name, String postcode); + Optional findByNameAndPostCode(String name, String postcode); @EnableScan User findByNameAndLeaveDate(String name, Instant leaveDate); diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DefaultDynamoDBDateMarshallerTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DefaultDynamoDBDateMarshallerTest.java index 1f936c35..d7f6c6e0 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DefaultDynamoDBDateMarshallerTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DefaultDynamoDBDateMarshallerTest.java @@ -26,46 +26,45 @@ public class DefaultDynamoDBDateMarshallerTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); + @Rule + public ExpectedException expectedException = ExpectedException.none(); - private DefaultDynamoDBDateMarshaller underTest = new DefaultDynamoDBDateMarshaller(); + private DefaultDynamoDBDateMarshaller underTest = new DefaultDynamoDBDateMarshaller(); - @Test - public void testMarshall() { - String actual = underTest.marshall(new Date(0)); + @Test + public void testMarshall() { + String actual = underTest.marshall(new Date(0)); - assertEquals("1970-01-01T00:00:00.000Z", actual); - } + assertEquals("1970-01-01T00:00:00.000Z", actual); + } - @Test - public void testMarshallNull() { - String actual = underTest.marshall(null); + @Test + public void testMarshallNull() { + String actual = underTest.marshall(null); - assertNull(actual); - } + assertNull(actual); + } - @Test - public void testUnmarshall() { - Date actual = underTest.unmarshall(Date.class, "1970-01-01T00:00:00.000Z"); + @Test + public void testUnmarshall() { + Date actual = underTest.unmarshall(Date.class, "1970-01-01T00:00:00.000Z"); - assertEquals(0L, actual.getTime()); - } + assertEquals(0L, actual.getTime()); + } - @Test - public void testUnmarshallNull() { - Date actual = underTest.unmarshall(Date.class, null); + @Test + public void testUnmarshallNull() { + Date actual = underTest.unmarshall(Date.class, null); - assertNull(actual); - } + assertNull(actual); + } - @Test - public void testUnmarshallGarbage() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Could not unmarshall 'garbage' via yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - - underTest.unmarshall(Date.class, "garbage"); - } + @Test + public void testUnmarshallGarbage() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Could not unmarshall 'garbage' via yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + underTest.unmarshall(Date.class, "garbage"); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBMappingContextTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBMappingContextTest.java index d226b5d1..b48f6204 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBMappingContextTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBMappingContextTest.java @@ -90,21 +90,24 @@ public void setUp() { @Test public void detectsPropertyAnnotation() { - DynamoDBPersistentEntityImpl entity = underTest.getPersistentEntity(DynamoDBMappingContextTestFieldEntity.class); + DynamoDBPersistentEntityImpl entity = underTest + .getPersistentEntity(DynamoDBMappingContextTestFieldEntity.class); assertThat(entity.getIdProperty(), is(notNullValue())); } @Test @Ignore public void detectdMethodsAnnotation() { - DynamoDBPersistentEntityImpl entity = underTest.getPersistentEntity(DynamoDBMappingContextTestMethodEntity.class); + DynamoDBPersistentEntityImpl entity = underTest + .getPersistentEntity(DynamoDBMappingContextTestMethodEntity.class); assertThat(entity.getIdProperty(), is(notNullValue())); } @Test public void detectdMethodsId() { - DynamoDBPersistentEntityImpl entity = underTest.getPersistentEntity(DynamoDBMappingContextTestIdEntity.class); + DynamoDBPersistentEntityImpl entity = underTest + .getPersistentEntity(DynamoDBMappingContextTestIdEntity.class); assertThat(entity.getIdProperty(), is(notNullValue())); } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentEntityTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentEntityTest.java index 89a6c64d..330b6122 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentEntityTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/DynamoDBPersistentEntityTest.java @@ -35,52 +35,56 @@ @RunWith(MockitoJUnitRunner.class) public class DynamoDBPersistentEntityTest { - static class DynamoDBPersistentEntity { - @DynamoDBHashKey - private String id; - - @Id - private DynamoDBHashAndRangeKey hashRangeKey; - - private String name; - } - - @Mock - private Comparator comparator; - - private ClassTypeInformation cti = ClassTypeInformation.from(DynamoDBPersistentEntity.class); - private DynamoDBPersistentEntityImpl underTest; - - @Before - public void setUp() { - underTest = new DynamoDBPersistentEntityImpl(cti, comparator); - } - - @Test - public void testSomeProperty() throws NoSuchFieldException { - Property prop = Property.of(cti, DynamoDBPersistentEntity.class.getDeclaredField("name")); - - DynamoDBPersistentProperty property = new DynamoDBPersistentPropertyImpl(prop, underTest, SimpleTypeHolder.DEFAULT); - DynamoDBPersistentProperty actual = underTest.returnPropertyIfBetterIdPropertyCandidateOrNull(property); - - assertNull(actual); - } - - @Test - public void testIdProperty() throws NoSuchFieldException { - Property prop = Property.of(cti, DynamoDBPersistentEntity.class.getDeclaredField("id")); - DynamoDBPersistentProperty property = new DynamoDBPersistentPropertyImpl(prop, underTest, SimpleTypeHolder.DEFAULT); - DynamoDBPersistentProperty actual = underTest.returnPropertyIfBetterIdPropertyCandidateOrNull(property); - - assertTrue(actual.isHashKeyProperty()); - } - - @Test - public void testCompositeIdProperty() throws NoSuchFieldException { - Property prop = Property.of(cti, DynamoDBPersistentEntity.class.getDeclaredField("hashRangeKey")); - DynamoDBPersistentProperty property = new DynamoDBPersistentPropertyImpl(prop, underTest, SimpleTypeHolder.DEFAULT); - DynamoDBPersistentProperty actual = underTest.returnPropertyIfBetterIdPropertyCandidateOrNull(property); - - assertTrue(actual.isCompositeIdProperty()); - } + static class DynamoDBPersistentEntity { + @DynamoDBHashKey + private String id; + + @Id + private DynamoDBHashAndRangeKey hashRangeKey; + + private String name; + } + + @Mock + private Comparator comparator; + + private ClassTypeInformation cti = ClassTypeInformation + .from(DynamoDBPersistentEntity.class); + private DynamoDBPersistentEntityImpl underTest; + + @Before + public void setUp() { + underTest = new DynamoDBPersistentEntityImpl(cti, comparator); + } + + @Test + public void testSomeProperty() throws NoSuchFieldException { + Property prop = Property.of(cti, DynamoDBPersistentEntity.class.getDeclaredField("name")); + + DynamoDBPersistentProperty property = new DynamoDBPersistentPropertyImpl(prop, underTest, + SimpleTypeHolder.DEFAULT); + DynamoDBPersistentProperty actual = underTest.returnPropertyIfBetterIdPropertyCandidateOrNull(property); + + assertNull(actual); + } + + @Test + public void testIdProperty() throws NoSuchFieldException { + Property prop = Property.of(cti, DynamoDBPersistentEntity.class.getDeclaredField("id")); + DynamoDBPersistentProperty property = new DynamoDBPersistentPropertyImpl(prop, underTest, + SimpleTypeHolder.DEFAULT); + DynamoDBPersistentProperty actual = underTest.returnPropertyIfBetterIdPropertyCandidateOrNull(property); + + assertTrue(actual.isHashKeyProperty()); + } + + @Test + public void testCompositeIdProperty() throws NoSuchFieldException { + Property prop = Property.of(cti, DynamoDBPersistentEntity.class.getDeclaredField("hashRangeKey")); + DynamoDBPersistentProperty property = new DynamoDBPersistentPropertyImpl(prop, underTest, + SimpleTypeHolder.DEFAULT); + DynamoDBPersistentProperty actual = underTest.returnPropertyIfBetterIdPropertyCandidateOrNull(property); + + assertTrue(actual.isCompositeIdProperty()); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/AbstractDynamoDBEventListenerTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/AbstractDynamoDBEventListenerTest.java index f35a00e0..9c8f5f98 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/AbstractDynamoDBEventListenerTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/AbstractDynamoDBEventListenerTest.java @@ -37,142 +37,142 @@ @RunWith(MockitoJUnitRunner.class) public class AbstractDynamoDBEventListenerTest { - private User sampleEntity = new User(); - @Mock - private PaginatedQueryList sampleQueryList; - @Mock - private PaginatedScanList sampleScanList; - - @Mock - private DynamoDBMappingEvent brokenEvent; - - private AbstractDynamoDBEventListener underTest; - - @Before - public void setUp() { - underTest = Mockito.spy(new AbstractDynamoDBEventListener() { - }); - - List queryList = new ArrayList<>(); - queryList.add(sampleEntity); - when(sampleQueryList.stream()).thenReturn(queryList.stream()); - when(sampleScanList.stream()).thenReturn(queryList.stream()); - } - - @Test(expected = AssertionError.class) - public void testNullArgument() { - // This is impossible but let's be sure that it is covered - when(brokenEvent.getSource()).thenReturn(null); - - underTest.onApplicationEvent(brokenEvent); - } - - @Test(expected = AssertionError.class) - public void testUnknownEvent() { - // Simulate an unknown event - when(brokenEvent.getSource()).thenReturn(new User()); - - underTest.onApplicationEvent(brokenEvent); - } - - @Test - @SuppressWarnings("unchecked") - public void testRawType() { - underTest = Mockito.spy(new AbstractDynamoDBEventListener() { - }); - - assertSame(Object.class, underTest.getDomainClass()); - } - - @Test - public void testAfterDelete() { - underTest.onApplicationEvent(new AfterDeleteEvent<>(sampleEntity)); - - verify(underTest).onAfterDelete(sampleEntity); - verify(underTest, never()).onAfterLoad(any()); - verify(underTest, never()).onAfterQuery(any()); - verify(underTest, never()).onAfterSave(any()); - verify(underTest, never()).onAfterScan(any()); - verify(underTest, never()).onBeforeDelete(any()); - verify(underTest, never()).onBeforeSave(any()); - } - - @Test - public void testAfterLoad() { - underTest.onApplicationEvent(new AfterLoadEvent<>(sampleEntity)); - - verify(underTest, never()).onAfterDelete(any()); - verify(underTest).onAfterLoad(sampleEntity); - verify(underTest, never()).onAfterQuery(any()); - verify(underTest, never()).onAfterSave(any()); - verify(underTest, never()).onAfterScan(any()); - verify(underTest, never()).onBeforeDelete(any()); - verify(underTest, never()).onBeforeSave(any()); - } - - @Test - public void testAfterQuery() { - underTest.onApplicationEvent(new AfterQueryEvent<>(sampleQueryList)); - - verify(underTest, never()).onAfterDelete(any()); - verify(underTest, never()).onAfterLoad(any()); - verify(underTest).onAfterQuery(sampleEntity); - verify(underTest, never()).onAfterSave(any()); - verify(underTest, never()).onAfterScan(any()); - verify(underTest, never()).onBeforeDelete(any()); - verify(underTest, never()).onBeforeSave(any()); - } - - @Test - public void testAfterSave() { - underTest.onApplicationEvent(new AfterSaveEvent<>(sampleEntity)); - - verify(underTest, never()).onAfterDelete(any()); - verify(underTest, never()).onAfterLoad(any()); - verify(underTest, never()).onAfterQuery(any()); - verify(underTest).onAfterSave(sampleEntity); - verify(underTest, never()).onAfterScan(any()); - verify(underTest, never()).onBeforeDelete(any()); - verify(underTest, never()).onBeforeSave(any()); - } - - @Test - public void testAfterScan() { - underTest.onApplicationEvent(new AfterScanEvent<>(sampleScanList)); - - verify(underTest, never()).onAfterDelete(any()); - verify(underTest, never()).onAfterLoad(any()); - verify(underTest, never()).onAfterQuery(any()); - verify(underTest, never()).onAfterSave(any()); - verify(underTest).onAfterScan(sampleEntity); - verify(underTest, never()).onBeforeDelete(any()); - verify(underTest, never()).onBeforeSave(any()); - } - - @Test - public void testBeforeDelete() { - underTest.onApplicationEvent(new BeforeDeleteEvent<>(sampleEntity)); - - verify(underTest, never()).onAfterDelete(any()); - verify(underTest, never()).onAfterLoad(any()); - verify(underTest, never()).onAfterQuery(any()); - verify(underTest, never()).onAfterSave(any()); - verify(underTest, never()).onAfterScan(any()); - verify(underTest).onBeforeDelete(sampleEntity); - verify(underTest, never()).onBeforeSave(any()); - } - - @Test - public void testBeforeSave() { - underTest.onApplicationEvent(new BeforeSaveEvent<>(sampleEntity)); - - verify(underTest, never()).onAfterDelete(any()); - verify(underTest, never()).onAfterLoad(any()); - verify(underTest, never()).onAfterQuery(any()); - verify(underTest, never()).onAfterSave(any()); - verify(underTest, never()).onAfterScan(any()); - verify(underTest, never()).onBeforeDelete(any()); - verify(underTest).onBeforeSave(sampleEntity); - } + private User sampleEntity = new User(); + @Mock + private PaginatedQueryList sampleQueryList; + @Mock + private PaginatedScanList sampleScanList; + + @Mock + private DynamoDBMappingEvent brokenEvent; + + private AbstractDynamoDBEventListener underTest; + + @Before + public void setUp() { + underTest = Mockito.spy(new AbstractDynamoDBEventListener() { + }); + + List queryList = new ArrayList<>(); + queryList.add(sampleEntity); + when(sampleQueryList.stream()).thenReturn(queryList.stream()); + when(sampleScanList.stream()).thenReturn(queryList.stream()); + } + + @Test(expected = AssertionError.class) + public void testNullArgument() { + // This is impossible but let's be sure that it is covered + when(brokenEvent.getSource()).thenReturn(null); + + underTest.onApplicationEvent(brokenEvent); + } + + @Test(expected = AssertionError.class) + public void testUnknownEvent() { + // Simulate an unknown event + when(brokenEvent.getSource()).thenReturn(new User()); + + underTest.onApplicationEvent(brokenEvent); + } + + @Test + @SuppressWarnings("unchecked") + public void testRawType() { + underTest = Mockito.spy(new AbstractDynamoDBEventListener() { + }); + + assertSame(Object.class, underTest.getDomainClass()); + } + + @Test + public void testAfterDelete() { + underTest.onApplicationEvent(new AfterDeleteEvent<>(sampleEntity)); + + verify(underTest).onAfterDelete(sampleEntity); + verify(underTest, never()).onAfterLoad(any()); + verify(underTest, never()).onAfterQuery(any()); + verify(underTest, never()).onAfterSave(any()); + verify(underTest, never()).onAfterScan(any()); + verify(underTest, never()).onBeforeDelete(any()); + verify(underTest, never()).onBeforeSave(any()); + } + + @Test + public void testAfterLoad() { + underTest.onApplicationEvent(new AfterLoadEvent<>(sampleEntity)); + + verify(underTest, never()).onAfterDelete(any()); + verify(underTest).onAfterLoad(sampleEntity); + verify(underTest, never()).onAfterQuery(any()); + verify(underTest, never()).onAfterSave(any()); + verify(underTest, never()).onAfterScan(any()); + verify(underTest, never()).onBeforeDelete(any()); + verify(underTest, never()).onBeforeSave(any()); + } + + @Test + public void testAfterQuery() { + underTest.onApplicationEvent(new AfterQueryEvent<>(sampleQueryList)); + + verify(underTest, never()).onAfterDelete(any()); + verify(underTest, never()).onAfterLoad(any()); + verify(underTest).onAfterQuery(sampleEntity); + verify(underTest, never()).onAfterSave(any()); + verify(underTest, never()).onAfterScan(any()); + verify(underTest, never()).onBeforeDelete(any()); + verify(underTest, never()).onBeforeSave(any()); + } + + @Test + public void testAfterSave() { + underTest.onApplicationEvent(new AfterSaveEvent<>(sampleEntity)); + + verify(underTest, never()).onAfterDelete(any()); + verify(underTest, never()).onAfterLoad(any()); + verify(underTest, never()).onAfterQuery(any()); + verify(underTest).onAfterSave(sampleEntity); + verify(underTest, never()).onAfterScan(any()); + verify(underTest, never()).onBeforeDelete(any()); + verify(underTest, never()).onBeforeSave(any()); + } + + @Test + public void testAfterScan() { + underTest.onApplicationEvent(new AfterScanEvent<>(sampleScanList)); + + verify(underTest, never()).onAfterDelete(any()); + verify(underTest, never()).onAfterLoad(any()); + verify(underTest, never()).onAfterQuery(any()); + verify(underTest, never()).onAfterSave(any()); + verify(underTest).onAfterScan(sampleEntity); + verify(underTest, never()).onBeforeDelete(any()); + verify(underTest, never()).onBeforeSave(any()); + } + + @Test + public void testBeforeDelete() { + underTest.onApplicationEvent(new BeforeDeleteEvent<>(sampleEntity)); + + verify(underTest, never()).onAfterDelete(any()); + verify(underTest, never()).onAfterLoad(any()); + verify(underTest, never()).onAfterQuery(any()); + verify(underTest, never()).onAfterSave(any()); + verify(underTest, never()).onAfterScan(any()); + verify(underTest).onBeforeDelete(sampleEntity); + verify(underTest, never()).onBeforeSave(any()); + } + + @Test + public void testBeforeSave() { + underTest.onApplicationEvent(new BeforeSaveEvent<>(sampleEntity)); + + verify(underTest, never()).onAfterDelete(any()); + verify(underTest, never()).onAfterLoad(any()); + verify(underTest, never()).onAfterQuery(any()); + verify(underTest, never()).onAfterSave(any()); + verify(underTest, never()).onAfterScan(any()); + verify(underTest, never()).onBeforeDelete(any()); + verify(underTest).onBeforeSave(sampleEntity); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/LoggingEventListenerTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/LoggingEventListenerTest.java index 6d1efcca..8200a5b0 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/LoggingEventListenerTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/LoggingEventListenerTest.java @@ -40,79 +40,79 @@ @RunWith(MockitoJUnitRunner.class) public class LoggingEventListenerTest { - private final TestLogger logger = TestLoggerFactory.getTestLogger(LoggingEventListener.class); - private final User sampleEntity = new User(); - @Mock - private PaginatedQueryList sampleQueryList; - @Mock - private PaginatedScanList sampleScanList; + private final TestLogger logger = TestLoggerFactory.getTestLogger(LoggingEventListener.class); + private final User sampleEntity = new User(); + @Mock + private PaginatedQueryList sampleQueryList; + @Mock + private PaginatedScanList sampleScanList; - private LoggingEventListener underTest; + private LoggingEventListener underTest; - @Before - public void setUp() { - underTest = new LoggingEventListener(); + @Before + public void setUp() { + underTest = new LoggingEventListener(); - logger.setEnabledLevels(Level.TRACE); + logger.setEnabledLevels(Level.TRACE); - List queryList = new ArrayList<>(); - queryList.add(sampleEntity); - when(sampleQueryList.stream()).thenReturn(queryList.stream()); - when(sampleScanList.stream()).thenReturn(queryList.stream()); - } + List queryList = new ArrayList<>(); + queryList.add(sampleEntity); + when(sampleQueryList.stream()).thenReturn(queryList.stream()); + when(sampleScanList.stream()).thenReturn(queryList.stream()); + } - @After - public void clearLoggers() { - TestLoggerFactory.clear(); - } + @After + public void clearLoggers() { + TestLoggerFactory.clear(); + } - @Test - public void testAfterDelete() { - underTest.onApplicationEvent(new AfterDeleteEvent<>(sampleEntity)); + @Test + public void testAfterDelete() { + underTest.onApplicationEvent(new AfterDeleteEvent<>(sampleEntity)); - assertThat(logger.getLoggingEvents(), is(asList(trace("onAfterDelete: {}", sampleEntity)))); - } + assertThat(logger.getLoggingEvents(), is(asList(trace("onAfterDelete: {}", sampleEntity)))); + } - @Test - public void testAfterLoad() { - underTest.onApplicationEvent(new AfterLoadEvent<>(sampleEntity)); + @Test + public void testAfterLoad() { + underTest.onApplicationEvent(new AfterLoadEvent<>(sampleEntity)); - assertThat(logger.getLoggingEvents(), is(asList(trace("onAfterLoad: {}", sampleEntity)))); - } + assertThat(logger.getLoggingEvents(), is(asList(trace("onAfterLoad: {}", sampleEntity)))); + } - @Test - public void testAfterQuery() { - underTest.onApplicationEvent(new AfterQueryEvent<>(sampleQueryList)); + @Test + public void testAfterQuery() { + underTest.onApplicationEvent(new AfterQueryEvent<>(sampleQueryList)); - assertThat(logger.getLoggingEvents(), is(asList(trace("onAfterQuery: {}", sampleEntity)))); - } + assertThat(logger.getLoggingEvents(), is(asList(trace("onAfterQuery: {}", sampleEntity)))); + } - @Test - public void testAfterSave() { - underTest.onApplicationEvent(new AfterSaveEvent<>(sampleEntity)); + @Test + public void testAfterSave() { + underTest.onApplicationEvent(new AfterSaveEvent<>(sampleEntity)); - assertThat(logger.getLoggingEvents(), is(asList(trace("onAfterSave: {}", sampleEntity)))); - } + assertThat(logger.getLoggingEvents(), is(asList(trace("onAfterSave: {}", sampleEntity)))); + } - @Test - public void testAfterScan() { - underTest.onApplicationEvent(new AfterScanEvent<>(sampleScanList)); + @Test + public void testAfterScan() { + underTest.onApplicationEvent(new AfterScanEvent<>(sampleScanList)); - assertThat(logger.getLoggingEvents(), is(asList(trace("onAfterScan: {}", sampleEntity)))); - } + assertThat(logger.getLoggingEvents(), is(asList(trace("onAfterScan: {}", sampleEntity)))); + } - @Test - public void testBeforeDelete() { - underTest.onApplicationEvent(new BeforeDeleteEvent<>(sampleEntity)); + @Test + public void testBeforeDelete() { + underTest.onApplicationEvent(new BeforeDeleteEvent<>(sampleEntity)); - assertThat(logger.getLoggingEvents(), is(asList(trace("onBeforeDelete: {}", sampleEntity)))); - } + assertThat(logger.getLoggingEvents(), is(asList(trace("onBeforeDelete: {}", sampleEntity)))); + } - @Test - public void testBeforeSave() { - underTest.onApplicationEvent(new BeforeSaveEvent<>(sampleEntity)); + @Test + public void testBeforeSave() { + underTest.onApplicationEvent(new BeforeSaveEvent<>(sampleEntity)); - assertThat(logger.getLoggingEvents(), is(asList(trace("onBeforeSave: {}", sampleEntity)))); - } + assertThat(logger.getLoggingEvents(), is(asList(trace("onBeforeSave: {}", sampleEntity)))); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/ValidatingDynamoDBEventListenerTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/ValidatingDynamoDBEventListenerTest.java index adfb2fd5..ae65c932 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/ValidatingDynamoDBEventListenerTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/mapping/event/ValidatingDynamoDBEventListenerTest.java @@ -38,50 +38,49 @@ @RunWith(MockitoJUnitRunner.class) public class ValidatingDynamoDBEventListenerTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private final User sampleEntity = new User(); - @Mock - private Validator validator; - private ValidatingDynamoDBEventListener underTest; + @Rule + public ExpectedException expectedException = ExpectedException.none(); + private final User sampleEntity = new User(); + @Mock + private Validator validator; + private ValidatingDynamoDBEventListener underTest; - @Before - public void setUp() { - underTest = new ValidatingDynamoDBEventListener(validator); - } + @Before + public void setUp() { + underTest = new ValidatingDynamoDBEventListener(validator); + } - @Test - public void testWrongConstructor() { - expectedException.expectMessage("validator must not be null!"); - expectedException.expect(IllegalArgumentException.class); + @Test + public void testWrongConstructor() { + expectedException.expectMessage("validator must not be null!"); + expectedException.expect(IllegalArgumentException.class); - new ValidatingDynamoDBEventListener(null); - } + new ValidatingDynamoDBEventListener(null); + } - @Test - public void testEmptyResult() { + @Test + public void testEmptyResult() { - underTest.onBeforeSave(sampleEntity); + underTest.onBeforeSave(sampleEntity); - assertTrue(true); - } + assertTrue(true); + } - @Test - public void testValidationException() { - expectedException.expect(ConstraintViolationException.class); - expectedException.expectMessage(allOf( - containsString("Test Validation Exception 1"), - containsString("Test Validation Exception 2"))); + @Test + public void testValidationException() { + expectedException.expect(ConstraintViolationException.class); + expectedException.expectMessage( + allOf(containsString("Test Validation Exception 1"), containsString("Test Validation Exception 2"))); - Set> validationResult = new HashSet<>(); - ConstraintViolation vc1 = mock(ConstraintViolation.class); - when(vc1.toString()).thenReturn("Test Validation Exception 1"); - validationResult.add(vc1); - ConstraintViolation vc2 = mock(ConstraintViolation.class); - when(vc2.toString()).thenReturn("Test Validation Exception 2"); - validationResult.add(vc2); - when(validator.validate(sampleEntity)).thenReturn(validationResult); + Set> validationResult = new HashSet<>(); + ConstraintViolation vc1 = mock(ConstraintViolation.class); + when(vc1.toString()).thenReturn("Test Validation Exception 1"); + validationResult.add(vc1); + ConstraintViolation vc2 = mock(ConstraintViolation.class); + when(vc2.toString()).thenReturn("Test Validation Exception 2"); + validationResult.add(vc2); + when(validator.validate(sampleEntity)).thenReturn(validationResult); - underTest.onBeforeSave(sampleEntity); - } + underTest.onBeforeSave(sampleEntity); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2EpocheDynamoDBMarshallerTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2EpocheDynamoDBMarshallerTest.java index 612efe26..593177a4 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2EpocheDynamoDBMarshallerTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2EpocheDynamoDBMarshallerTest.java @@ -38,20 +38,20 @@ public void testNullMarshall() { assertNull(actual); } - + @Test public void testMarshall() { assertEquals("0", underTest.marshall(new Date(0))); assertEquals("0", underTest.convert(new Date(0))); } - + @Test public void testUnmarshallNull() { Date actual = underTest.unmarshall(Date.class, null); assertNull(actual); } - + @Test public void testUnmarshall() { assertEquals(new Date(0), underTest.unmarshall(Date.class, "0")); diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2IsoDynamoDBMarshallerTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2IsoDynamoDBMarshallerTest.java index 18489a5d..3d3c0df2 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2IsoDynamoDBMarshallerTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Date2IsoDynamoDBMarshallerTest.java @@ -38,20 +38,20 @@ public void testNullMarshall() { assertNull(actual); } - + @Test public void testMarshall() { assertEquals("1970-01-01T00:00:00.000Z", underTest.marshall(new Date(0))); assertEquals("1970-01-01T00:00:00.000Z", underTest.convert(new Date(0))); } - + @Test public void testUnmarshallNull() { Date actual = underTest.unmarshall(Date.class, null); assertNull(actual); } - + @Test public void testUnmarshall() { assertEquals(new Date(0), underTest.unmarshall(Date.class, "1970-01-01T00:00:00.000Z")); diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2EpocheDynamoDBMarshallerTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2EpocheDynamoDBMarshallerTest.java index de70cd02..abeb1c0f 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2EpocheDynamoDBMarshallerTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2EpocheDynamoDBMarshallerTest.java @@ -38,20 +38,20 @@ public void testNullMarshall() { assertNull(actual); } - + @Test public void testMarshall() { assertEquals("0", underTest.marshall(Instant.ofEpochMilli(0))); assertEquals("0", underTest.convert(Instant.ofEpochMilli(0))); } - + @Test public void testUnmarshallNull() { Instant actual = underTest.unmarshall(Instant.class, null); assertNull(actual); } - + @Test public void testUnmarshall() { assertEquals(Instant.ofEpochMilli(0), underTest.unmarshall(Instant.class, "0")); diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2IsoDynamoDBMarshallerTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2IsoDynamoDBMarshallerTest.java index c7787739..2872697f 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2IsoDynamoDBMarshallerTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2IsoDynamoDBMarshallerTest.java @@ -38,20 +38,20 @@ public void testNullMarshall() { assertNull(actual); } - + @Test public void testMarshall() { assertEquals("1970-01-01T00:00:00.000Z", underTest.marshall(Instant.ofEpochMilli(0))); assertEquals("1970-01-01T00:00:00.000Z", underTest.convert(Instant.ofEpochMilli(0))); } - + @Test public void testUnmarshallNull() { Instant actual = underTest.unmarshall(Instant.class, null); assertNull(actual); } - + @Test public void testUnmarshall() { assertEquals(Instant.ofEpochMilli(0), underTest.unmarshall(Instant.class, "1970-01-01T00:00:00.000Z")); diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractMultipleEntityQueryTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractMultipleEntityQueryTest.java index 7219f3f7..d814ce16 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractMultipleEntityQueryTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractMultipleEntityQueryTest.java @@ -34,49 +34,49 @@ @RunWith(MockitoJUnitRunner.class) public class AbstractMultipleEntityQueryTest { - private static class TestAbstractMultipleEntityQuery extends AbstractMultipleEntityQuery { - private final List resultList; + private static class TestAbstractMultipleEntityQuery extends AbstractMultipleEntityQuery { + private final List resultList; - public TestAbstractMultipleEntityQuery(DynamoDBOperations dynamoDBOperations, User... resultEntities) { - super(dynamoDBOperations, User.class); - resultList = Arrays.asList(resultEntities); - } + public TestAbstractMultipleEntityQuery(DynamoDBOperations dynamoDBOperations, User... resultEntities) { + super(dynamoDBOperations, User.class); + resultList = Arrays.asList(resultEntities); + } - @Override - public List getResultList() { - return resultList; - } - } + @Override + public List getResultList() { + return resultList; + } + } - @Rule - public ExpectedException expectedException = ExpectedException.none(); + @Rule + public ExpectedException expectedException = ExpectedException.none(); - @Mock - private DynamoDBOperations dynamoDBOperations; - @Mock - private User entity; + @Mock + private DynamoDBOperations dynamoDBOperations; + @Mock + private User entity; - private AbstractMultipleEntityQuery underTest; + private AbstractMultipleEntityQuery underTest; - @Test - public void testNullResult() { - underTest = new TestAbstractMultipleEntityQuery(dynamoDBOperations); + @Test + public void testNullResult() { + underTest = new TestAbstractMultipleEntityQuery(dynamoDBOperations); - assertNull(underTest.getSingleResult()); - } + assertNull(underTest.getSingleResult()); + } - @Test - public void testSingleResult() { - underTest = new TestAbstractMultipleEntityQuery(dynamoDBOperations, entity); + @Test + public void testSingleResult() { + underTest = new TestAbstractMultipleEntityQuery(dynamoDBOperations, entity); - assertSame(entity, underTest.getSingleResult()); - } + assertSame(entity, underTest.getSingleResult()); + } - @Test - public void testMultiResult() { - expectedException.expect(IncorrectResultSizeDataAccessException.class); - underTest = new TestAbstractMultipleEntityQuery(dynamoDBOperations, entity, entity); + @Test + public void testMultiResult() { + expectedException.expect(IncorrectResultSizeDataAccessException.class); + underTest = new TestAbstractMultipleEntityQuery(dynamoDBOperations, entity, entity); - underTest.getSingleResult(); - } + underTest.getSingleResult(); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractQueryTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractQueryTest.java index 1e9d633d..3655615a 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractQueryTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractQueryTest.java @@ -31,41 +31,41 @@ @RunWith(MockitoJUnitRunner.class) public class AbstractQueryTest { - private static class QueryTest extends AbstractQuery { - public QueryTest(DynamoDBOperations dynamoDBOperations, Class clazz) { - super(dynamoDBOperations, clazz); - } + private static class QueryTest extends AbstractQuery { + public QueryTest(DynamoDBOperations dynamoDBOperations, Class clazz) { + super(dynamoDBOperations, clazz); + } - @Override - public List getResultList() { - return null; - } + @Override + public List getResultList() { + return null; + } - @Override - public T getSingleResult() { - return null; - } - } + @Override + public T getSingleResult() { + return null; + } + } - @Mock - private DynamoDBOperations dynamoDBOperations; - private AbstractQuery underTest; + @Mock + private DynamoDBOperations dynamoDBOperations; + private AbstractQuery underTest; - @Before - public void setUp() { - underTest = new QueryTest<>(dynamoDBOperations, User.class); - } + @Before + public void setUp() { + underTest = new QueryTest<>(dynamoDBOperations, User.class); + } - @Test - public void testSetter() { - assertFalse(underTest.isScanCountEnabled()); - assertFalse(underTest.isScanEnabled()); + @Test + public void testSetter() { + assertFalse(underTest.isScanCountEnabled()); + assertFalse(underTest.isScanEnabled()); - underTest.setScanCountEnabled(true); - underTest.setScanEnabled(true); + underTest.setScanCountEnabled(true); + underTest.setScanEnabled(true); + + assertTrue(underTest.isScanCountEnabled()); + assertTrue(underTest.isScanEnabled()); + } - assertTrue(underTest.isScanCountEnabled()); - assertTrue(underTest.isScanEnabled()); - } - } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractSingleEntityQueryTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractSingleEntityQueryTest.java index 0ce95971..4856923a 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractSingleEntityQueryTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/query/AbstractSingleEntityQueryTest.java @@ -27,29 +27,29 @@ public class AbstractSingleEntityQueryTest { - @Mock - private DynamoDBOperations dynamoDBOperations; - @Mock - private User entity; - - private AbstractSingleEntityQuery underTest; - - @Before - public void setUp() { - underTest = new AbstractSingleEntityQuery(dynamoDBOperations, User.class) { - @Override - public User getSingleResult() { - return entity; - } - }; - } - - @Test - public void testGetResultList() { - List actual = underTest.getResultList(); - - assertEquals(1, actual.size()); - assertEquals(entity, actual.get(0)); - } + @Mock + private DynamoDBOperations dynamoDBOperations; + @Mock + private User entity; + + private AbstractSingleEntityQuery underTest; + + @Before + public void setUp() { + underTest = new AbstractSingleEntityQuery(dynamoDBOperations, User.class) { + @Override + public User getSingleResult() { + return entity; + } + }; + } + + @Test + public void testGetResultList() { + List actual = underTest.getResultList(); + + assertEquals(1, actual.size()); + assertEquals(entity, actual.get(0)); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/query/CountByHashAndRangeKeyQueryTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/query/CountByHashAndRangeKeyQueryTest.java index 163c9912..ac2e0dba 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/query/CountByHashAndRangeKeyQueryTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/query/CountByHashAndRangeKeyQueryTest.java @@ -30,35 +30,35 @@ @RunWith(MockitoJUnitRunner.class) public class CountByHashAndRangeKeyQueryTest { - private static final Class DOMAIN_CLASS = User.class; - @Mock - private DynamoDBOperations dynamoDBOperations; - @Mock - private User sampleEntity; - private Object hashKey; - private Object rangeKey; - private CountByHashAndRangeKeyQuery underTest; + private static final Class DOMAIN_CLASS = User.class; + @Mock + private DynamoDBOperations dynamoDBOperations; + @Mock + private User sampleEntity; + private Object hashKey; + private Object rangeKey; + private CountByHashAndRangeKeyQuery underTest; - @Before - public void setUp() { - hashKey = ThreadLocalRandom.current().nextLong(); - rangeKey = ThreadLocalRandom.current().nextLong(); - underTest = new CountByHashAndRangeKeyQuery(dynamoDBOperations, DOMAIN_CLASS, hashKey, rangeKey); - } + @Before + public void setUp() { + hashKey = ThreadLocalRandom.current().nextLong(); + rangeKey = ThreadLocalRandom.current().nextLong(); + underTest = new CountByHashAndRangeKeyQuery(dynamoDBOperations, DOMAIN_CLASS, hashKey, rangeKey); + } - @Test - public void testGetSingleResultExists() { - when(dynamoDBOperations.load(DOMAIN_CLASS, hashKey, rangeKey)).thenReturn(sampleEntity); - Long actual = underTest.getSingleResult(); + @Test + public void testGetSingleResultExists() { + when(dynamoDBOperations.load(DOMAIN_CLASS, hashKey, rangeKey)).thenReturn(sampleEntity); + Long actual = underTest.getSingleResult(); - assertEquals(Long.valueOf(1), actual); - } + assertEquals(Long.valueOf(1), actual); + } - @Test - public void testGetSingleResultDoesntExist() { - when(dynamoDBOperations.load(DOMAIN_CLASS, hashKey, rangeKey)).thenReturn(null); - Long actual = underTest.getSingleResult(); + @Test + public void testGetSingleResultDoesntExist() { + when(dynamoDBOperations.load(DOMAIN_CLASS, hashKey, rangeKey)).thenReturn(null); + Long actual = underTest.getSingleResult(); - assertEquals(Long.valueOf(0), actual); - } + assertEquals(Long.valueOf(0), actual); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/query/CountByHashKeyQueryTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/query/CountByHashKeyQueryTest.java index 9710d729..72ecca77 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/query/CountByHashKeyQueryTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/query/CountByHashKeyQueryTest.java @@ -30,33 +30,33 @@ @RunWith(MockitoJUnitRunner.class) public class CountByHashKeyQueryTest { - private static final Class DOMAIN_CLASS = User.class; - @Mock - private DynamoDBOperations dynamoDBOperations; - @Mock - private User sampleEntity; - private Object hashKey; - private CountByHashKeyQuery underTest; - - @Before - public void setUp() { - hashKey = ThreadLocalRandom.current().nextLong(); - underTest = new CountByHashKeyQuery(dynamoDBOperations, DOMAIN_CLASS, hashKey); - } - - @Test - public void testGetSingleResultExists() { - when(dynamoDBOperations.load(DOMAIN_CLASS, hashKey)).thenReturn(sampleEntity); - Long actual = underTest.getSingleResult(); - - assertEquals(Long.valueOf(1), actual); - } - - @Test - public void testGetSingleResultDoesntExist() { - when(dynamoDBOperations.load(DOMAIN_CLASS, hashKey)).thenReturn(null); - Long actual = underTest.getSingleResult(); - - assertEquals(Long.valueOf(0), actual); - } + private static final Class DOMAIN_CLASS = User.class; + @Mock + private DynamoDBOperations dynamoDBOperations; + @Mock + private User sampleEntity; + private Object hashKey; + private CountByHashKeyQuery underTest; + + @Before + public void setUp() { + hashKey = ThreadLocalRandom.current().nextLong(); + underTest = new CountByHashKeyQuery(dynamoDBOperations, DOMAIN_CLASS, hashKey); + } + + @Test + public void testGetSingleResultExists() { + when(dynamoDBOperations.load(DOMAIN_CLASS, hashKey)).thenReturn(sampleEntity); + Long actual = underTest.getSingleResult(); + + assertEquals(Long.valueOf(1), actual); + } + + @Test + public void testGetSingleResultDoesntExist() { + when(dynamoDBOperations.load(DOMAIN_CLASS, hashKey)).thenReturn(null); + Long actual = underTest.getSingleResult(); + + assertEquals(Long.valueOf(0), actual); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/query/QueryExpressionCountQueryTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/query/QueryExpressionCountQueryTest.java index ea83f4d2..0c7e3def 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/query/QueryExpressionCountQueryTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/query/QueryExpressionCountQueryTest.java @@ -31,26 +31,26 @@ @RunWith(MockitoJUnitRunner.class) public class QueryExpressionCountQueryTest { - @Mock - private DynamoDBOperations dynamoDBOperations; - @Mock - private DynamoDBQueryExpression queryExpression; + @Mock + private DynamoDBOperations dynamoDBOperations; + @Mock + private DynamoDBQueryExpression queryExpression; - private QueryExpressionCountQuery underTest; + private QueryExpressionCountQuery underTest; - @Before - public void setUp() { - underTest = new QueryExpressionCountQuery<>(dynamoDBOperations, User.class, queryExpression); - } + @Before + public void setUp() { + underTest = new QueryExpressionCountQuery<>(dynamoDBOperations, User.class, queryExpression); + } - @Test - public void testGetSingleResult() { - int expected = ThreadLocalRandom.current().nextInt(); - when(dynamoDBOperations.count(User.class, queryExpression)).thenReturn(expected); + @Test + public void testGetSingleResult() { + int expected = ThreadLocalRandom.current().nextInt(); + when(dynamoDBOperations.count(User.class, queryExpression)).thenReturn(expected); - Long actual = underTest.getSingleResult(); + Long actual = underTest.getSingleResult(); - assertEquals(Long.valueOf(expected), actual); - } + assertEquals(Long.valueOf(expected), actual); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/query/QueryRequestCountQueryTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/query/QueryRequestCountQueryTest.java index 209317c9..40599e06 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/query/QueryRequestCountQueryTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/query/QueryRequestCountQueryTest.java @@ -30,25 +30,25 @@ @RunWith(MockitoJUnitRunner.class) public class QueryRequestCountQueryTest { - @Mock - private DynamoDBOperations dynamoDBOperations; - @Mock - private QueryRequest queryRequest; + @Mock + private DynamoDBOperations dynamoDBOperations; + @Mock + private QueryRequest queryRequest; - private QueryRequestCountQuery underTest; + private QueryRequestCountQuery underTest; - @Before - public void setUp() { - underTest = new QueryRequestCountQuery(dynamoDBOperations, queryRequest); - } + @Before + public void setUp() { + underTest = new QueryRequestCountQuery(dynamoDBOperations, queryRequest); + } - @Test - public void testGetSingleResult() { - int expected = ThreadLocalRandom.current().nextInt(); - when(dynamoDBOperations.count(Long.class, queryRequest)).thenReturn(expected); + @Test + public void testGetSingleResult() { + int expected = ThreadLocalRandom.current().nextInt(); + when(dynamoDBOperations.count(Long.class, queryRequest)).thenReturn(expected); - Long actual = underTest.getSingleResult(); + Long actual = underTest.getSingleResult(); - assertEquals(Long.valueOf(expected), actual); - } + assertEquals(Long.valueOf(expected), actual); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/query/ScanExpressionCountQueryTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/query/ScanExpressionCountQueryTest.java index 63c7d2df..0871692a 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/query/ScanExpressionCountQueryTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/query/ScanExpressionCountQueryTest.java @@ -30,52 +30,52 @@ @RunWith(MockitoJUnitRunner.class) public class ScanExpressionCountQueryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); + @Rule + public ExpectedException expectedException = ExpectedException.none(); - @Mock - private DynamoDBOperations dynamoDBOperations; - @Mock - private DynamoDBScanExpression scanExpression; + @Mock + private DynamoDBOperations dynamoDBOperations; + @Mock + private DynamoDBScanExpression scanExpression; - private ScanExpressionCountQuery underTest; + private ScanExpressionCountQuery underTest; - @Test - public void testScanCountEnabledTrueTrue() { - underTest = new ScanExpressionCountQuery<>(dynamoDBOperations, User.class, scanExpression, true); + @Test + public void testScanCountEnabledTrueTrue() { + underTest = new ScanExpressionCountQuery<>(dynamoDBOperations, User.class, scanExpression, true); - underTest.assertScanCountEnabled(true); + underTest.assertScanCountEnabled(true); - assertTrue(true); - } + assertTrue(true); + } - @Test - public void testScanCountEnabledTrueFalse() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Scanning for the total counts for this query is not enabled. " + - " To enable annotate your repository method with @EnableScanCount, or enable scanning for all repository methods by annotating your repository interface with @EnableScanCount. " + - " This total count is required to serve this Page query - if total counts are not desired an alternative approach could be to replace the Page query with a Slice query "); - underTest = new ScanExpressionCountQuery<>(dynamoDBOperations, User.class, scanExpression, true); + @Test + public void testScanCountEnabledTrueFalse() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Scanning for the total counts for this query is not enabled. " + + " To enable annotate your repository method with @EnableScanCount, or enable scanning for all repository methods by annotating your repository interface with @EnableScanCount. " + + " This total count is required to serve this Page query - if total counts are not desired an alternative approach could be to replace the Page query with a Slice query "); + underTest = new ScanExpressionCountQuery<>(dynamoDBOperations, User.class, scanExpression, true); - underTest.assertScanCountEnabled(false); - } + underTest.assertScanCountEnabled(false); + } - @Test - public void testScanCountEnabledFalseTrue() { - underTest = new ScanExpressionCountQuery<>(dynamoDBOperations, User.class, scanExpression, false); + @Test + public void testScanCountEnabledFalseTrue() { + underTest = new ScanExpressionCountQuery<>(dynamoDBOperations, User.class, scanExpression, false); - underTest.assertScanCountEnabled(true); + underTest.assertScanCountEnabled(true); - assertTrue(true); - } + assertTrue(true); + } - @Test - public void testScanCountEnabledFalseFalse() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Scanning for counts for this query is not enabled. " + - " To enable annotate your repository method with @EnableScanCount, or enable scanning for all repository methods by annotating your repository interface with @EnableScanCount"); - underTest = new ScanExpressionCountQuery<>(dynamoDBOperations, User.class, scanExpression, false); + @Test + public void testScanCountEnabledFalseFalse() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Scanning for counts for this query is not enabled. " + + " To enable annotate your repository method with @EnableScanCount, or enable scanning for all repository methods by annotating your repository interface with @EnableScanCount"); + underTest = new ScanExpressionCountQuery<>(dynamoDBOperations, User.class, scanExpression, false); - underTest.assertScanCountEnabled(false); - } + underTest.assertScanCountEnabled(false); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/DynamoDBHashAndRangeKeyTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/DynamoDBHashAndRangeKeyTest.java index 806d05d6..8c828a05 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/DynamoDBHashAndRangeKeyTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/DynamoDBHashAndRangeKeyTest.java @@ -26,35 +26,35 @@ @RunWith(MockitoJUnitRunner.class) public class DynamoDBHashAndRangeKeyTest { - @Mock - private Object hash; - @Mock - private Object range; + @Mock + private Object hash; + @Mock + private Object range; - @Test - public void testConstructor() { - DynamoDBHashAndRangeKey underTest = new DynamoDBHashAndRangeKey(hash, range); + @Test + public void testConstructor() { + DynamoDBHashAndRangeKey underTest = new DynamoDBHashAndRangeKey(hash, range); - assertEquals(hash, underTest.getHashKey()); - assertEquals(range, underTest.getRangeKey()); - } + assertEquals(hash, underTest.getHashKey()); + assertEquals(range, underTest.getRangeKey()); + } - @Test - public void testDefaultConstructor() { - DynamoDBHashAndRangeKey underTest = new DynamoDBHashAndRangeKey(); + @Test + public void testDefaultConstructor() { + DynamoDBHashAndRangeKey underTest = new DynamoDBHashAndRangeKey(); - assertNull(underTest.getHashKey()); - assertNull(underTest.getRangeKey()); - } + assertNull(underTest.getHashKey()); + assertNull(underTest.getRangeKey()); + } - @Test - public void testGetterSetter() { - DynamoDBHashAndRangeKey underTest = new DynamoDBHashAndRangeKey(); + @Test + public void testGetterSetter() { + DynamoDBHashAndRangeKey underTest = new DynamoDBHashAndRangeKey(); - underTest.setHashKey(hash); - underTest.setRangeKey(range); + underTest.setHashKey(hash); + underTest.setRangeKey(range); - assertEquals(hash, underTest.getHashKey()); - assertEquals(range, underTest.getRangeKey()); - } + assertEquals(hash, underTest.getHashKey()); + assertEquals(range, underTest.getRangeKey()); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryBeanTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryBeanTest.java index dec7e335..1a6f72b8 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryBeanTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/cdi/DynamoDBRepositoryBeanTest.java @@ -40,80 +40,83 @@ @RunWith(MockitoJUnitRunner.class) public class DynamoDBRepositoryBeanTest { - interface SampleRepository extends Repository { - } - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Mock - private CreationalContext creationalContext; - @Mock - private BeanManager beanManager; - @Mock - private Bean amazonDynamoDBBean; - @Mock - private AmazonDynamoDB amazonDynamoDB; - @Mock - private javax.enterprise.inject.spi.Bean dynamoDBMapperConfigBean; - @Mock - private Bean dynamoDBOperationsBean; - - private Set qualifiers = Collections.emptySet(); - private Class repositoryType = SampleRepository.class; - - @Before - public void setUp() { - when(beanManager.createCreationalContext(amazonDynamoDBBean)).thenReturn(creationalContext); - when(beanManager.getReference(amazonDynamoDBBean, AmazonDynamoDB.class, creationalContext)).thenReturn(amazonDynamoDB); - } - - @Test - public void testNullOperationsOk() { - DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, amazonDynamoDBBean, - dynamoDBMapperConfigBean, null, qualifiers, repositoryType); - - assertNotNull(underTest); - } - - @Test - public void testNullOperationFail() { - expectedException.expectMessage("amazonDynamoDBBean must not be null!"); - - DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, null, - dynamoDBMapperConfigBean, null, qualifiers, repositoryType); - } - - @Test - public void testSetOperationOk1() { - DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, null, - null, dynamoDBOperationsBean, qualifiers, repositoryType); - - assertNotNull(underTest); - } - - @Test - public void testSetOperationFail1() { - expectedException.expectMessage("Cannot specify both dynamoDBMapperConfigBean bean and dynamoDBOperationsBean in repository configuration"); - - DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, null, - dynamoDBMapperConfigBean, dynamoDBOperationsBean, qualifiers, repositoryType); - } - - @Test - public void testSetOperationFail2() { - expectedException.expectMessage("Cannot specify both amazonDynamoDB bean and dynamoDBOperationsBean in repository configuration"); - - DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, amazonDynamoDBBean, - null, dynamoDBOperationsBean, qualifiers, repositoryType); - } - - @Test - public void testCreateRepostiory() { - DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, amazonDynamoDBBean, - dynamoDBMapperConfigBean, null, qualifiers, repositoryType); - - SampleRepository actual = underTest.create(creationalContext, SampleRepository.class); - assertNotNull(actual); - } + interface SampleRepository extends Repository { + } + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Mock + private CreationalContext creationalContext; + @Mock + private BeanManager beanManager; + @Mock + private Bean amazonDynamoDBBean; + @Mock + private AmazonDynamoDB amazonDynamoDB; + @Mock + private javax.enterprise.inject.spi.Bean dynamoDBMapperConfigBean; + @Mock + private Bean dynamoDBOperationsBean; + + private Set qualifiers = Collections.emptySet(); + private Class repositoryType = SampleRepository.class; + + @Before + public void setUp() { + when(beanManager.createCreationalContext(amazonDynamoDBBean)).thenReturn(creationalContext); + when(beanManager.getReference(amazonDynamoDBBean, AmazonDynamoDB.class, creationalContext)) + .thenReturn(amazonDynamoDB); + } + + @Test + public void testNullOperationsOk() { + DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, amazonDynamoDBBean, + dynamoDBMapperConfigBean, null, qualifiers, repositoryType); + + assertNotNull(underTest); + } + + @Test + public void testNullOperationFail() { + expectedException.expectMessage("amazonDynamoDBBean must not be null!"); + + DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, null, + dynamoDBMapperConfigBean, null, qualifiers, repositoryType); + } + + @Test + public void testSetOperationOk1() { + DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, null, null, + dynamoDBOperationsBean, qualifiers, repositoryType); + + assertNotNull(underTest); + } + + @Test + public void testSetOperationFail1() { + expectedException.expectMessage( + "Cannot specify both dynamoDBMapperConfigBean bean and dynamoDBOperationsBean in repository configuration"); + + DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, null, + dynamoDBMapperConfigBean, dynamoDBOperationsBean, qualifiers, repositoryType); + } + + @Test + public void testSetOperationFail2() { + expectedException.expectMessage( + "Cannot specify both amazonDynamoDB bean and dynamoDBOperationsBean in repository configuration"); + + DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, amazonDynamoDBBean, + null, dynamoDBOperationsBean, qualifiers, repositoryType); + } + + @Test + public void testCreateRepostiory() { + DynamoDBRepositoryBean underTest = new DynamoDBRepositoryBean(beanManager, amazonDynamoDBBean, + dynamoDBMapperConfigBean, null, qualifiers, repositoryType); + + SampleRepository actual = underTest.create(creationalContext, SampleRepository.class); + assertNotNull(actual); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCriteriaUnitTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCriteriaUnitTest.java index 304d4a5b..a756c585 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCriteriaUnitTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/AbstractDynamoDBQueryCriteriaUnitTest.java @@ -27,20 +27,18 @@ import java.util.List; import java.util.TimeZone; - -public abstract class AbstractDynamoDBQueryCriteriaUnitTest> { +public abstract class AbstractDynamoDBQueryCriteriaUnitTest> { protected C criteria; @Test - public void addAttributeValueTest_WhenValueIsSingleDate() throws ParseException - { + public void addAttributeValueTest_WhenValueIsSingleDate() throws ParseException { // Setup date formats for EST and UCT DateFormat estDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); estDateFormat.setTimeZone(TimeZone.getTimeZone("EST")); DateFormat utcDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); utcDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - + // Generate a Date object using a fixed EST date string String dateInESTString = "2014-02-12T02:34:00.000Z"; Date now = estDateFormat.parse(dateInESTString); @@ -50,27 +48,27 @@ public void addAttributeValueTest_WhenValueIsSingleDate() throws ParseException // Sanity check - confirm that the EST and UTC strings aren't equal Assert.assertNotEquals(dateInESTString, dateInUTCString); - + List attributeValueList = new ArrayList(); - // Add "now" as an attribute value - a Date object originally generated from EST string - criteria.addAttributeValue(attributeValueList , now, "someDateProperty", Date.class, false); - + // Add "now" as an attribute value - a Date object originally generated from EST + // string + criteria.addAttributeValue(attributeValueList, now, "someDateProperty", Date.class, false); + AttributeValue resultingValue = attributeValueList.get(0); - + // Ensuring that the resulting AttributeValue is encoded as a UTC string - Assert.assertEquals(dateInUTCString,resultingValue.getS()); + Assert.assertEquals(dateInUTCString, resultingValue.getS()); } - + @Test - public void addAttributeValueTest_WhenValueIsDateCollection() throws ParseException - { + public void addAttributeValueTest_WhenValueIsDateCollection() throws ParseException { // Setup date formats for EST and UCT DateFormat estDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); estDateFormat.setTimeZone(TimeZone.getTimeZone("EST")); DateFormat utcDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); utcDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - + // Generate a Date object using a fixed EST date string String dateInESTString = "2014-02-12T02:34:00.000Z"; Date now = estDateFormat.parse(dateInESTString); @@ -80,22 +78,23 @@ public void addAttributeValueTest_WhenValueIsDateCollection() throws ParseExcept // Sanity check - confirm that the EST and UTC strings aren't equal Assert.assertNotEquals(dateInESTString, dateInUTCString); - + List attributeValueList = new ArrayList(); List dateList = new ArrayList(); dateList.add(now); - + List dateStringList = new ArrayList(); dateStringList.add(dateInUTCString); - - // Add "now" as an attribute value - a Date object originally generated from EST string - criteria.addAttributeValue(attributeValueList , dateList, "someDateProperty", Date.class, true); - + + // Add "now" as an attribute value - a Date object originally generated from EST + // string + criteria.addAttributeValue(attributeValueList, dateList, "someDateProperty", Date.class, true); + AttributeValue resultingValue = attributeValueList.get(0); - + // Ensuring that the resulting AttributeValue is encoded as a UTC string - Assert.assertEquals(dateStringList,resultingValue.getSS()); + Assert.assertEquals(dateStringList, resultingValue.getSS()); } - + } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashAndRangeKeyCriteriaUnitTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashAndRangeKeyCriteriaUnitTest.java index 2e4a676c..49a601d9 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashAndRangeKeyCriteriaUnitTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashAndRangeKeyCriteriaUnitTest.java @@ -26,257 +26,227 @@ import org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBIdIsHashAndRangeKeyEntityInformation; @RunWith(MockitoJUnitRunner.class) -public class DynamoDBEntityWithHashAndRangeKeyCriteriaUnitTest extends AbstractDynamoDBQueryCriteriaUnitTest> { - +public class DynamoDBEntityWithHashAndRangeKeyCriteriaUnitTest + extends + AbstractDynamoDBQueryCriteriaUnitTest> { + @Mock - private DynamoDBIdIsHashAndRangeKeyEntityInformation entityInformation; - - + private DynamoDBIdIsHashAndRangeKeyEntityInformation entityInformation; + @Before - public void setUp() - { + public void setUp() { Mockito.when(entityInformation.getHashKeyPropertyName()).thenReturn("userName"); Mockito.when(entityInformation.getRangeKeyPropertyName()).thenReturn("playlistName"); criteria = new DynamoDBEntityWithHashAndRangeKeyCriteria<>(entityInformation, null); } - + @Test - public void testHasIndexHashKeyEqualConditionAnd_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsAnIndexHashKeyButNotAHashKeyOrRangeKey() - { + public void testHasIndexHashKeyEqualConditionAnd_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsAnIndexHashKeyButNotAHashKeyOrRangeKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); criteria.withPropertyEquals("displayName", "some display name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertTrue(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexHashKeyButIsAHashKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexHashKeyButIsAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("userName")).thenReturn(false); criteria.withPropertyEquals("userName", "some user name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexHashKeyButIsARangeKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexHashKeyButIsARangeKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("playlistName")).thenReturn(false); criteria.withPropertyEquals("playlistName", "some playlist name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsBothAnIndexHashKeyAndAHashKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsBothAnIndexHashKeyAndAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("userName")).thenReturn(true); criteria.withPropertyEquals("userName", "some user name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertTrue(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsBothAnIndexHashKeyAndARangeKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsBothAnIndexHashKeyAndARangeKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("playlistName")).thenReturn(true); criteria.withPropertyEquals("playlistName", "some playlist name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertTrue(hasIndexHashKeyEqualCondition); } - - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKeyOrRangeKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKeyOrRangeKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("displayName")).thenReturn(false); criteria.withPropertyEquals("displayName", "some display name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKeyButIsRangeKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKeyButIsRangeKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("playlistName")).thenReturn(false); criteria.withPropertyEquals("playlistName", "some playlist name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKeyOrRangeKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKeyOrRangeKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); criteria.withPropertyEquals("displayName", "some display name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertTrue(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKeyAndIsARangeKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKeyAndIsARangeKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("playlistName")).thenReturn(true); criteria.withPropertyEquals("playlistName", "some playlist name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertTrue(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexRangeKeyButIsAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexRangeKeyButIsAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("userName")).thenReturn(false); criteria.withPropertyEquals("userName", "some user name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertFalse(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexRangeKeyButIsARangeKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexRangeKeyButIsARangeKey() { criteria.withPropertyEquals("playlist name", "some playlist name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertFalse(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsBothAnIndexRangeKeyAndAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsBothAnIndexRangeKeyAndAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("userName")).thenReturn(true); criteria.withPropertyEquals("userName", "some user name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertTrue(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKeyOrARangeKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKeyOrARangeKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(false); criteria.withPropertyEquals("displayName", "some display name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertFalse(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKeyButIsARangeKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKeyButIsARangeKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("playlistName")).thenReturn(false); criteria.withPropertyEquals("playlistName", "some playlist name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertFalse(hasIndexRangeKeyCondition); } - + // repeat - + @Test - public void testHasIndexHashKeyEqualConditionAnd_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexHashKeyButNotAHashKeyOrRangeKey() - { + public void testHasIndexHashKeyEqualConditionAnd_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexHashKeyButNotAHashKeyOrRangeKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); - criteria.withPropertyBetween("displayName", "some display name","some other display name", String.class); + criteria.withPropertyBetween("displayName", "some display name", "some other display name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualConditionAnd_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexHashKeyButNotAHashKeyButIsARangeKey() - { + public void testHasIndexHashKeyEqualConditionAnd_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexHashKeyButNotAHashKeyButIsARangeKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("playlistName")).thenReturn(true); - criteria.withPropertyBetween("playlistName", "some playlist name","some other playlist name", String.class); + criteria.withPropertyBetween("playlistName", "some playlist name", "some other playlist name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNotAnIndexHashKeyButIsAHashKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNotAnIndexHashKeyButIsAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("userName")).thenReturn(false); - criteria.withPropertyBetween("userName", "some user name","some other user name", String.class); + criteria.withPropertyBetween("userName", "some user name", "some other user name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsBothAnIndexHashKeyAndAHashKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsBothAnIndexHashKeyAndAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("userName")).thenReturn(true); - criteria.withPropertyBetween("userName", "some user name","some other user name", String.class); + criteria.withPropertyBetween("userName", "some user name", "some other user name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKeyOrARangeKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKeyOrARangeKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("displayName")).thenReturn(false); - criteria.withPropertyBetween("displayName", "some display name","some other display name", String.class); + criteria.withPropertyBetween("displayName", "some display name", "some other display name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKeyButIsARangeKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKeyButIsARangeKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("playlistName")).thenReturn(false); - criteria.withPropertyBetween("playlistName", "some playlist name","some other playlist name", String.class); + criteria.withPropertyBetween("playlistName", "some playlist name", "some other playlist name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKeyOrARangeKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKeyOrARangeKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); - criteria.withPropertyBetween("displayName", "some display name","some other display name", String.class); + criteria.withPropertyBetween("displayName", "some display name", "some other display name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertTrue(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKeyButIsARangeKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKeyButIsARangeKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("playlistName")).thenReturn(true); - criteria.withPropertyBetween("playlistName", "some playlist name","some other playlist name", String.class); + criteria.withPropertyBetween("playlistName", "some playlist name", "some other playlist name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertTrue(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNotAnIndexRangeKeyButIsAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNotAnIndexRangeKeyButIsAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("userName")).thenReturn(false); - criteria.withPropertyBetween("userName", "some user name","some other user name", String.class); + criteria.withPropertyBetween("userName", "some user name", "some other user name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertFalse(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsBothAnIndexRangeKeyAndAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsBothAnIndexRangeKeyAndAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("userName")).thenReturn(true); - criteria.withPropertyBetween("userName", "some user name","some other user name", String.class); + criteria.withPropertyBetween("userName", "some user name", "some other user name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertTrue(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKeyOrARangeKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKeyOrARangeKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(false); - criteria.withPropertyBetween("displayName", "some display name","some other display name", String.class); + criteria.withPropertyBetween("displayName", "some display name", "some other display name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertFalse(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKeyButIsARangeKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKeyButIsARangeKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("playlistName")).thenReturn(false); - criteria.withPropertyBetween("playlistName", "some playlist name","some other playlist name", String.class); + criteria.withPropertyBetween("playlistName", "some playlist name", "some other playlist name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertFalse(hasIndexRangeKeyCondition); } - - - - + } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashKeyOnlyCriteriaUnitTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashKeyOnlyCriteriaUnitTest.java index 3816c071..8005f105 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashKeyOnlyCriteriaUnitTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBEntityWithHashKeyOnlyCriteriaUnitTest.java @@ -28,166 +28,147 @@ import java.util.Date; @RunWith(MockitoJUnitRunner.class) -public class DynamoDBEntityWithHashKeyOnlyCriteriaUnitTest extends AbstractDynamoDBQueryCriteriaUnitTest> { +public class DynamoDBEntityWithHashKeyOnlyCriteriaUnitTest + extends + AbstractDynamoDBQueryCriteriaUnitTest> { @Mock - private DynamoDBEntityInformation entityInformation; - - + private DynamoDBEntityInformation entityInformation; + @Before - public void setUp() - { + public void setUp() { Mockito.when(entityInformation.getHashKeyPropertyName()).thenReturn("id"); criteria = new DynamoDBEntityWithHashKeyOnlyCriteria<>(entityInformation, null); } - + @Test - public void testHasIndexHashKeyEqualConditionAnd_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsAnIndexHashKeyButNotAHashKey() - { + public void testHasIndexHashKeyEqualConditionAnd_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsAnIndexHashKeyButNotAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("name")).thenReturn(true); criteria.withPropertyEquals("name", "some name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertTrue(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexHashKeyButIsAHashKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexHashKeyButIsAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("id")).thenReturn(false); criteria.withPropertyEquals("id", "some id", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsBothAnIndexHashKeyAndAHashKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsBothAnIndexHashKeyAndAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("id")).thenReturn(true); criteria.withPropertyEquals("id", "some id", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertTrue(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("joinDate")).thenReturn(false); criteria.withPropertyEquals("joinDate", new Date(), Date.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("name")).thenReturn(true); criteria.withPropertyEquals("name", "some name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertTrue(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexRangeKeyButIsAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNotAnIndexRangeKeyButIsAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("id")).thenReturn(false); criteria.withPropertyEquals("id", "some id", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertFalse(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsBothAnIndexRangeKeyAndAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsBothAnIndexRangeKeyAndAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("id")).thenReturn(true); criteria.withPropertyEquals("id", "some id", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertTrue(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsEqualityOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("joinDate")).thenReturn(false); criteria.withPropertyEquals("joinDate", new Date(), Date.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertFalse(hasIndexRangeKeyCondition); } - + // repeat - + @Test - public void testHasIndexHashKeyEqualConditionAnd_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexHashKeyButNotAHashKey() - { + public void testHasIndexHashKeyEqualConditionAnd_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexHashKeyButNotAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("name")).thenReturn(true); - criteria.withPropertyBetween("name", "some name","some other name", String.class); + criteria.withPropertyBetween("name", "some name", "some other name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNotAnIndexHashKeyButIsAHashKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNotAnIndexHashKeyButIsAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("name")).thenReturn(false); - criteria.withPropertyBetween("name", "some name","some other name", String.class); + criteria.withPropertyBetween("name", "some name", "some other name", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsBothAnIndexHashKeyAndAHashKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsBothAnIndexHashKeyAndAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("id")).thenReturn(true); - criteria.withPropertyBetween("id", "some id","some other id", String.class); + criteria.withPropertyBetween("id", "some id", "some other id", String.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKey() - { + public void testHasIndexHashKeyEqualCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexHashKeyOrAHashKey() { Mockito.when(entityInformation.isGlobalIndexHashKeyProperty("joinDate")).thenReturn(false); - criteria.withPropertyBetween("joinDate", new Date(),new Date(), Date.class); + criteria.withPropertyBetween("joinDate", new Date(), new Date(), Date.class); boolean hasIndexHashKeyEqualCondition = criteria.hasIndexHashKeyEqualCondition(); Assert.assertFalse(hasIndexHashKeyEqualCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsAnIndexRangeKeyButNotAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("name")).thenReturn(true); - criteria.withPropertyBetween("name", "some name","some other name", String.class); + criteria.withPropertyBetween("name", "some name", "some other name", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertTrue(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNotAnIndexRangeKeyButIsAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNotAnIndexRangeKeyButIsAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("id")).thenReturn(false); - criteria.withPropertyBetween("id", "some id","some other id", String.class); + criteria.withPropertyBetween("id", "some id", "some other id", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertFalse(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsBothAnIndexRangeKeyAndAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsBothAnIndexRangeKeyAndAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("id")).thenReturn(true); - criteria.withPropertyBetween("id", "some id","some other id", String.class); + criteria.withPropertyBetween("id", "some id", "some other id", String.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertTrue(hasIndexRangeKeyCondition); } - + @Test - public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKey() - { + public void testHasIndexRangeKeyCondition_WhenConditionCriteriaIsNonEqualityConditionOnAPropertyWhichIsNeitherAnIndexRangeKeyOrAHashKey() { Mockito.when(entityInformation.isGlobalIndexRangeKeyProperty("joinDate")).thenReturn(false); - criteria.withPropertyBetween("joinDate", new Date(),new Date(), Date.class); + criteria.withPropertyBetween("joinDate", new Date(), new Date(), Date.class); boolean hasIndexRangeKeyCondition = criteria.hasIndexRangeKeyCondition(); Assert.assertFalse(hasIndexRangeKeyCondition); } - - - - + } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryLookupStrategyTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryLookupStrategyTest.java index 9a06494f..1e13bbd8 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryLookupStrategyTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/DynamoDBQueryLookupStrategyTest.java @@ -30,35 +30,35 @@ @RunWith(MockitoJUnitRunner.class) public class DynamoDBQueryLookupStrategyTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Mock - private DynamoDBOperations dynamoDBOperations; + @Rule + public ExpectedException expectedException = ExpectedException.none(); + @Mock + private DynamoDBOperations dynamoDBOperations; - @Test - public void testCreate() { - QueryLookupStrategy actual; - actual = DynamoDBQueryLookupStrategy.create(dynamoDBOperations, Key.CREATE); - assertNotNull(actual); + @Test + public void testCreate() { + QueryLookupStrategy actual; + actual = DynamoDBQueryLookupStrategy.create(dynamoDBOperations, Key.CREATE); + assertNotNull(actual); - actual = DynamoDBQueryLookupStrategy.create(dynamoDBOperations, Key.CREATE_IF_NOT_FOUND); - assertNotNull(actual); - } + actual = DynamoDBQueryLookupStrategy.create(dynamoDBOperations, Key.CREATE_IF_NOT_FOUND); + assertNotNull(actual); + } - @Test - public void testNull() { - QueryLookupStrategy actualNull = DynamoDBQueryLookupStrategy.create(dynamoDBOperations, null); - QueryLookupStrategy actualCreate = DynamoDBQueryLookupStrategy.create(dynamoDBOperations, Key.CREATE); + @Test + public void testNull() { + QueryLookupStrategy actualNull = DynamoDBQueryLookupStrategy.create(dynamoDBOperations, null); + QueryLookupStrategy actualCreate = DynamoDBQueryLookupStrategy.create(dynamoDBOperations, Key.CREATE); - assertSame(actualNull.getClass(), actualCreate.getClass()); - } + assertSame(actualNull.getClass(), actualCreate.getClass()); + } - @Test - public void testDeclaredQuery() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unsupported query lookup strategy USE_DECLARED_QUERY!"); + @Test + public void testDeclaredQuery() { + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Unsupported query lookup strategy USE_DECLARED_QUERY!"); - DynamoDBQueryLookupStrategy.create(dynamoDBOperations, Key.USE_DECLARED_QUERY); - } + DynamoDBQueryLookupStrategy.create(dynamoDBOperations, Key.USE_DECLARED_QUERY); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/PartTreeDynamoDBQueryUnitTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/PartTreeDynamoDBQueryUnitTest.java index c3817f2b..b8013b7c 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/PartTreeDynamoDBQueryUnitTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/query/PartTreeDynamoDBQueryUnitTest.java @@ -76,18 +76,18 @@ public class PartTreeDynamoDBQueryUnitTest { private DynamoDBQueryMethod mockDynamoDBUserQueryMethod; @Mock - private DynamoDBEntityInformation mockUserEntityMetadata; + private DynamoDBEntityInformation mockUserEntityMetadata; @Mock private DynamoDBQueryMethod mockDynamoDBPlaylistQueryMethod; @Mock - private DynamoDBIdIsHashAndRangeKeyEntityInformation mockPlaylistEntityMetadata; + private DynamoDBIdIsHashAndRangeKeyEntityInformation mockPlaylistEntityMetadata; @Mock @SuppressWarnings("rawtypes") private Parameters mockParameters; - + @Mock private User mockUser; @@ -120,7 +120,7 @@ public void setUp() { Mockito.when(mockPlaylistEntityMetadata.isCompositeHashAndRangeKeyProperty("playlistId")).thenReturn(true); Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropertyName()).thenReturn("userName"); -// Mockito.when(mockPlaylistEntityMetadata.isHashKeyProperty("userName")).thenReturn(true); + // Mockito.when(mockPlaylistEntityMetadata.isHashKeyProperty("userName")).thenReturn(true); Mockito.when(mockPlaylistEntityMetadata.getJavaType()).thenReturn(Playlist.class); Mockito.when(mockPlaylistEntityMetadata.getRangeKeyPropertyName()).thenReturn("playlistName"); Mockito.when(mockPlaylistEntityMetadata.getIndexRangeKeyPropertyNames()).thenReturn(new HashSet()); @@ -129,14 +129,14 @@ public void setUp() { Mockito.when(mockDynamoDBPlaylistQueryMethod.getEntityInformation()).thenReturn(mockPlaylistEntityMetadata); Mockito.when(mockDynamoDBPlaylistQueryMethod.getParameters()).thenReturn(mockParameters); Mockito.when(mockUserEntityMetadata.getHashKeyPropertyName()).thenReturn("id"); -// Mockito.when(mockUserEntityMetadata.isHashKeyProperty("id")).thenReturn(true); + // Mockito.when(mockUserEntityMetadata.isHashKeyProperty("id")).thenReturn(true); Mockito.when(mockUserEntityMetadata.getJavaType()).thenReturn(User.class); Mockito.when(mockDynamoDBUserQueryMethod.isScanEnabled()).thenReturn(true); Mockito.when(mockDynamoDBPlaylistQueryMethod.isScanEnabled()).thenReturn(true); } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) private void setupCommonMocksForThisRepositoryMethod( DynamoDBEntityInformation mockEntityMetadata, DynamoDBQueryMethod mockDynamoDBQueryMethod, Class clazz, String repositoryMethodName, int numberOfParameters, String hashKeyProperty, @@ -146,19 +146,23 @@ private void setupCommonMocksForThisRepositoryMetho Mockito.when(mockEntityMetadata.isRangeKeyAware()).thenReturn(true); } - // Dirty Harry 9 3/4: In recent versions of spring-data-commons, a lot of methods within - // org.springframework.data.repository.query.QueryMethod have become final. Thus they can't - // be mocked by Mockito anymore https://github.com/mockito/mockito/wiki/FAQ#what-are-the-limitations-of-mockito + // Dirty Harry 9 3/4: In recent versions of spring-data-commons, a lot of + // methods within + // org.springframework.data.repository.query.QueryMethod have become final. Thus + // they can't + // be mocked by Mockito anymore + // https://github.com/mockito/mockito/wiki/FAQ#what-are-the-limitations-of-mockito // Therefore setting the field explicitly that is used by all the isXXX methods try { Field unwrappedReturnTypeField = mockDynamoDBQueryMethod.getClass() // Mockito-generated class - .getSuperclass() // org.socialsignin.spring.data.dynamodb.repository.query.DynamoDBQueryMethod - .getSuperclass() // org.springframework.data.repository.query.QueryMethod - .getDeclaredField("unwrappedReturnType"); + .getSuperclass() // org.socialsignin.spring.data.dynamodb.repository.query.DynamoDBQueryMethod + .getSuperclass() // org.springframework.data.repository.query.QueryMethod + .getDeclaredField("unwrappedReturnType"); unwrappedReturnTypeField.setAccessible(true); // It's final therefore unlocking the field unwrappedReturnTypeField.set(mockDynamoDBQueryMethod, clazz); } catch (Exception e) { - // There is little we can and want do if it fails - Aborting the whole test is fine + // There is little we can and want do if it fails - Aborting the whole test is + // fine throw new RuntimeException(e); } @@ -168,9 +172,9 @@ private void setupCommonMocksForThisRepositoryMetho Mockito.when(mockDynamoDBQueryMethod.getParameters()).thenReturn(mockParameters); Mockito.when(mockParameters.getBindableParameters()).thenReturn(mockParameters); Mockito.when(mockParameters.getNumberOfParameters()).thenReturn(numberOfParameters); -// Mockito.when(mockDynamoDBQueryMethod.getReturnedObjectType()).thenReturn(returnedObjectClass); + // Mockito.when(mockDynamoDBQueryMethod.getReturnedObjectType()).thenReturn(returnedObjectClass); if (hashKeyProperty != null) { -// Mockito.when(mockEntityMetadata.isHashKeyProperty(hashKeyProperty)).thenReturn(true); + // Mockito.when(mockEntityMetadata.isHashKeyProperty(hashKeyProperty)).thenReturn(true); } for (int i = 0; i < numberOfParameters; i++) { @@ -197,7 +201,7 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithSingleStringPa Mockito.when(mockDynamoDBOperations.load(User.class, "someId")).thenReturn(mockUser); // Execute the query - Object[] parameters = new Object[] { "someId" }; + Object[] parameters = new Object[]{"someId"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected single result @@ -213,11 +217,11 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntityWithCompositeId_Wit Playlist.class, "findByUserNameAndPlaylistName", 2, "userName", "playlistName"); // Mock out specific DynamoDBOperations behavior expected by this method - Mockito.when(mockDynamoDBOperations.load(Playlist.class, "someUserName", "somePlaylistName")).thenReturn( - mockPlaylist); + Mockito.when(mockDynamoDBOperations.load(Playlist.class, "someUserName", "somePlaylistName")) + .thenReturn(mockPlaylist); // Execute the query - Object[] parameters = new Object[] { "someUserName", "somePlaylistName" }; + Object[] parameters = new Object[]{"someUserName", "somePlaylistName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected single result @@ -239,12 +243,12 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntityWithCompositeId_Whe Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn("somePlaylistName"); // Mock out specific DynamoDBOperations behavior expected by this method - Mockito.when(mockDynamoDBOperations.load(Playlist.class, "someUserName", "somePlaylistName")).thenReturn( - mockPlaylist); + Mockito.when(mockDynamoDBOperations.load(Playlist.class, "someUserName", "somePlaylistName")) + .thenReturn(mockPlaylist); // Execute the query - Object[] parameters = new Object[] { playlistId }; + Object[] parameters = new Object[]{playlistId}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected single result @@ -254,8 +258,8 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntityWithCompositeId_Whe Mockito.verify(mockDynamoDBOperations).load(Playlist.class, "someUserName", "somePlaylistName"); } - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test(expected=UnsupportedOperationException.class) + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test(expected = UnsupportedOperationException.class) public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByNotCompositeId() { PlaylistId playlistId = new PlaylistId(); playlistId.setUserName("someUserName"); @@ -266,26 +270,27 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); -// Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); -// Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn("somePlaylistName"); + // Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); + // Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn("somePlaylistName"); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockPlaylistScanResults.get(0)).thenReturn(mockPlaylist); -// Mockito.when(mockPlaylistScanResults.size()).thenReturn(1); -// Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( -// mockPlaylistScanResults); + // Mockito.when(mockPlaylistScanResults.get(0)).thenReturn(mockPlaylist); + // Mockito.when(mockPlaylistScanResults.size()).thenReturn(1); + // Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), + // scanCaptor.capture())).thenReturn( + // mockPlaylistScanResults); // Execute the query - Object[] parameters = new Object[] { playlistId }; + Object[] parameters = new Object[]{playlistId}; partTreeDynamoDBQuery.execute(parameters); } @Test - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByRangeKeyOnly() { setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, @@ -298,12 +303,12 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistScanResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockPlaylistScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockPlaylistScanResults); // Execute the query - Object[] parameters = new Object[] { "somePlaylistName" }; + Object[] parameters = new Object[]{"somePlaylistName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -344,7 +349,7 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF } @Test - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByCompositeIdWithRangeKeyOnly() { PlaylistId playlistId = new PlaylistId(); playlistId.setPlaylistName("somePlaylistName"); @@ -361,12 +366,12 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistScanResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockPlaylistScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockPlaylistScanResults); // Execute the query - Object[] parameters = new Object[] { playlistId }; + Object[] parameters = new Object[]{playlistId}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -406,7 +411,7 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WithSingleStringParameter_WhenFindingByHashKeyOnly() { setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, @@ -414,19 +419,19 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WithS Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( - mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { "someUserName" }; + Object[] parameters = new Object[]{"someUserName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -448,7 +453,6 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WithS Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); } - @SuppressWarnings("unchecked") @Test public void testExecute_WhenFinderMethodIsCountingEntityWithCompositeIdList_WhenFindingByRangeKeyOnly_ScanCountEnabled() { @@ -463,12 +467,11 @@ public void testExecute_WhenFinderMethodIsCountingEntityWithCompositeIdList_When ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); @SuppressWarnings("rawtypes") ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockDynamoDBOperations.count(classCaptor.capture(), scanCaptor.capture())).thenReturn( - 100); + Mockito.when(mockDynamoDBOperations.count(classCaptor.capture(), scanCaptor.capture())).thenReturn(100); // Execute the query - Object[] parameters = new Object[] { "somePlaylistName" }; + Object[] parameters = new Object[]{"somePlaylistName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -507,7 +510,7 @@ public void testExecute_WhenFinderMethodIsCountingEntityWithCompositeIdList_When } @SuppressWarnings("unchecked") - @Test(expected=IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) public void testExecute_WhenFinderMethodIsCountingEntityWithCompositeIdList_WhenFindingByRangeKeyOnly_ScanCountDisabled() { setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, @@ -520,17 +523,18 @@ public void testExecute_WhenFinderMethodIsCountingEntityWithCompositeIdList_When ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); @SuppressWarnings("rawtypes") ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockDynamoDBOperations.count(classCaptor.capture(), scanCaptor.capture())).thenReturn( -// 100); + // Mockito.when(mockDynamoDBOperations.count(classCaptor.capture(), + // scanCaptor.capture())).thenReturn( + // 100); // Execute the query - Object[] parameters = new Object[] { "somePlaylistName" }; + Object[] parameters = new Object[]{"somePlaylistName"}; partTreeDynamoDBQuery.execute(parameters); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WithSingleStringParameter_WhenFindingByHashKeyAndNotRangeKey() { setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, @@ -539,20 +543,19 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WithS Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); -// Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( -// prototypeHashKey); - + // Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( + // prototypeHashKey); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistScanResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockPlaylistScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockPlaylistScanResults); // Execute the query - Object[] parameters = new Object[] { "someUserName", "somePlaylistName" }; + Object[] parameters = new Object[]{"someUserName", "somePlaylistName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -563,7 +566,6 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WithS // Assert that we scanned DynamoDB for the correct class assertEquals(classCaptor.getValue(), Playlist.class); - // Assert that we have the correct filter conditions Map filterConditions = scanCaptor.getValue().getScanFilter(); assertEquals(2, filterConditions.size()); @@ -599,16 +601,16 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WithS // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); // Assert - // that - // we - // obtain - // the - // expected - // results + // that + // we + // obtain + // the + // expected + // results } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByCompositeIdWithHashKeyOnly() { PlaylistId playlistId = new PlaylistId(); @@ -619,8 +621,8 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn(null); @@ -629,11 +631,11 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( - mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { playlistId }; + Object[] parameters = new Object[]{playlistId}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -651,15 +653,14 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Playlist hashKeyPropertyPlaylist = (Playlist) hashKeyPrototypeObject; assertEquals("someUserName", hashKeyPropertyPlaylist.getUserName()); - - assertEquals(0,queryCaptor.getValue().getRangeKeyConditions().size()); + assertEquals(0, queryCaptor.getValue().getRangeKeyConditions().size()); // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByCompositeId_HashKey() { PlaylistId playlistId = new PlaylistId(); @@ -670,21 +671,21 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); -// Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); -// Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn(null); + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); + // Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); + // Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn(null); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( - mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { "someUserName" }; + Object[] parameters = new Object[]{"someUserName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -702,15 +703,14 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Playlist hashKeyPropertyPlaylist = (Playlist) hashKeyPrototypeObject; assertEquals("someUserName", hashKeyPropertyPlaylist.getUserName()); - - assertEquals(0,queryCaptor.getValue().getRangeKeyConditions().size()); + assertEquals(0, queryCaptor.getValue().getRangeKeyConditions().size()); // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByCompositeId_HashKeyAndIndexRangeKey() { PlaylistId playlistId = new PlaylistId(); @@ -721,10 +721,10 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); -// Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); -// Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn(null); + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); + // Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); + // Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn(null); Set indexRangeKeyPropertyNames = new HashSet(); indexRangeKeyPropertyNames.add("displayName"); Mockito.when(mockPlaylistEntityMetadata.getIndexRangeKeyPropertyNames()).thenReturn(indexRangeKeyPropertyNames); @@ -734,11 +734,11 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( - mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { "someUserName","someDisplayName" }; + Object[] parameters = new Object[]{"someUserName", "someDisplayName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -756,23 +756,18 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Playlist hashKeyPropertyPlaylist = (Playlist) hashKeyPrototypeObject; assertEquals("someUserName", hashKeyPropertyPlaylist.getUserName()); - - - assertEquals(1,queryCaptor.getValue().getRangeKeyConditions().size()); + assertEquals(1, queryCaptor.getValue().getRangeKeyConditions().size()); Condition condition = (Condition) queryCaptor.getValue().getRangeKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.EQ.name(),condition.getComparisonOperator()); - assertEquals(1,condition.getAttributeValueList().size()); - assertEquals("someDisplayName",condition.getAttributeValueList().get(0).getS()); + assertEquals(ComparisonOperator.EQ.name(), condition.getComparisonOperator()); + assertEquals(1, condition.getAttributeValueList().size()); + assertEquals("someDisplayName", condition.getAttributeValueList().get(0).getS()); // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); } - - - @Test public void testExecute_WhenFinderMethodIsFindingSingleEntityWithCompositeId_WhenFindingByCompositeId_HashKeyAndCompositeId_RangeKey() { PlaylistId playlistId = new PlaylistId(); @@ -781,16 +776,16 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntityWithCompositeId_Whe setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, "findByPlaylistIdUserNameAndPlaylistIdPlaylistName", 2, "userName", "playlistName"); -// Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); -// Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn("somePlaylistName"); + // Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); + // Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn("somePlaylistName"); // Mock out specific DynamoDBOperations behavior expected by this method - Mockito.when(mockDynamoDBOperations.load(Playlist.class, "someUserName", "somePlaylistName")).thenReturn( - mockPlaylist); + Mockito.when(mockDynamoDBOperations.load(Playlist.class, "someUserName", "somePlaylistName")) + .thenReturn(mockPlaylist); // Execute the query - Object[] parameters = new Object[] { "someUserName","somePlaylistName" }; + Object[] parameters = new Object[]{"someUserName", "somePlaylistName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected single result @@ -800,7 +795,7 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntityWithCompositeId_Whe Mockito.verify(mockDynamoDBOperations).load(Playlist.class, "someUserName", "somePlaylistName"); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByCompositeIdWithHashKeyOnly_WhenSortingByRangeKey() { PlaylistId playlistId = new PlaylistId(); @@ -811,8 +806,8 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn(null); @@ -821,11 +816,11 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( - mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { playlistId }; + Object[] parameters = new Object[]{playlistId}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -843,17 +838,16 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Playlist hashKeyPropertyPlaylist = (Playlist) hashKeyPrototypeObject; assertEquals("someUserName", hashKeyPropertyPlaylist.getUserName()); - - assertEquals(0,queryCaptor.getValue().getRangeKeyConditions().size()); + assertEquals(0, queryCaptor.getValue().getRangeKeyConditions().size()); // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) // Can't sort by indexrangekey when querying by hash key only - @Test(expected=UnsupportedOperationException.class) + @Test(expected = UnsupportedOperationException.class) public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByCompositeIdWithHashKeyOnly_WhenSortingByIndexRangeKey() { PlaylistId playlistId = new PlaylistId(); playlistId.setUserName("someUserName"); @@ -863,8 +857,8 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn(null); Set indexRangeKeyPropertyNames = new HashSet(); @@ -874,23 +868,22 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); -// Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); -// Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( -// mockPlaylistQueryResults); + // Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + // Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + // Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), + // queryCaptor.capture())).thenReturn( + // mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { playlistId }; + Object[] parameters = new Object[]{playlistId}; partTreeDynamoDBQuery.execute(parameters); - } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByHashKeyAndIndexRangeKey() { - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, "findByUserNameAndDisplayName", 2, "userName", "playlistName"); Set indexRangeKeyPropertyNames = new HashSet(); @@ -899,20 +892,19 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); - + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( - mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { "someUserName","someDisplayName" }; + Object[] parameters = new Object[]{"someUserName", "someDisplayName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -923,28 +915,28 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF // Assert that we scanned DynamoDB for the correct class assertEquals(classCaptor.getValue(), Playlist.class); - // Assert that we have only one filter condition for the hash key,and for the index range key + // Assert that we have only one filter condition for the hash key,and for the + // index range key Object hashKeyPrototypeObject = queryCaptor.getValue().getHashKeyValues(); assertTrue(hashKeyPrototypeObject instanceof Playlist); Playlist hashKeyPropertyPlaylist = (Playlist) hashKeyPrototypeObject; assertEquals("someUserName", hashKeyPropertyPlaylist.getUserName()); - assertEquals(1,queryCaptor.getValue().getRangeKeyConditions().size()); + assertEquals(1, queryCaptor.getValue().getRangeKeyConditions().size()); Condition condition = (Condition) queryCaptor.getValue().getRangeKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.EQ.name(),condition.getComparisonOperator()); - assertEquals(1,condition.getAttributeValueList().size()); - assertEquals("someDisplayName",condition.getAttributeValueList().get(0).getS()); + assertEquals(ComparisonOperator.EQ.name(), condition.getComparisonOperator()); + assertEquals(1, condition.getAttributeValueList().size()); + assertEquals("someDisplayName", condition.getAttributeValueList().get(0).getS()); // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByHashKeyAndIndexRangeKey_WithValidOrderSpecified() { - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, "findByUserNameAndDisplayNameOrderByDisplayNameDesc", 2, "userName", "playlistName"); Set indexRangeKeyPropertyNames = new HashSet(); @@ -953,20 +945,19 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); - + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( - mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { "someUserName","someDisplayName" }; + Object[] parameters = new Object[]{"someUserName", "someDisplayName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -977,17 +968,18 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF // Assert that we scanned DynamoDB for the correct class assertEquals(classCaptor.getValue(), Playlist.class); - // Assert that we have only one filter condition for the hash key,and for the index range key + // Assert that we have only one filter condition for the hash key,and for the + // index range key Object hashKeyPrototypeObject = queryCaptor.getValue().getHashKeyValues(); assertTrue(hashKeyPrototypeObject instanceof Playlist); Playlist hashKeyPropertyPlaylist = (Playlist) hashKeyPrototypeObject; assertEquals("someUserName", hashKeyPropertyPlaylist.getUserName()); - assertEquals(1,queryCaptor.getValue().getRangeKeyConditions().size()); + assertEquals(1, queryCaptor.getValue().getRangeKeyConditions().size()); Condition condition = (Condition) queryCaptor.getValue().getRangeKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.EQ.name(),condition.getComparisonOperator()); - assertEquals(1,condition.getAttributeValueList().size()); - assertEquals("someDisplayName",condition.getAttributeValueList().get(0).getS()); + assertEquals(ComparisonOperator.EQ.name(), condition.getComparisonOperator()); + assertEquals(1, condition.getAttributeValueList().size()); + assertEquals("someDisplayName", condition.getAttributeValueList().get(0).getS()); Assert.assertFalse(queryCaptor.getValue().isScanIndexForward()); @@ -996,12 +988,11 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF } - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test(expected=UnsupportedOperationException.class) + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test(expected = UnsupportedOperationException.class) public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByHashKeyAndIndexRangeKey_WithInvalidOrderSpecified() { - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, "findByUserNameAndDisplayNameOrderByPlaylistNameDesc", 2, "userName", "playlistName"); Set indexRangeKeyPropertyNames = new HashSet(); @@ -1010,30 +1001,28 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); - + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); -// Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); -// Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( -// mockPlaylistQueryResults); + // Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + // Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + // Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), + // queryCaptor.capture())).thenReturn( + // mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { "someUserName","someDisplayName" }; + Object[] parameters = new Object[]{"someUserName", "someDisplayName"}; partTreeDynamoDBQuery.execute(parameters); - } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByHashKeyAndIndexRangeKey_OrderByIndexRangeKey() { - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, "findByUserNameAndDisplayNameOrderByDisplayNameDesc", 2, "userName", "playlistName"); Set indexRangeKeyPropertyNames = new HashSet(); @@ -1042,20 +1031,19 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); - + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( - mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { "someUserName","someDisplayName" }; + Object[] parameters = new Object[]{"someUserName", "someDisplayName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -1066,29 +1054,29 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF // Assert that we scanned DynamoDB for the correct class assertEquals(classCaptor.getValue(), Playlist.class); - // Assert that we have only one filter condition for the hash key,and for the index range key + // Assert that we have only one filter condition for the hash key,and for the + // index range key Object hashKeyPrototypeObject = queryCaptor.getValue().getHashKeyValues(); assertTrue(hashKeyPrototypeObject instanceof Playlist); Playlist hashKeyPropertyPlaylist = (Playlist) hashKeyPrototypeObject; assertEquals("someUserName", hashKeyPropertyPlaylist.getUserName()); - assertEquals(1,queryCaptor.getValue().getRangeKeyConditions().size()); + assertEquals(1, queryCaptor.getValue().getRangeKeyConditions().size()); Condition condition = (Condition) queryCaptor.getValue().getRangeKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.EQ.name(),condition.getComparisonOperator()); - assertEquals(1,condition.getAttributeValueList().size()); - assertEquals("someDisplayName",condition.getAttributeValueList().get(0).getS()); + assertEquals(ComparisonOperator.EQ.name(), condition.getComparisonOperator()); + assertEquals(1, condition.getAttributeValueList().size()); + assertEquals("someDisplayName", condition.getAttributeValueList().get(0).getS()); // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) // Sorting by range key when querying by indexrangekey not supported - @Test(expected=UnsupportedOperationException.class) + @Test(expected = UnsupportedOperationException.class) public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByHashKeyAndIndexRangeKey_OrderByRangeKey() { - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, "findByUserNameAndDisplayNameOrderByPlaylistNameDesc", 2, "userName", "playlistName"); Set indexRangeKeyPropertyNames = new HashSet(); @@ -1097,54 +1085,52 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); - + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); -// Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); -// Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( -// mockPlaylistQueryResults); + // Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + // Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + // Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), + // queryCaptor.capture())).thenReturn( + // mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { "someUserName","someDisplayName" }; + Object[] parameters = new Object[]{"someUserName", "someDisplayName"}; partTreeDynamoDBQuery.execute(parameters); - } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByHashKeyAndIndexRangeKeyWithOveriddenName() { - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, "findByUserNameAndDisplayName", 2, "userName", "playlistName"); Set indexRangeKeyPropertyNames = new HashSet(); indexRangeKeyPropertyNames.add("displayName"); Mockito.when(mockPlaylistEntityMetadata.getIndexRangeKeyPropertyNames()).thenReturn(indexRangeKeyPropertyNames); - Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("displayName")).thenReturn(Optional.of("DisplayName")); + Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("displayName")) + .thenReturn(Optional.of("DisplayName")); Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( - prototypeHashKey); - + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")) + .thenReturn(prototypeHashKey); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(DynamoDBQueryExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())).thenReturn( - mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); // Execute the query - Object[] parameters = new Object[] { "someUserName","someDisplayName" }; + Object[] parameters = new Object[]{"someUserName", "someDisplayName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected results @@ -1155,27 +1141,25 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF // Assert that we scanned DynamoDB for the correct class assertEquals(classCaptor.getValue(), Playlist.class); - // Assert that we have only one filter condition for the hash key,and for the index range key + // Assert that we have only one filter condition for the hash key,and for the + // index range key Object hashKeyPrototypeObject = queryCaptor.getValue().getHashKeyValues(); assertTrue(hashKeyPrototypeObject instanceof Playlist); Playlist hashKeyPropertyPlaylist = (Playlist) hashKeyPrototypeObject; assertEquals("someUserName", hashKeyPropertyPlaylist.getUserName()); - assertEquals(1,queryCaptor.getValue().getRangeKeyConditions().size()); + assertEquals(1, queryCaptor.getValue().getRangeKeyConditions().size()); Condition condition = (Condition) queryCaptor.getValue().getRangeKeyConditions().get("DisplayName"); - assertEquals(ComparisonOperator.EQ.name(),condition.getComparisonOperator()); - assertEquals(1,condition.getAttributeValueList().size()); - assertEquals("someDisplayName",condition.getAttributeValueList().get(0).getS()); + assertEquals(ComparisonOperator.EQ.name(), condition.getComparisonOperator()); + assertEquals(1, condition.getAttributeValueList().size()); + assertEquals("someDisplayName", condition.getAttributeValueList().get(0).getS()); // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); } - - - - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByCompositeIdWithHashKeyOnlyAndByAnotherPropertyWithOverriddenAttributeName() { PlaylistId playlistId = new PlaylistId(); @@ -1186,22 +1170,23 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); -// Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( -// prototypeHashKey); + // Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( + // prototypeHashKey); Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn(null); - Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("displayName")).thenReturn(Optional.of("DisplayName")); + Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("displayName")) + .thenReturn(Optional.of("DisplayName")); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); -// Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + // Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); + // Mockito.when(mockUserScanResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { playlistId, "someDisplayName" }; + Object[] parameters = new Object[]{playlistId, "someDisplayName"}; partTreeDynamoDBQuery.execute(parameters); // Assert that we scanned DynamoDB for the correct class @@ -1242,16 +1227,16 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); // Assert - // that - // we - // obtain - // the - // expected - // results + // that + // we + // obtain + // the + // expected + // results } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByCompositeIdWithRangeKeyOnlyAndByAnotherPropertyWithOverriddenAttributeName() { PlaylistId playlistId = new PlaylistId(); @@ -1264,18 +1249,19 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF prototypeHashKey.setUserName("someUserName"); Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn(null); Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn("somePlaylistName"); - Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("displayName")).thenReturn(Optional.of("DisplayName")); + Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("displayName")) + .thenReturn(Optional.of("DisplayName")); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); -// Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + // Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); + // Mockito.when(mockUserScanResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { playlistId, "someDisplayName" }; + Object[] parameters = new Object[]{playlistId, "someDisplayName"}; partTreeDynamoDBQuery.execute(parameters); // Assert that we scanned DynamoDB for the correct class @@ -1316,16 +1302,16 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); // Assert - // that - // we - // obtain - // the - // expected - // results + // that + // we + // obtain + // the + // expected + // results } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByNotHashKeyAndNotRangeKey() { @@ -1336,13 +1322,13 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); -// Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + // Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); + // Mockito.when(mockUserScanResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { "someUserName", "somePlaylistName" }; + Object[] parameters = new Object[]{"someUserName", "somePlaylistName"}; partTreeDynamoDBQuery.execute(parameters); // Assert that we scanned DynamoDB for the correct class @@ -1383,16 +1369,16 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); // Assert - // that - // we - // obtain - // the - // expected - // results + // that + // we + // obtain + // the + // expected + // results } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenFindingByCompositeIdAndByAnotherPropertyWithOverriddenAttributeName() { PlaylistId playlistId = new PlaylistId(); @@ -1405,22 +1391,23 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF Playlist prototypeHashKey = new Playlist(); prototypeHashKey.setUserName("someUserName"); -// Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( -// prototypeHashKey); + // Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someUserName")).thenReturn( + // prototypeHashKey); Mockito.when(mockPlaylistEntityMetadata.getHashKey(playlistId)).thenReturn("someUserName"); Mockito.when(mockPlaylistEntityMetadata.getRangeKey(playlistId)).thenReturn("somePlaylistName"); - Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("displayName")).thenReturn(Optional.of("DisplayName")); + Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("displayName")) + .thenReturn(Optional.of("DisplayName")); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); -// Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + // Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); + // Mockito.when(mockUserScanResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { playlistId, "someDisplayName" }; + Object[] parameters = new Object[]{playlistId, "someDisplayName"}; partTreeDynamoDBQuery.execute(parameters); // Assert that we scanned DynamoDB for the correct class @@ -1471,16 +1458,16 @@ public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeIdList_WhenF // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); // Assert - // that - // we - // obtain - // the - // expected - // results + // that + // we + // obtain + // the + // expected + // results } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithSingleStringParameter_WhenNotFindingByHashKey() { setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, @@ -1491,11 +1478,11 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithSingleStringPa ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { "someName" }; + Object[] parameters = new Object[]{"someName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected single result @@ -1533,7 +1520,7 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithSingleStringPa Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithSingleStringParameter_WhenNotFindingByHashKey_WhenDynamoAttributeNameOverridden() { setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, @@ -1545,11 +1532,11 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithSingleStringPa ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { "someName" }; + Object[] parameters = new Object[]{"someName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected single result @@ -1587,7 +1574,7 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithSingleStringPa Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithMultipleStringParameters_WhenFindingByHashKeyAndANonHashOrRangeProperty() { setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, @@ -1598,11 +1585,11 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithMultipleString ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { "someId", "someName" }; + Object[] parameters = new Object[]{"someId", "someName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected single result @@ -1649,8 +1636,7 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithMultipleString Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithMultipleStringParameters_WhenFindingByHashKeyAndACollectionProperty() { setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, @@ -1664,11 +1650,11 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithMultipleString ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { testSet }; + Object[] parameters = new Object[]{testSet}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected single result @@ -1683,7 +1669,6 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithMultipleString Condition testSetFilterCondition = filterConditions.get("testSet"); assertNotNull(testSetFilterCondition); - assertEquals(ComparisonOperator.EQ.name(), testSetFilterCondition.getComparisonOperator()); // Assert we only have one attribute value for each filter condition @@ -1694,18 +1679,16 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithMultipleString // and its value is the parameter expected assertNotNull(testSetFilterCondition.getAttributeValueList().get(0).getSS()); - - assertTrue(ClassUtils.isAssignable(Iterable.class, testSetFilterCondition.getAttributeValueList().get(0).getSS().getClass())); + assertTrue(ClassUtils.isAssignable(Iterable.class, + testSetFilterCondition.getAttributeValueList().get(0).getSS().getClass())); Iterable iterable = testSetFilterCondition.getAttributeValueList().get(0).getSS(); List returnObjects = new ArrayList(); - for (Object object : iterable) - { + for (Object object : iterable) { returnObjects.add(object); } - assertEquals(1,returnObjects.size()); - assertEquals("testData",returnObjects.get(0)); - + assertEquals(1, returnObjects.size()); + assertEquals("testData", returnObjects.get(0)); // Assert that all other attribute value types other than String type // are null @@ -1715,14 +1698,11 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithMultipleString assertNull(testSetFilterCondition.getAttributeValueList().get(0).getB()); assertNull(testSetFilterCondition.getAttributeValueList().get(0).getBS()); - // Verify that the expected DynamoDBOperations method was called Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - - - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithMultipleStringParameters_WhenFindingByHashKeyAndANonHashOrRangeProperty_WhenDynamoDBAttributeNamesOveridden() { setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, @@ -1736,11 +1716,11 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithMultipleString ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { "someId", "someName" }; + Object[] parameters = new Object[]{"someId", "someName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected single result @@ -1787,7 +1767,7 @@ public void testExecute_WhenFinderMethodIsFindingSingleEntity_WithMultipleString Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringParameter_WhenNotFindingByHashKey() { setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, @@ -1799,11 +1779,11 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringPara ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { "someName" }; + Object[] parameters = new Object[]{"someName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected list of results @@ -1845,7 +1825,7 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringPara Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test(expected = UnsupportedOperationException.class) // Not yet supported public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringParameterIgnoringCase_WhenNotFindingByHashKey() { @@ -1856,18 +1836,19 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringPara // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); -// Mockito.when(mockUserScanResults.size()).thenReturn(1); -// Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( -// mockUserScanResults); + // Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); + // Mockito.when(mockUserScanResults.size()).thenReturn(1); + // Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), + // scanCaptor.capture())).thenReturn( + // mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { "someName" }; + Object[] parameters = new Object[]{"someName"}; partTreeDynamoDBQuery.execute(parameters); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test(expected = UnsupportedOperationException.class) // Not yet supported public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringParameter_WithSort_WhenNotFindingByHashKey() { @@ -1878,35 +1859,37 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringPara // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); -// Mockito.when(mockUserScanResults.size()).thenReturn(1); -// Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( -// mockUserScanResults); + // Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); + // Mockito.when(mockUserScanResults.size()).thenReturn(1); + // Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), + // scanCaptor.capture())).thenReturn( + // mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { "someName" }; + Object[] parameters = new Object[]{"someName"}; partTreeDynamoDBQuery.execute(parameters); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringArrayParameter_WithIn_WhenNotFindingByHashKey() { - setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, "findByNameIn", - 1, "id", null); + setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, + "findByNameIn", 1, "id", null); Mockito.when(mockDynamoDBUserQueryMethod.isCollectionQuery()).thenReturn(true); - String[] names = new String[] { "someName", "someOtherName" }; + String[] names = new String[]{"someName", "someOtherName"}; // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn(mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { names }; + Object[] parameters = new Object[]{names}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected list of results @@ -1950,24 +1933,25 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringArra } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleListParameter_WithIn_WhenNotFindingByHashKey() { - setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, "findByNameIn", - 1, "id", null); + setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, + "findByNameIn", 1, "id", null); Mockito.when(mockDynamoDBUserQueryMethod.isCollectionQuery()).thenReturn(true); - List names = Arrays.asList(new String[] { "someName", "someOtherName" }); + List names = Arrays.asList(new String[]{"someName", "someOtherName"}); // Mock out specific DynamoDBOperations behavior expected by this method ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn(mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { names }; + Object[] parameters = new Object[]{names}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected list of results @@ -2011,7 +1995,7 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleListParame } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleDateParameter_WhenNotFindingByHashKey() throws ParseException { @@ -2029,11 +2013,11 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleDateParame ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { joinDate }; + Object[] parameters = new Object[]{joinDate}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected list of results @@ -2075,7 +2059,7 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleDateParame Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleDateParameter_WithCustomMarshaller_WhenNotFindingByHashKey() throws ParseException { @@ -2095,11 +2079,11 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleDateParame ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { joinYear }; + Object[] parameters = new Object[]{joinYear}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected list of results @@ -2142,7 +2126,7 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleDateParame } // Global Secondary Index Test 1 - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleDateParameter_WithCustomMarshaller_WhenFindingByGlobalSecondaryHashIndexHashKey() throws ParseException { @@ -2158,9 +2142,10 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleDateParame Mockito.when(mockUserEntityMetadata.getMarshallerForProperty("joinYear")).thenReturn(marshaller); - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("joinYear", new String[] {"JoinYear-index"}); - Mockito.when(mockUserEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("joinYear", new String[]{"JoinYear-index"}); + Mockito.when(mockUserEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); Mockito.when(mockUserEntityMetadata.getDynamoDBTableName()).thenReturn("user"); @@ -2170,15 +2155,13 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleDateParame Mockito.when(mockUserQueryResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserQueryResults.size()).thenReturn(1); Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockUserQueryResults); + .thenReturn(mockUserQueryResults); Mockito.when(mockDynamoDBOperations.getOverriddenTableName(User.class, "user")).thenReturn("user"); - // Execute the query - Object[] parameters = new Object[] { joinYear}; + Object[] parameters = new Object[]{joinYear}; Object o = partTreeDynamoDBQuery.execute(parameters); - // Assert that we obtain the expected results assertEquals(mockUserQueryResults, o); assertEquals(1, mockUserQueryResults.size()); @@ -2187,19 +2170,19 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleDateParame // Assert that we scanned DynamoDB for the correct class assertEquals(classCaptor.getValue(), User.class); - String indexName = queryCaptor.getValue().getIndexName(); + String indexName = queryCaptor.getValue().getIndexName(); assertNotNull(indexName); - assertEquals("JoinYear-index",indexName); + assertEquals("JoinYear-index", indexName); - assertEquals("user",queryCaptor.getValue().getTableName()); + assertEquals("user", queryCaptor.getValue().getTableName()); - - // Assert that we have only one range condition for the global secondary index hash key - assertEquals(1,queryCaptor.getValue().getKeyConditions().size()); + // Assert that we have only one range condition for the global secondary index + // hash key + assertEquals(1, queryCaptor.getValue().getKeyConditions().size()); Condition condition = queryCaptor.getValue().getKeyConditions().get("joinYear"); - assertEquals(ComparisonOperator.EQ.name(),condition.getComparisonOperator()); - assertEquals(1,condition.getAttributeValueList().size()); - assertEquals(joinYearString,condition.getAttributeValueList().get(0).getS()); + assertEquals(ComparisonOperator.EQ.name(), condition.getComparisonOperator()); + assertEquals(1, condition.getAttributeValueList().size()); + assertEquals(joinYearString, condition.getAttributeValueList().get(0).getS()); // Assert that all other attribute value types other than String type // are null @@ -2213,1221 +2196,1139 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleDateParame Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); } + // Global Secondary Index Test 2 + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityList_WithDateParameterAndStringParameter_WithCustomMarshaller_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKey() + throws ParseException { + String joinYearString = "2013"; + DateFormat dateFormat = new SimpleDateFormat("yyyy"); + Date joinYear = dateFormat.parse(joinYearString); + setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, + "findByJoinYearAndPostCode", 2, "id", null); + Mockito.when(mockDynamoDBUserQueryMethod.isCollectionQuery()).thenReturn(true); + DynamoDBMarshaller marshaller = new DynamoDBYearMarshaller(); - // Global Secondary Index Test 2 - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityList_WithDateParameterAndStringParameter_WithCustomMarshaller_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKey() - throws ParseException { - String joinYearString = "2013"; - DateFormat dateFormat = new SimpleDateFormat("yyyy"); - Date joinYear = dateFormat.parse(joinYearString); - - setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, - "findByJoinYearAndPostCode", 2, "id", null); - Mockito.when(mockDynamoDBUserQueryMethod.isCollectionQuery()).thenReturn(true); - DynamoDBMarshaller marshaller = new DynamoDBYearMarshaller(); + Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("joinYear")).thenReturn(true); + Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("postCode")).thenReturn(true); - Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("joinYear")).thenReturn(true); - Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("postCode")).thenReturn(true); + Mockito.when(mockUserEntityMetadata.getMarshallerForProperty("joinYear")).thenReturn(marshaller); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("joinYear", new String[]{"JoinYear-index"}); + indexRangeKeySecondaryIndexNames.put("postCode", new String[]{"JoinYear-index"}); - Mockito.when(mockUserEntityMetadata.getMarshallerForProperty("joinYear")).thenReturn(marshaller); + Mockito.when(mockUserEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("joinYear", new String[] {"JoinYear-index"}); - indexRangeKeySecondaryIndexNames.put("postCode", new String[] {"JoinYear-index"}); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockUserQueryResults.get(0)).thenReturn(mockUser); + Mockito.when(mockUserQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockUserQueryResults); + Mockito.when(mockUserEntityMetadata.getDynamoDBTableName()).thenReturn("user"); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(User.class, "user")).thenReturn("user"); - Mockito.when(mockUserEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); + // Execute the query + Object[] parameters = new Object[]{joinYear, "nw1"}; + Object o = partTreeDynamoDBQuery.execute(parameters); - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockUserQueryResults.get(0)).thenReturn(mockUser); - Mockito.when(mockUserQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockUserQueryResults); - Mockito.when(mockUserEntityMetadata.getDynamoDBTableName()).thenReturn("user"); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(User.class, "user")).thenReturn("user"); + // Assert that we obtain the expected results + assertEquals(mockUserQueryResults, o); + assertEquals(1, mockUserQueryResults.size()); + assertEquals(mockUser, mockUserQueryResults.get(0)); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), User.class); - // Execute the query - Object[] parameters = new Object[] { joinYear,"nw1"}; - Object o = partTreeDynamoDBQuery.execute(parameters); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("JoinYear-index", indexName); + + // Assert that we have only two range conditions for the global secondary index + // hash key and range key + assertEquals(2, queryCaptor.getValue().getKeyConditions().size()); + Condition yearCondition = queryCaptor.getValue().getKeyConditions().get("joinYear"); + assertEquals(ComparisonOperator.EQ.name(), yearCondition.getComparisonOperator()); + assertEquals(1, yearCondition.getAttributeValueList().size()); + assertEquals(joinYearString, yearCondition.getAttributeValueList().get(0).getS()); + Condition postCodeCondition = queryCaptor.getValue().getKeyConditions().get("postCode"); + assertEquals(ComparisonOperator.EQ.name(), postCodeCondition.getComparisonOperator()); + assertEquals(1, postCodeCondition.getAttributeValueList().size()); + assertEquals("nw1", postCodeCondition.getAttributeValueList().get(0).getS()); + + assertEquals("user", queryCaptor.getValue().getTableName()); + // Assert that all other attribute value types other than String type + // are null + assertNull(yearCondition.getAttributeValueList().get(0).getSS()); + assertNull(yearCondition.getAttributeValueList().get(0).getN()); + assertNull(yearCondition.getAttributeValueList().get(0).getNS()); + assertNull(yearCondition.getAttributeValueList().get(0).getB()); + assertNull(yearCondition.getAttributeValueList().get(0).getBS()); + assertNull(postCodeCondition.getAttributeValueList().get(0).getSS()); + assertNull(postCodeCondition.getAttributeValueList().get(0).getN()); + assertNull(postCodeCondition.getAttributeValueList().get(0).getNS()); + assertNull(postCodeCondition.getAttributeValueList().get(0).getB()); + assertNull(postCodeCondition.getAttributeValueList().get(0).getBS()); - // Assert that we obtain the expected results - assertEquals(mockUserQueryResults, o); - assertEquals(1, mockUserQueryResults.size()); - assertEquals(mockUser, mockUserQueryResults.get(0)); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), User.class); + // Global Secondary Index Test 3 + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashIndexHashKey() + throws ParseException { - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("JoinYear-index",indexName); + setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, + Playlist.class, "findByDisplayNameOrderByDisplayNameDesc", 1, "userName", "playlistName"); + Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - // Assert that we have only two range conditions for the global secondary index hash key and range key - assertEquals(2,queryCaptor.getValue().getKeyConditions().size()); - Condition yearCondition = queryCaptor.getValue().getKeyConditions().get("joinYear"); - assertEquals(ComparisonOperator.EQ.name(),yearCondition.getComparisonOperator()); - assertEquals(1,yearCondition.getAttributeValueList().size()); - assertEquals(joinYearString,yearCondition.getAttributeValueList().get(0).getS()); - Condition postCodeCondition = queryCaptor.getValue().getKeyConditions().get("postCode"); - assertEquals(ComparisonOperator.EQ.name(),postCodeCondition.getComparisonOperator()); - assertEquals(1,postCodeCondition.getAttributeValueList().size()); - assertEquals("nw1",postCodeCondition.getAttributeValueList().get(0).getS()); + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("displayName", new String[]{"DisplayName-index"}); + Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); + Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - assertEquals("user",queryCaptor.getValue().getTableName()); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - // Assert that all other attribute value types other than String type - // are null - assertNull(yearCondition.getAttributeValueList().get(0).getSS()); - assertNull(yearCondition.getAttributeValueList().get(0).getN()); - assertNull(yearCondition.getAttributeValueList().get(0).getNS()); - assertNull(yearCondition.getAttributeValueList().get(0).getB()); - assertNull(yearCondition.getAttributeValueList().get(0).getBS()); - assertNull(postCodeCondition.getAttributeValueList().get(0).getSS()); - assertNull(postCodeCondition.getAttributeValueList().get(0).getN()); - assertNull(postCodeCondition.getAttributeValueList().get(0).getNS()); - assertNull(postCodeCondition.getAttributeValueList().get(0).getB()); - assertNull(postCodeCondition.getAttributeValueList().get(0).getBS()); + // Execute the query + Object[] parameters = new Object[]{"Michael"}; + Object o = partTreeDynamoDBQuery.execute(parameters); - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(),queryCaptor.getValue()); - } + // Assert that we obtain the expected results + assertEquals(mockPlaylistQueryResults, o); + assertEquals(1, mockPlaylistQueryResults.size()); + assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), Playlist.class); - // Global Secondary Index Test 3 - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashIndexHashKey() - throws ParseException { + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("DisplayName-index", indexName); + assertEquals("playlist", queryCaptor.getValue().getTableName()); - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, - "findByDisplayNameOrderByDisplayNameDesc", 1, "userName", "playlistName"); - Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); + // Assert that we have only one range condition for the global secondary index + // hash key + assertEquals(1, queryCaptor.getValue().getKeyConditions().size()); + Condition condition = queryCaptor.getValue().getKeyConditions().get("displayName"); + assertEquals(ComparisonOperator.EQ.name(), condition.getComparisonOperator()); + assertEquals(1, condition.getAttributeValueList().size()); + assertEquals("Michael", condition.getAttributeValueList().get(0).getS()); + // Assert that all other attribute value types other than String type + // are null + assertNull(condition.getAttributeValueList().get(0).getSS()); + assertNull(condition.getAttributeValueList().get(0).getN()); + assertNull(condition.getAttributeValueList().get(0).getNS()); + assertNull(condition.getAttributeValueList().get(0).getB()); + assertNull(condition.getAttributeValueList().get(0).getBS()); - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("displayName", new String[] {"DisplayName-index"}); - Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); + // Global Secondary Index Test 3a + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashIndexHashKey_WhereSecondaryHashKeyIsPrimaryRangeKey() + throws ParseException { - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); - Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockPlaylistQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); + setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, + Playlist.class, "findByPlaylistName", 1, "userName", "playlistName"); + Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("playlistName", new String[]{"PlaylistName-index"}); + Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); - // Execute the query - Object[] parameters = new Object[] { "Michael"}; - Object o = partTreeDynamoDBQuery.execute(parameters); + Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - // Assert that we obtain the expected results - assertEquals(mockPlaylistQueryResults, o); - assertEquals(1, mockPlaylistQueryResults.size()); - assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); + // Execute the query + Object[] parameters = new Object[]{"Some Playlist"}; + Object o = partTreeDynamoDBQuery.execute(parameters); - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), Playlist.class); + // Assert that we obtain the expected results + assertEquals(mockPlaylistQueryResults, o); + assertEquals(1, mockPlaylistQueryResults.size()); + assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("DisplayName-index",indexName); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), Playlist.class); - assertEquals("playlist",queryCaptor.getValue().getTableName()); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("PlaylistName-index", indexName); + assertEquals("playlist", queryCaptor.getValue().getTableName()); - // Assert that we have only one range condition for the global secondary index hash key - assertEquals(1,queryCaptor.getValue().getKeyConditions().size()); - Condition condition = queryCaptor.getValue().getKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.EQ.name(),condition.getComparisonOperator()); - assertEquals(1,condition.getAttributeValueList().size()); - assertEquals("Michael",condition.getAttributeValueList().get(0).getS()); + // Assert that we have the correct conditions + assertEquals(1, queryCaptor.getValue().getKeyConditions().size()); + Condition condition = queryCaptor.getValue().getKeyConditions().get("playlistName"); + assertEquals(ComparisonOperator.EQ.name(), condition.getComparisonOperator()); + assertEquals(1, condition.getAttributeValueList().size()); + assertEquals("Some Playlist", condition.getAttributeValueList().get(0).getS()); + // Assert that all other attribute value types other than String type + // are null + assertNull(condition.getAttributeValueList().get(0).getSS()); + assertNull(condition.getAttributeValueList().get(0).getN()); + assertNull(condition.getAttributeValueList().get(0).getNS()); + assertNull(condition.getAttributeValueList().get(0).getB()); + assertNull(condition.getAttributeValueList().get(0).getBS()); - // Assert that all other attribute value types other than String type - // are null - assertNull(condition.getAttributeValueList().get(0).getSS()); - assertNull(condition.getAttributeValueList().get(0).getN()); - assertNull(condition.getAttributeValueList().get(0).getNS()); - assertNull(condition.getAttributeValueList().get(0).getB()); - assertNull(condition.getAttributeValueList().get(0).getBS()); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } + // Global Secondary Index Test 4 + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKey_WhereSecondaryHashKeyIsPrimaryHashKey() + throws ParseException { + setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, + Playlist.class, "findByUserNameAndDisplayName", 2, "userName", "playlistName"); + Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - // Global Secondary Index Test 3a - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashIndexHashKey_WhereSecondaryHashKeyIsPrimaryRangeKey() - throws ParseException { + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("userName")).thenReturn(true); + // Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("displayName", new String[]{"UserName-DisplayName-index"}); + indexRangeKeySecondaryIndexNames.put("userName", new String[]{"UserName-DisplayName-index"}); - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, - "findByPlaylistName", 1, "userName", "playlistName"); - Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); + Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); + Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("playlistName", new String[] {"PlaylistName-index"}); - Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); + // Execute the query + Object[] parameters = new Object[]{"1", "Michael"}; + Object o = partTreeDynamoDBQuery.execute(parameters); - Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); + // Assert that we obtain the expected results + assertEquals(mockPlaylistQueryResults, o); + assertEquals(1, mockPlaylistQueryResults.size()); + assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); - Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockPlaylistQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), Playlist.class); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("UserName-DisplayName-index", indexName); - // Execute the query - Object[] parameters = new Object[] { "Some Playlist"}; - Object o = partTreeDynamoDBQuery.execute(parameters); + assertEquals("playlist", queryCaptor.getValue().getTableName()); + // Assert that we the correct conditions + assertEquals(2, queryCaptor.getValue().getKeyConditions().size()); + Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); + assertEquals(ComparisonOperator.EQ.name(), globalRangeKeyCondition.getComparisonOperator()); + assertEquals(1, globalRangeKeyCondition.getAttributeValueList().size()); + assertEquals("Michael", globalRangeKeyCondition.getAttributeValueList().get(0).getS()); + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("userName"); + assertEquals(ComparisonOperator.EQ.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("1", globalHashKeyCondition.getAttributeValueList().get(0).getS()); - // Assert that we obtain the expected results - assertEquals(mockPlaylistQueryResults, o); - assertEquals(1, mockPlaylistQueryResults.size()); - assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); + // Assert that all other attribute value types other than String type + // are null + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), Playlist.class); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("PlaylistName-index",indexName); + // Global Secondary Index Test 4b + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKey_WhereSecondaryHashKeyIsPrimaryRangeKey() + throws ParseException { - assertEquals("playlist",queryCaptor.getValue().getTableName()); + setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, + Playlist.class, "findByPlaylistNameAndDisplayName", 2, "userName", "playlistName"); + Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("playlistName")).thenReturn(true); + // Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("playlistName", new String[]{"PlaylistName-DisplayName-index"}); + indexRangeKeySecondaryIndexNames.put("displayName", new String[]{"PlaylistName-DisplayName-index"}); - // Assert that we have the correct conditions - assertEquals(1,queryCaptor.getValue().getKeyConditions().size()); - Condition condition = queryCaptor.getValue().getKeyConditions().get("playlistName"); - assertEquals(ComparisonOperator.EQ.name(),condition.getComparisonOperator()); - assertEquals(1,condition.getAttributeValueList().size()); - assertEquals("Some Playlist",condition.getAttributeValueList().get(0).getS()); + Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); + Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - // Assert that all other attribute value types other than String type - // are null - assertNull(condition.getAttributeValueList().get(0).getSS()); - assertNull(condition.getAttributeValueList().get(0).getN()); - assertNull(condition.getAttributeValueList().get(0).getNS()); - assertNull(condition.getAttributeValueList().get(0).getB()); - assertNull(condition.getAttributeValueList().get(0).getBS()); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } + // Execute the query + Object[] parameters = new Object[]{"SomePlaylistName", "Michael"}; + Object o = partTreeDynamoDBQuery.execute(parameters); + // Assert that we obtain the expected results + assertEquals(mockPlaylistQueryResults, o); + assertEquals(1, mockPlaylistQueryResults.size()); + assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), Playlist.class); - // Global Secondary Index Test 4 - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKey_WhereSecondaryHashKeyIsPrimaryHashKey() - throws ParseException { + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("PlaylistName-DisplayName-index", indexName); + assertEquals("playlist", queryCaptor.getValue().getTableName()); - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, - "findByUserNameAndDisplayName", 2, "userName", "playlistName"); - Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); + // Assert that we have the correct conditions + assertEquals(2, queryCaptor.getValue().getKeyConditions().size()); + Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); + assertEquals(ComparisonOperator.EQ.name(), globalRangeKeyCondition.getComparisonOperator()); + assertEquals(1, globalRangeKeyCondition.getAttributeValueList().size()); + assertEquals("Michael", globalRangeKeyCondition.getAttributeValueList().get(0).getS()); + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("playlistName"); + assertEquals(ComparisonOperator.EQ.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("SomePlaylistName", globalHashKeyCondition.getAttributeValueList().get(0).getS()); + // Assert that all other attribute value types other than String type + // are null + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("userName")).thenReturn(true); -// Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("displayName", new String[] {"UserName-DisplayName-index"}); - indexRangeKeySecondaryIndexNames.put("userName", new String[] {"UserName-DisplayName-index"}); + // Global Secondary Index Test 4c + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKey_WhereSecondaryRangeKeyIsPrimaryRangeKey() + throws ParseException { - Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); + setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, + Playlist.class, "findByDisplayNameAndPlaylistName", 2, "userName", "playlistName"); + Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); + // Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("playlistName")).thenReturn(true); - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); - Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockPlaylistQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("displayName", new String[]{"DisplayName-PlaylistName-index"}); + indexRangeKeySecondaryIndexNames.put("playlistName", new String[]{"DisplayName-PlaylistName-index"}); + Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); - // Execute the query - Object[] parameters = new Object[] { "1","Michael"}; - Object o = partTreeDynamoDBQuery.execute(parameters); + Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - // Assert that we obtain the expected results - assertEquals(mockPlaylistQueryResults, o); - assertEquals(1, mockPlaylistQueryResults.size()); - assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); + // Execute the query + Object[] parameters = new Object[]{"SomeDisplayName", "SomePlaylistName"}; + Object o = partTreeDynamoDBQuery.execute(parameters); - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), Playlist.class); + // Assert that we obtain the expected results + assertEquals(mockPlaylistQueryResults, o); + assertEquals(1, mockPlaylistQueryResults.size()); + assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("UserName-DisplayName-index",indexName); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), Playlist.class); - assertEquals("playlist",queryCaptor.getValue().getTableName()); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("DisplayName-PlaylistName-index", indexName); + assertEquals("playlist", queryCaptor.getValue().getTableName()); - // Assert that we the correct conditions - assertEquals(2,queryCaptor.getValue().getKeyConditions().size()); - Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.EQ.name(),globalRangeKeyCondition.getComparisonOperator()); - assertEquals(1,globalRangeKeyCondition.getAttributeValueList().size()); - assertEquals("Michael",globalRangeKeyCondition.getAttributeValueList().get(0).getS()); - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("userName"); - assertEquals(ComparisonOperator.EQ.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("1",globalHashKeyCondition.getAttributeValueList().get(0).getS()); + // Assert that we have the correct conditions - // Assert that all other attribute value types other than String type - // are null - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + assertEquals(2, queryCaptor.getValue().getKeyConditions().size()); + Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); + assertEquals(ComparisonOperator.EQ.name(), globalRangeKeyCondition.getComparisonOperator()); + assertEquals(1, globalRangeKeyCondition.getAttributeValueList().size()); + assertEquals("SomeDisplayName", globalRangeKeyCondition.getAttributeValueList().get(0).getS()); + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("playlistName"); + assertEquals(ComparisonOperator.EQ.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("SomePlaylistName", globalHashKeyCondition.getAttributeValueList().get(0).getS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); + // Assert that all other attribute value types other than String type + // are null + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - // Global Secondary Index Test 4b - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKey_WhereSecondaryHashKeyIsPrimaryRangeKey() - throws ParseException { + // Global Secondary Index Test 4d + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKey_WhereSecondaryRangeKeyIsPrimaryHashKey() + throws ParseException { + setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, + Playlist.class, "findByDisplayNameAndUserName", 2, "userName", "playlistName"); + Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, - "findByPlaylistNameAndDisplayName", 2, "userName", "playlistName"); - Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); + // Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("userName")).thenReturn(true); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("displayName", new String[]{"DisplayName-UserName-index"}); + indexRangeKeySecondaryIndexNames.put("userName", new String[]{"DisplayName-UserName-index"}); - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("playlistName")).thenReturn(true); -// Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("playlistName", new String[] {"PlaylistName-DisplayName-index"}); - indexRangeKeySecondaryIndexNames.put("displayName", new String[] {"PlaylistName-DisplayName-index"}); + Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); - Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); + Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); - Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockPlaylistQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); + // Execute the query + Object[] parameters = new Object[]{"SomeDisplayName", "SomeUserName"}; + Object o = partTreeDynamoDBQuery.execute(parameters); + // Assert that we obtain the expected results + assertEquals(mockPlaylistQueryResults, o); + assertEquals(1, mockPlaylistQueryResults.size()); + assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - // Execute the query - Object[] parameters = new Object[] { "SomePlaylistName","Michael"}; - Object o = partTreeDynamoDBQuery.execute(parameters); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), Playlist.class); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("DisplayName-UserName-index", indexName); - // Assert that we obtain the expected results - assertEquals(mockPlaylistQueryResults, o); - assertEquals(1, mockPlaylistQueryResults.size()); - assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); + assertEquals("playlist", queryCaptor.getValue().getTableName()); - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), Playlist.class); + // Assert that we have the correct conditions - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("PlaylistName-DisplayName-index",indexName); + assertEquals(2, queryCaptor.getValue().getKeyConditions().size()); + Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); + assertEquals(ComparisonOperator.EQ.name(), globalRangeKeyCondition.getComparisonOperator()); + assertEquals(1, globalRangeKeyCondition.getAttributeValueList().size()); + assertEquals("SomeDisplayName", globalRangeKeyCondition.getAttributeValueList().get(0).getS()); + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("userName"); + assertEquals(ComparisonOperator.EQ.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("SomeUserName", globalHashKeyCondition.getAttributeValueList().get(0).getS()); - assertEquals("playlist",queryCaptor.getValue().getTableName()); + // Assert that all other attribute value types other than String type + // are null + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - // Assert that we have the correct conditions - assertEquals(2,queryCaptor.getValue().getKeyConditions().size()); - Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.EQ.name(),globalRangeKeyCondition.getComparisonOperator()); - assertEquals(1,globalRangeKeyCondition.getAttributeValueList().size()); - assertEquals("Michael",globalRangeKeyCondition.getAttributeValueList().get(0).getS()); - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("playlistName"); - assertEquals(ComparisonOperator.EQ.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("SomePlaylistName",globalHashKeyCondition.getAttributeValueList().get(0).getS()); + // Global Secondary Index Test 4e + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereSecondaryHashKeyIsPrimaryHashKey() + throws ParseException { - // Assert that all other attribute value types other than String type - // are null - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, + Playlist.class, "findByUserNameAndDisplayNameAfter", 2, "userName", "playlistName"); + Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("userName")).thenReturn(true); + // Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("displayName", new String[]{"UserName-DisplayName-index"}); + indexRangeKeySecondaryIndexNames.put("userName", new String[]{"UserName-DisplayName-index"}); + Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); + Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - // Global Secondary Index Test 4c - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKey_WhereSecondaryRangeKeyIsPrimaryRangeKey() - throws ParseException { - - - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, - "findByDisplayNameAndPlaylistName", 2, "userName", "playlistName"); - Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - - - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); -// Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("playlistName")).thenReturn(true); - - - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("displayName", new String[] {"DisplayName-PlaylistName-index"}); - indexRangeKeySecondaryIndexNames.put("playlistName", new String[] {"DisplayName-PlaylistName-index"}); - - Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); - - Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); - Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockPlaylistQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - - - // Execute the query - Object[] parameters = new Object[] { "SomeDisplayName","SomePlaylistName"}; - Object o = partTreeDynamoDBQuery.execute(parameters); - - - // Assert that we obtain the expected results - assertEquals(mockPlaylistQueryResults, o); - assertEquals(1, mockPlaylistQueryResults.size()); - assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), Playlist.class); - - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("DisplayName-PlaylistName-index",indexName); - - assertEquals("playlist",queryCaptor.getValue().getTableName()); - - - // Assert that we have the correct conditions - - assertEquals(2,queryCaptor.getValue().getKeyConditions().size()); - Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.EQ.name(),globalRangeKeyCondition.getComparisonOperator()); - assertEquals(1,globalRangeKeyCondition.getAttributeValueList().size()); - assertEquals("SomeDisplayName",globalRangeKeyCondition.getAttributeValueList().get(0).getS()); - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("playlistName"); - assertEquals(ComparisonOperator.EQ.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("SomePlaylistName",globalHashKeyCondition.getAttributeValueList().get(0).getS()); - - // Assert that all other attribute value types other than String type - // are null - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); - - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } - - // Global Secondary Index Test 4d - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKey_WhereSecondaryRangeKeyIsPrimaryHashKey() - throws ParseException { - - - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, - "findByDisplayNameAndUserName", 2, "userName", "playlistName"); - Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - - - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); -// Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("userName")).thenReturn(true); - - - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("displayName", new String[] {"DisplayName-UserName-index"}); - indexRangeKeySecondaryIndexNames.put("userName", new String[] {"DisplayName-UserName-index"}); - - Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); - - Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); - Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockPlaylistQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - - - // Execute the query - Object[] parameters = new Object[] { "SomeDisplayName","SomeUserName"}; - Object o = partTreeDynamoDBQuery.execute(parameters); - - - // Assert that we obtain the expected results - assertEquals(mockPlaylistQueryResults, o); - assertEquals(1, mockPlaylistQueryResults.size()); - assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), Playlist.class); - - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("DisplayName-UserName-index",indexName); - - assertEquals("playlist",queryCaptor.getValue().getTableName()); - - - // Assert that we have the correct conditions - - assertEquals(2,queryCaptor.getValue().getKeyConditions().size()); - Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.EQ.name(),globalRangeKeyCondition.getComparisonOperator()); - assertEquals(1,globalRangeKeyCondition.getAttributeValueList().size()); - assertEquals("SomeDisplayName",globalRangeKeyCondition.getAttributeValueList().get(0).getS()); - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("userName"); - assertEquals(ComparisonOperator.EQ.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("SomeUserName",globalHashKeyCondition.getAttributeValueList().get(0).getS()); - - // Assert that all other attribute value types other than String type - // are null - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); - - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } - - - // Global Secondary Index Test 4e - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereSecondaryHashKeyIsPrimaryHashKey() - throws ParseException { - - - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, - "findByUserNameAndDisplayNameAfter", 2, "userName", "playlistName"); - Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - - - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("userName")).thenReturn(true); -// Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); - - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("displayName", new String[] {"UserName-DisplayName-index"}); - indexRangeKeySecondaryIndexNames.put("userName", new String[] {"UserName-DisplayName-index"}); - - Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); - - Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); - Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockPlaylistQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - - - // Execute the query - Object[] parameters = new Object[] { "1","Michael"}; - Object o = partTreeDynamoDBQuery.execute(parameters); - - - // Assert that we obtain the expected results - assertEquals(mockPlaylistQueryResults, o); - assertEquals(1, mockPlaylistQueryResults.size()); - assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), Playlist.class); - - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("UserName-DisplayName-index",indexName); - - assertEquals("playlist",queryCaptor.getValue().getTableName()); - - - // Assert that we the correct conditions - assertEquals(2,queryCaptor.getValue().getKeyConditions().size()); - Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.GT.name(),globalRangeKeyCondition.getComparisonOperator()); - assertEquals(1,globalRangeKeyCondition.getAttributeValueList().size()); - assertEquals("Michael",globalRangeKeyCondition.getAttributeValueList().get(0).getS()); - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("userName"); - assertEquals(ComparisonOperator.EQ.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("1",globalHashKeyCondition.getAttributeValueList().get(0).getS()); - - // Assert that all other attribute value types other than String type - // are null - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); - - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } - - // Global Secondary Index Test 4e2 - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereSecondaryHashKeyIsPrimaryHashKey_WhenAccessingPropertyViaCompositeIdPath() - throws ParseException { - - - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, - "findByPlaylistIdUserNameAndDisplayNameAfter", 2, "userName", "playlistName"); - Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - - - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("userName")).thenReturn(true); -// Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); - - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("displayName", new String[] {"UserName-DisplayName-index"}); - indexRangeKeySecondaryIndexNames.put("userName", new String[] {"UserName-DisplayName-index"}); - - Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); - - Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); - Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockPlaylistQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - - - // Execute the query - Object[] parameters = new Object[] { "1","Michael"}; - Object o = partTreeDynamoDBQuery.execute(parameters); - - - // Assert that we obtain the expected results - assertEquals(mockPlaylistQueryResults, o); - assertEquals(1, mockPlaylistQueryResults.size()); - assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), Playlist.class); - - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("UserName-DisplayName-index",indexName); - - assertEquals("playlist",queryCaptor.getValue().getTableName()); - - - // Assert that we the correct conditions - assertEquals(2,queryCaptor.getValue().getKeyConditions().size()); - Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.GT.name(),globalRangeKeyCondition.getComparisonOperator()); - assertEquals(1,globalRangeKeyCondition.getAttributeValueList().size()); - assertEquals("Michael",globalRangeKeyCondition.getAttributeValueList().get(0).getS()); - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("userName"); - assertEquals(ComparisonOperator.EQ.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("1",globalHashKeyCondition.getAttributeValueList().get(0).getS()); - - // Assert that all other attribute value types other than String type - // are null - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); - - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } - - // Global Secondary Index Test 4f - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereSecondaryHashKeyIsPrimaryRangeKey() - throws ParseException { - - - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, - "findByPlaylistNameAndDisplayNameAfter", 2, "userName", "playlistName"); - Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - - - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("playlistName")).thenReturn(true); -// Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("playlistName", new String[] {"PlaylistName-DisplayName-index"}); - indexRangeKeySecondaryIndexNames.put("displayName", new String[] {"PlaylistName-DisplayName-index"}); - - Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); - - Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); - Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockPlaylistQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - - - // Execute the query - Object[] parameters = new Object[] { "SomePlaylistName","Michael"}; - Object o = partTreeDynamoDBQuery.execute(parameters); - - - // Assert that we obtain the expected results - assertEquals(mockPlaylistQueryResults, o); - assertEquals(1, mockPlaylistQueryResults.size()); - assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), Playlist.class); - - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("PlaylistName-DisplayName-index",indexName); - - assertEquals("playlist",queryCaptor.getValue().getTableName()); - - - // Assert that we have the correct conditions - assertEquals(2,queryCaptor.getValue().getKeyConditions().size()); - Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.GT.name(),globalRangeKeyCondition.getComparisonOperator()); - assertEquals(1,globalRangeKeyCondition.getAttributeValueList().size()); - assertEquals("Michael",globalRangeKeyCondition.getAttributeValueList().get(0).getS()); - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("playlistName"); - assertEquals(ComparisonOperator.EQ.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("SomePlaylistName",globalHashKeyCondition.getAttributeValueList().get(0).getS()); - - // Assert that all other attribute value types other than String type - // are null - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); - - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } - - - - // Global Secondary Index Test 4g - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereSecondaryRangeKeyIsPrimaryRangeKey() - throws ParseException { + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); + // Execute the query + Object[] parameters = new Object[]{"1", "Michael"}; + Object o = partTreeDynamoDBQuery.execute(parameters); - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, - "findByDisplayNameAndPlaylistNameAfter", 2, "userName", "playlistName"); - Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); + // Assert that we obtain the expected results + assertEquals(mockPlaylistQueryResults, o); + assertEquals(1, mockPlaylistQueryResults.size()); + assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), Playlist.class); - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("playlistName")).thenReturn(true); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("UserName-DisplayName-index", indexName); + assertEquals("playlist", queryCaptor.getValue().getTableName()); - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("displayName", new String[] {"DisplayName-PlaylistName-index"}); - indexRangeKeySecondaryIndexNames.put("playlistName", new String[] {"DisplayName-PlaylistName-index"}); + // Assert that we the correct conditions + assertEquals(2, queryCaptor.getValue().getKeyConditions().size()); + Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); + assertEquals(ComparisonOperator.GT.name(), globalRangeKeyCondition.getComparisonOperator()); + assertEquals(1, globalRangeKeyCondition.getAttributeValueList().size()); + assertEquals("Michael", globalRangeKeyCondition.getAttributeValueList().get(0).getS()); + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("userName"); + assertEquals(ComparisonOperator.EQ.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("1", globalHashKeyCondition.getAttributeValueList().get(0).getS()); - Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); + // Assert that all other attribute value types other than String type + // are null + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); - Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockPlaylistQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); + // Global Secondary Index Test 4e2 + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereSecondaryHashKeyIsPrimaryHashKey_WhenAccessingPropertyViaCompositeIdPath() + throws ParseException { + setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, + Playlist.class, "findByPlaylistIdUserNameAndDisplayNameAfter", 2, "userName", "playlistName"); + Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - // Execute the query - Object[] parameters = new Object[] { "SomeDisplayName","SomePlaylistName"}; - Object o = partTreeDynamoDBQuery.execute(parameters); + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("userName")).thenReturn(true); + // Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("displayName", new String[]{"UserName-DisplayName-index"}); + indexRangeKeySecondaryIndexNames.put("userName", new String[]{"UserName-DisplayName-index"}); - // Assert that we obtain the expected results - assertEquals(mockPlaylistQueryResults, o); - assertEquals(1, mockPlaylistQueryResults.size()); - assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); + Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), Playlist.class); + Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("DisplayName-PlaylistName-index",indexName); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - assertEquals("playlist",queryCaptor.getValue().getTableName()); + // Execute the query + Object[] parameters = new Object[]{"1", "Michael"}; + Object o = partTreeDynamoDBQuery.execute(parameters); + // Assert that we obtain the expected results + assertEquals(mockPlaylistQueryResults, o); + assertEquals(1, mockPlaylistQueryResults.size()); + assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - // Assert that we have the correct conditions + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), Playlist.class); - assertEquals(2,queryCaptor.getValue().getKeyConditions().size()); - Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.EQ.name(),globalRangeKeyCondition.getComparisonOperator()); - assertEquals(1,globalRangeKeyCondition.getAttributeValueList().size()); - assertEquals("SomeDisplayName",globalRangeKeyCondition.getAttributeValueList().get(0).getS()); - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("playlistName"); - assertEquals(ComparisonOperator.GT.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("SomePlaylistName",globalHashKeyCondition.getAttributeValueList().get(0).getS()); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("UserName-DisplayName-index", indexName); - // Assert that all other attribute value types other than String type - // are null - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + assertEquals("playlist", queryCaptor.getValue().getTableName()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); + // Assert that we the correct conditions + assertEquals(2, queryCaptor.getValue().getKeyConditions().size()); + Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); + assertEquals(ComparisonOperator.GT.name(), globalRangeKeyCondition.getComparisonOperator()); + assertEquals(1, globalRangeKeyCondition.getAttributeValueList().size()); + assertEquals("Michael", globalRangeKeyCondition.getAttributeValueList().get(0).getS()); + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("userName"); + assertEquals(ComparisonOperator.EQ.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("1", globalHashKeyCondition.getAttributeValueList().get(0).getS()); - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } + // Assert that all other attribute value types other than String type + // are null + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - // Global Secondary Index Test 4h - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereSecondaryRangeKeyIsPrimaryHashKey() - throws ParseException { + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } + // Global Secondary Index Test 4f + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereSecondaryHashKeyIsPrimaryRangeKey() + throws ParseException { - setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, Playlist.class, - "findByDisplayNameAndUserNameAfter", 2, "userName", "playlistName"); - Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); + setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, + Playlist.class, "findByPlaylistNameAndDisplayNameAfter", 2, "userName", "playlistName"); + Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("playlistName")).thenReturn(true); + // Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("displayName")).thenReturn(true); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("playlistName", new String[]{"PlaylistName-DisplayName-index"}); + indexRangeKeySecondaryIndexNames.put("displayName", new String[]{"PlaylistName-DisplayName-index"}); - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); - Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("userName")).thenReturn(true); + Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); + Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("displayName", new String[] {"DisplayName-UserName-index"}); - indexRangeKeySecondaryIndexNames.put("userName", new String[] {"DisplayName-UserName-index"}); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); + // Execute the query + Object[] parameters = new Object[]{"SomePlaylistName", "Michael"}; + Object o = partTreeDynamoDBQuery.execute(parameters); - Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); + // Assert that we obtain the expected results + assertEquals(mockPlaylistQueryResults, o); + assertEquals(1, mockPlaylistQueryResults.size()); + assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); - Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockPlaylistQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), Playlist.class); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("PlaylistName-DisplayName-index", indexName); - // Execute the query - Object[] parameters = new Object[] { "SomeDisplayName","SomeUserName"}; - Object o = partTreeDynamoDBQuery.execute(parameters); + assertEquals("playlist", queryCaptor.getValue().getTableName()); + // Assert that we have the correct conditions + assertEquals(2, queryCaptor.getValue().getKeyConditions().size()); + Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); + assertEquals(ComparisonOperator.GT.name(), globalRangeKeyCondition.getComparisonOperator()); + assertEquals(1, globalRangeKeyCondition.getAttributeValueList().size()); + assertEquals("Michael", globalRangeKeyCondition.getAttributeValueList().get(0).getS()); + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("playlistName"); + assertEquals(ComparisonOperator.EQ.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("SomePlaylistName", globalHashKeyCondition.getAttributeValueList().get(0).getS()); - // Assert that we obtain the expected results - assertEquals(mockPlaylistQueryResults, o); - assertEquals(1, mockPlaylistQueryResults.size()); - assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); + // Assert that all other attribute value types other than String type + // are null + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), Playlist.class); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("DisplayName-UserName-index",indexName); + // Global Secondary Index Test 4g + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereSecondaryRangeKeyIsPrimaryRangeKey() + throws ParseException { - assertEquals("playlist",queryCaptor.getValue().getTableName()); + setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, + Playlist.class, "findByDisplayNameAndPlaylistNameAfter", 2, "userName", "playlistName"); + Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("playlistName")).thenReturn(true); - // Assert that we have the correct conditions + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("displayName", new String[]{"DisplayName-PlaylistName-index"}); + indexRangeKeySecondaryIndexNames.put("playlistName", new String[]{"DisplayName-PlaylistName-index"}); - assertEquals(2,queryCaptor.getValue().getKeyConditions().size()); - Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); - assertEquals(ComparisonOperator.EQ.name(),globalRangeKeyCondition.getComparisonOperator()); - assertEquals(1,globalRangeKeyCondition.getAttributeValueList().size()); - assertEquals("SomeDisplayName",globalRangeKeyCondition.getAttributeValueList().get(0).getS()); - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("userName"); - assertEquals(ComparisonOperator.GT.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("SomeUserName",globalHashKeyCondition.getAttributeValueList().get(0).getS()); + Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); - // Assert that all other attribute value types other than String type - // are null - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } + // Execute the query + Object[] parameters = new Object[]{"SomeDisplayName", "SomePlaylistName"}; + Object o = partTreeDynamoDBQuery.execute(parameters); + // Assert that we obtain the expected results + assertEquals(mockPlaylistQueryResults, o); + assertEquals(1, mockPlaylistQueryResults.size()); + assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - // Global Secondary Index Test 4i - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereBothSecondaryHashKeyAndSecondaryIndexRangeKeyMembersOfMultipleIndexes() - throws ParseException { + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), Playlist.class); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("DisplayName-PlaylistName-index", indexName); - setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, - "findByNameAndPostCodeAfter", 2, "id", null); - Mockito.when(mockDynamoDBUserQueryMethod.isCollectionQuery()).thenReturn(true); + assertEquals("playlist", queryCaptor.getValue().getTableName()); + // Assert that we have the correct conditions - Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("name")).thenReturn(true); - Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("postCode")).thenReturn(true); + assertEquals(2, queryCaptor.getValue().getKeyConditions().size()); + Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); + assertEquals(ComparisonOperator.EQ.name(), globalRangeKeyCondition.getComparisonOperator()); + assertEquals(1, globalRangeKeyCondition.getAttributeValueList().size()); + assertEquals("SomeDisplayName", globalRangeKeyCondition.getAttributeValueList().get(0).getS()); + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("playlistName"); + assertEquals(ComparisonOperator.GT.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("SomePlaylistName", globalHashKeyCondition.getAttributeValueList().get(0).getS()); + // Assert that all other attribute value types other than String type + // are null + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("name", new String[] {"Name-PostCode-index","Name-JoinYear-index"}); - indexRangeKeySecondaryIndexNames.put("postCode", new String[] {"Name-PostCode-index","Id-PostCode-index"}); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - Mockito.when(mockUserEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); + // Global Secondary Index Test 4h + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityWithCompositeKeyList_WhenFindingByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereSecondaryRangeKeyIsPrimaryHashKey() + throws ParseException { - Mockito.when(mockUserEntityMetadata.getDynamoDBTableName()).thenReturn("user"); + setupCommonMocksForThisRepositoryMethod(mockPlaylistEntityMetadata, mockDynamoDBPlaylistQueryMethod, + Playlist.class, "findByDisplayNameAndUserNameAfter", 2, "userName", "playlistName"); + Mockito.when(mockDynamoDBPlaylistQueryMethod.isCollectionQuery()).thenReturn(true); - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockUserQueryResults.get(0)).thenReturn(mockUser); - Mockito.when(mockUserQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockUserQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(User.class, "user")).thenReturn("user"); + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexHashKeyProperty("displayName")).thenReturn(true); + Mockito.when(mockPlaylistEntityMetadata.isGlobalIndexRangeKeyProperty("userName")).thenReturn(true); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("displayName", new String[]{"DisplayName-UserName-index"}); + indexRangeKeySecondaryIndexNames.put("userName", new String[]{"DisplayName-UserName-index"}); - // Execute the query - Object[] parameters = new Object[] { "SomeName","SomePostCode"}; - Object o = partTreeDynamoDBQuery.execute(parameters); + Mockito.when(mockPlaylistEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); + Mockito.when(mockPlaylistEntityMetadata.getDynamoDBTableName()).thenReturn("playlist"); - // Assert that we obtain the expected results - assertEquals(mockUserQueryResults, o); - assertEquals(1, mockUserQueryResults.size()); - assertEquals(mockUser, mockUserQueryResults.get(0)); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockPlaylistQueryResults.get(0)).thenReturn(mockPlaylist); + Mockito.when(mockPlaylistQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockPlaylistQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(Playlist.class, "playlist")).thenReturn("playlist"); - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), User.class); + // Execute the query + Object[] parameters = new Object[]{"SomeDisplayName", "SomeUserName"}; + Object o = partTreeDynamoDBQuery.execute(parameters); - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("Name-PostCode-index",indexName); + // Assert that we obtain the expected results + assertEquals(mockPlaylistQueryResults, o); + assertEquals(1, mockPlaylistQueryResults.size()); + assertEquals(mockPlaylist, mockPlaylistQueryResults.get(0)); - assertEquals("user",queryCaptor.getValue().getTableName()); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), Playlist.class); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("DisplayName-UserName-index", indexName); - // Assert that we have the correct conditions + assertEquals("playlist", queryCaptor.getValue().getTableName()); - assertEquals(2,queryCaptor.getValue().getKeyConditions().size()); - Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("name"); - assertEquals(ComparisonOperator.EQ.name(),globalRangeKeyCondition.getComparisonOperator()); - assertEquals(1,globalRangeKeyCondition.getAttributeValueList().size()); - assertEquals("SomeName",globalRangeKeyCondition.getAttributeValueList().get(0).getS()); - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("postCode"); - assertEquals(ComparisonOperator.GT.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("SomePostCode",globalHashKeyCondition.getAttributeValueList().get(0).getS()); + // Assert that we have the correct conditions - // Assert that all other attribute value types other than String type - // are null - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + assertEquals(2, queryCaptor.getValue().getKeyConditions().size()); + Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("displayName"); + assertEquals(ComparisonOperator.EQ.name(), globalRangeKeyCondition.getComparisonOperator()); + assertEquals(1, globalRangeKeyCondition.getAttributeValueList().size()); + assertEquals("SomeDisplayName", globalRangeKeyCondition.getAttributeValueList().get(0).getS()); + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("userName"); + assertEquals(ComparisonOperator.GT.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("SomeUserName", globalHashKeyCondition.getAttributeValueList().get(0).getS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); + // Assert that all other attribute value types other than String type + // are null + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } - // Global Secondary Index Test 4j - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityByGlobalSecondaryHashAndRangeIndexHashCondition_WhereSecondaryHashKeyMemberOfMultipleIndexes() - throws ParseException { + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } + // Global Secondary Index Test 4i + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityByGlobalSecondaryHashAndRangeIndexHashAndRangeKeyNonEqualityCondition_WhereBothSecondaryHashKeyAndSecondaryIndexRangeKeyMembersOfMultipleIndexes() + throws ParseException { - setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, - "findByName", 1, "id", null); - Mockito.when(mockDynamoDBUserQueryMethod.isCollectionQuery()).thenReturn(true); + setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, + "findByNameAndPostCodeAfter", 2, "id", null); + Mockito.when(mockDynamoDBUserQueryMethod.isCollectionQuery()).thenReturn(true); + Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("name")).thenReturn(true); + Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("postCode")).thenReturn(true); - Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("name")).thenReturn(true); -// Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("postCode")).thenReturn(true); -// Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("joinYear")).thenReturn(true); -// Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("id")).thenReturn(true); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("name", new String[]{"Name-PostCode-index", "Name-JoinYear-index"}); + indexRangeKeySecondaryIndexNames.put("postCode", new String[]{"Name-PostCode-index", "Id-PostCode-index"}); + Mockito.when(mockUserEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("name", new String[] {"Name-PostCode-index","Name-JoinYear-index"}); - indexRangeKeySecondaryIndexNames.put("postCode", new String[] {"Name-PostCode-index","Id-PostCode-index"}); - indexRangeKeySecondaryIndexNames.put("joinYear", new String[] {"Name-JoinYear-index"}); - indexRangeKeySecondaryIndexNames.put("id", new String[] {"Id-PostCode-index"}); + Mockito.when(mockUserEntityMetadata.getDynamoDBTableName()).thenReturn("user"); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockUserQueryResults.get(0)).thenReturn(mockUser); + Mockito.when(mockUserQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockUserQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(User.class, "user")).thenReturn("user"); - Mockito.when(mockUserEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); + // Execute the query + Object[] parameters = new Object[]{"SomeName", "SomePostCode"}; + Object o = partTreeDynamoDBQuery.execute(parameters); - Mockito.when(mockUserEntityMetadata.getDynamoDBTableName()).thenReturn("user"); + // Assert that we obtain the expected results + assertEquals(mockUserQueryResults, o); + assertEquals(1, mockUserQueryResults.size()); + assertEquals(mockUser, mockUserQueryResults.get(0)); - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockUserQueryResults.get(0)).thenReturn(mockUser); - Mockito.when(mockUserQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockUserQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(User.class, "user")).thenReturn("user"); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), User.class); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("Name-PostCode-index", indexName); - // Execute the query - Object[] parameters = new Object[] { "SomeName"}; - Object o = partTreeDynamoDBQuery.execute(parameters); + assertEquals("user", queryCaptor.getValue().getTableName()); + // Assert that we have the correct conditions - // Assert that we obtain the expected results - assertEquals(mockUserQueryResults, o); - assertEquals(1, mockUserQueryResults.size()); - assertEquals(mockUser, mockUserQueryResults.get(0)); + assertEquals(2, queryCaptor.getValue().getKeyConditions().size()); + Condition globalRangeKeyCondition = queryCaptor.getValue().getKeyConditions().get("name"); + assertEquals(ComparisonOperator.EQ.name(), globalRangeKeyCondition.getComparisonOperator()); + assertEquals(1, globalRangeKeyCondition.getAttributeValueList().size()); + assertEquals("SomeName", globalRangeKeyCondition.getAttributeValueList().get(0).getS()); + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("postCode"); + assertEquals(ComparisonOperator.GT.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("SomePostCode", globalHashKeyCondition.getAttributeValueList().get(0).getS()); - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), User.class); + // Assert that all other attribute value types other than String type + // are null + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalRangeKeyCondition.getAttributeValueList().get(0).getBS()); + + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("Name-PostCode-index",indexName); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } + // Global Secondary Index Test 4j + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityByGlobalSecondaryHashAndRangeIndexHashCondition_WhereSecondaryHashKeyMemberOfMultipleIndexes() + throws ParseException { - assertEquals("user",queryCaptor.getValue().getTableName()); + setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, + "findByName", 1, "id", null); + Mockito.when(mockDynamoDBUserQueryMethod.isCollectionQuery()).thenReturn(true); + Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("name")).thenReturn(true); + // Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("postCode")).thenReturn(true); + // Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("joinYear")).thenReturn(true); + // Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("id")).thenReturn(true); - // Assert that we have the correct conditions - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("name"); - assertEquals(ComparisonOperator.EQ.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("SomeName",globalHashKeyCondition.getAttributeValueList().get(0).getS()); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("name", new String[]{"Name-PostCode-index", "Name-JoinYear-index"}); + indexRangeKeySecondaryIndexNames.put("postCode", new String[]{"Name-PostCode-index", "Id-PostCode-index"}); + indexRangeKeySecondaryIndexNames.put("joinYear", new String[]{"Name-JoinYear-index"}); + indexRangeKeySecondaryIndexNames.put("id", new String[]{"Id-PostCode-index"}); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); + Mockito.when(mockUserEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } + Mockito.when(mockUserEntityMetadata.getDynamoDBTableName()).thenReturn("user"); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockUserQueryResults.get(0)).thenReturn(mockUser); + Mockito.when(mockUserQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockUserQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(User.class, "user")).thenReturn("user"); - // Global Secondary Index Test 4k - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenFinderMethodIsFindingEntityByGlobalSecondaryHashAndRangeIndexHashCondition_WhereSecondaryHashKeyMemberOfMultipleIndexes_WhereOneIndexIsExactMatch() - throws ParseException { + // Execute the query + Object[] parameters = new Object[]{"SomeName"}; + Object o = partTreeDynamoDBQuery.execute(parameters); + // Assert that we obtain the expected results + assertEquals(mockUserQueryResults, o); + assertEquals(1, mockUserQueryResults.size()); + assertEquals(mockUser, mockUserQueryResults.get(0)); - setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, - "findByName", 1, "id", null); - Mockito.when(mockDynamoDBUserQueryMethod.isCollectionQuery()).thenReturn(true); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), User.class); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("Name-PostCode-index", indexName); - Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("name")).thenReturn(true); -// Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("postCode")).thenReturn(true); -// Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("joinYear")).thenReturn(true); -// Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("id")).thenReturn(true); + assertEquals("user", queryCaptor.getValue().getTableName()); + // Assert that we have the correct conditions + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("name"); + assertEquals(ComparisonOperator.EQ.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("SomeName", globalHashKeyCondition.getAttributeValueList().get(0).getS()); - Map indexRangeKeySecondaryIndexNames = new HashMap(); - indexRangeKeySecondaryIndexNames.put("name", new String[] {"Name-PostCode-index","Name-index","Name-JoinYear-index"}); - indexRangeKeySecondaryIndexNames.put("postCode", new String[] {"Name-PostCode-index","Id-PostCode-index"}); - indexRangeKeySecondaryIndexNames.put("joinYear", new String[] {"Name-JoinYear-index"}); - indexRangeKeySecondaryIndexNames.put("id", new String[] {"Id-PostCode-index"}); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - Mockito.when(mockUserEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()).thenReturn(indexRangeKeySecondaryIndexNames); + // Global Secondary Index Test 4k + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenFinderMethodIsFindingEntityByGlobalSecondaryHashAndRangeIndexHashCondition_WhereSecondaryHashKeyMemberOfMultipleIndexes_WhereOneIndexIsExactMatch() + throws ParseException { - Mockito.when(mockUserEntityMetadata.getDynamoDBTableName()).thenReturn("user"); + setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, + "findByName", 1, "id", null); + Mockito.when(mockDynamoDBUserQueryMethod.isCollectionQuery()).thenReturn(true); - // Mock out specific QueryRequestMapper behavior expected by this method - ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); - Mockito.when(mockUserQueryResults.get(0)).thenReturn(mockUser); - Mockito.when(mockUserQueryResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) - .thenReturn(mockUserQueryResults); - Mockito.when(mockDynamoDBOperations.getOverriddenTableName(User.class, "user")).thenReturn("user"); + Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("name")).thenReturn(true); + // Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("postCode")).thenReturn(true); + // Mockito.when(mockUserEntityMetadata.isGlobalIndexRangeKeyProperty("joinYear")).thenReturn(true); + // Mockito.when(mockUserEntityMetadata.isGlobalIndexHashKeyProperty("id")).thenReturn(true); + Map indexRangeKeySecondaryIndexNames = new HashMap(); + indexRangeKeySecondaryIndexNames.put("name", + new String[]{"Name-PostCode-index", "Name-index", "Name-JoinYear-index"}); + indexRangeKeySecondaryIndexNames.put("postCode", new String[]{"Name-PostCode-index", "Id-PostCode-index"}); + indexRangeKeySecondaryIndexNames.put("joinYear", new String[]{"Name-JoinYear-index"}); + indexRangeKeySecondaryIndexNames.put("id", new String[]{"Id-PostCode-index"}); - // Execute the query - Object[] parameters = new Object[] { "SomeName"}; - Object o = partTreeDynamoDBQuery.execute(parameters); + Mockito.when(mockUserEntityMetadata.getGlobalSecondaryIndexNamesByPropertyName()) + .thenReturn(indexRangeKeySecondaryIndexNames); + Mockito.when(mockUserEntityMetadata.getDynamoDBTableName()).thenReturn("user"); - // Assert that we obtain the expected results - assertEquals(mockUserQueryResults, o); - assertEquals(1, mockUserQueryResults.size()); - assertEquals(mockUser, mockUserQueryResults.get(0)); + // Mock out specific QueryRequestMapper behavior expected by this method + ArgumentCaptor queryCaptor = ArgumentCaptor.forClass(QueryRequest.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + Mockito.when(mockUserQueryResults.get(0)).thenReturn(mockUser); + Mockito.when(mockUserQueryResults.size()).thenReturn(1); + Mockito.when(mockDynamoDBOperations.query(classCaptor.capture(), queryCaptor.capture())) + .thenReturn(mockUserQueryResults); + Mockito.when(mockDynamoDBOperations.getOverriddenTableName(User.class, "user")).thenReturn("user"); - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), User.class); + // Execute the query + Object[] parameters = new Object[]{"SomeName"}; + Object o = partTreeDynamoDBQuery.execute(parameters); - String indexName = queryCaptor.getValue().getIndexName(); - assertNotNull(indexName); - assertEquals("Name-index",indexName); + // Assert that we obtain the expected results + assertEquals(mockUserQueryResults, o); + assertEquals(1, mockUserQueryResults.size()); + assertEquals(mockUser, mockUserQueryResults.get(0)); - assertEquals("user",queryCaptor.getValue().getTableName()); + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), User.class); + String indexName = queryCaptor.getValue().getIndexName(); + assertNotNull(indexName); + assertEquals("Name-index", indexName); - // Assert that we have the correct conditions - Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("name"); - assertEquals(ComparisonOperator.EQ.name(),globalHashKeyCondition.getComparisonOperator()); - assertEquals(1,globalHashKeyCondition.getAttributeValueList().size()); - assertEquals("SomeName",globalHashKeyCondition.getAttributeValueList().get(0).getS()); + assertEquals("user", queryCaptor.getValue().getTableName()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); - assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); + // Assert that we have the correct conditions + Condition globalHashKeyCondition = queryCaptor.getValue().getKeyConditions().get("name"); + assertEquals(ComparisonOperator.EQ.name(), globalHashKeyCondition.getComparisonOperator()); + assertEquals(1, globalHashKeyCondition.getAttributeValueList().size()); + assertEquals("SomeName", globalHashKeyCondition.getAttributeValueList().get(0).getS()); - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); - } + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getSS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getN()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getNS()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getB()); + assertNull(globalHashKeyCondition.getAttributeValueList().get(0).getBS()); + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).query(classCaptor.getValue(), queryCaptor.getValue()); + } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringParameter_WithCustomMarshaller_WhenNotFindingByHashKey() throws ParseException { @@ -3446,11 +3347,11 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringPara ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { postcode }; + Object[] parameters = new Object[]{postcode}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected list of results @@ -3492,7 +3393,7 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringPara Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleIntegerParameter_WhenNotFindingByHashKey() { int numberOfPlaylists = 5; @@ -3506,11 +3407,11 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleIntegerPar ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { numberOfPlaylists }; + Object[] parameters = new Object[]{numberOfPlaylists}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected list of results @@ -3552,7 +3453,7 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleIntegerPar Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringParameter_WhenNotFindingByNotHashKey() { setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, @@ -3564,11 +3465,11 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringPara ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { "someId" }; + Object[] parameters = new Object[]{"someId"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected list of results @@ -3610,7 +3511,7 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringPara Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringParameter_WhenNotFindingByNotAProperty() { setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, @@ -3622,11 +3523,11 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringPara ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); // Execute the query - Object[] parameters = new Object[] { "someName" }; + Object[] parameters = new Object[]{"someName"}; Object o = partTreeDynamoDBQuery.execute(parameters); // Assert that we obtain the expected list of results @@ -3668,278 +3569,277 @@ public void testExecute_WhenFinderMethodIsFindingEntityList_WithSingleStringPara Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); } - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenExistsQueryFindsNoEntity() { - setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, - "existsByName", 1, "id", null); - Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("name")).thenReturn(Optional.of("Name")); - - // Mock out specific DynamoDBOperations behavior expected by this method - ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockUserScanResults.size()).thenReturn(0); - Mockito.when(mockUserScanResults.isEmpty()).thenReturn(true); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); - - // Execute the query - Object[] parameters = new Object[] { "someName" }; - Object o = partTreeDynamoDBQuery.execute(parameters); - - // Assert that we obtain the expected single result - assertEquals(false, o); - - // Assert that we scanned DynamoDB for the correct class - assertEquals(User.class, classCaptor.getValue()); - - // Assert that we have only one filter condition, for the name of the - // property - Map filterConditions = scanCaptor.getValue().getScanFilter(); - assertEquals(1, filterConditions.size()); - Condition filterCondition = filterConditions.get("Name"); - assertNotNull(filterCondition); - - assertEquals(ComparisonOperator.EQ.name(), filterCondition.getComparisonOperator()); - - // Assert we only have one attribute value for this filter condition - assertEquals(1, filterCondition.getAttributeValueList().size()); - - // Assert that there the attribute value type for this attribute value - // is String, - // and its value is the parameter expected - assertEquals("someName", filterCondition.getAttributeValueList().get(0).getS()); - - // Assert that all other attribute value types other than String type - // are null - assertNull(filterCondition.getAttributeValueList().get(0).getSS()); - assertNull(filterCondition.getAttributeValueList().get(0).getN()); - assertNull(filterCondition.getAttributeValueList().get(0).getNS()); - assertNull(filterCondition.getAttributeValueList().get(0).getB()); - assertNull(filterCondition.getAttributeValueList().get(0).getBS()); - - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenExistsQueryFindsOneEntity() { - setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, - "existsByName", 1, "id", null); - Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("name")).thenReturn(Optional.of("Name")); - - // Mock out specific DynamoDBOperations behavior expected by this method - ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); -// Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockUserScanResults.isEmpty()).thenReturn(false); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); - - // Execute the query - Object[] parameters = new Object[] { "someName" }; - Object o = partTreeDynamoDBQuery.execute(parameters); - - // Assert that we obtain the expected single result - assertEquals(true, o); - - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), User.class); - - // Assert that we have only one filter condition, for the name of the - // property - Map filterConditions = scanCaptor.getValue().getScanFilter(); - assertEquals(1, filterConditions.size()); - Condition filterCondition = filterConditions.get("Name"); - assertNotNull(filterCondition); - - assertEquals(ComparisonOperator.EQ.name(), filterCondition.getComparisonOperator()); - - // Assert we only have one attribute value for this filter condition - assertEquals(1, filterCondition.getAttributeValueList().size()); - - // Assert that there the attribute value type for this attribute value - // is String, - // and its value is the parameter expected - assertEquals("someName", filterCondition.getAttributeValueList().get(0).getS()); - - // Assert that all other attribute value types other than String type - // are null - assertNull(filterCondition.getAttributeValueList().get(0).getSS()); - assertNull(filterCondition.getAttributeValueList().get(0).getN()); - assertNull(filterCondition.getAttributeValueList().get(0).getNS()); - assertNull(filterCondition.getAttributeValueList().get(0).getB()); - assertNull(filterCondition.getAttributeValueList().get(0).getBS()); - - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); - } - - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenExistsQueryFindsMultipleEntities() { - setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, - "existsByName", 1, "id", null); - Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("name")).thenReturn(Optional.of("Name")); - - // Mock out specific DynamoDBOperations behavior expected by this method - ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); -// Mockito.when(mockUserScanResults.get(1)).thenReturn(mockUser); -// Mockito.when(mockUserScanResults.size()).thenReturn(2); - Mockito.when(mockUserScanResults.isEmpty()).thenReturn(false); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); - - // Execute the query - Object[] parameters = new Object[] { "someName" }; - Object o = partTreeDynamoDBQuery.execute(parameters); - - // Assert that we obtain the expected single result - assertEquals(true, o); - - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), User.class); - - // Assert that we have only one filter condition, for the name of the - // property - Map filterConditions = scanCaptor.getValue().getScanFilter(); - assertEquals(1, filterConditions.size()); - Condition filterCondition = filterConditions.get("Name"); - assertNotNull(filterCondition); - - assertEquals(ComparisonOperator.EQ.name(), filterCondition.getComparisonOperator()); - - // Assert we only have one attribute value for this filter condition - assertEquals(1, filterCondition.getAttributeValueList().size()); - - // Assert that there the attribute value type for this attribute value - // is String, - // and its value is the parameter expected - assertEquals("someName", filterCondition.getAttributeValueList().get(0).getS()); - - // Assert that all other attribute value types other than String type - // are null - assertNull(filterCondition.getAttributeValueList().get(0).getSS()); - assertNull(filterCondition.getAttributeValueList().get(0).getN()); - assertNull(filterCondition.getAttributeValueList().get(0).getNS()); - assertNull(filterCondition.getAttributeValueList().get(0).getB()); - assertNull(filterCondition.getAttributeValueList().get(0).getBS()); - - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenExistsWithLimitQueryFindsNoEntity() { - setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, - "existsTop1ByName", 1, "id", null); - Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("name")).thenReturn(Optional.of("Name")); - - // Mock out specific DynamoDBOperations behavior expected by this method - ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockUserScanResults.size()).thenReturn(0); - Mockito.when(mockUserScanResults.isEmpty()).thenReturn(true); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); - - // Execute the query - Object[] parameters = new Object[] { "someName" }; - Object o = partTreeDynamoDBQuery.execute(parameters); - - // Assert that we obtain the expected single result - assertEquals(false, o); - - // Assert that we scanned DynamoDB for the correct class - assertEquals(User.class, classCaptor.getValue()); - - // Assert that we have only one filter condition, for the name of the - // property - Map filterConditions = scanCaptor.getValue().getScanFilter(); - assertEquals(1, filterConditions.size()); - Condition filterCondition = filterConditions.get("Name"); - assertNotNull(filterCondition); - - assertEquals(ComparisonOperator.EQ.name(), filterCondition.getComparisonOperator()); - - // Assert we only have one attribute value for this filter condition - assertEquals(1, filterCondition.getAttributeValueList().size()); - - // Assert that there the attribute value type for this attribute value - // is String, - // and its value is the parameter expected - assertEquals("someName", filterCondition.getAttributeValueList().get(0).getS()); - - // Assert that all other attribute value types other than String type - // are null - assertNull(filterCondition.getAttributeValueList().get(0).getSS()); - assertNull(filterCondition.getAttributeValueList().get(0).getN()); - assertNull(filterCondition.getAttributeValueList().get(0).getNS()); - assertNull(filterCondition.getAttributeValueList().get(0).getB()); - assertNull(filterCondition.getAttributeValueList().get(0).getBS()); - - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testExecute_WhenExistsWithLimitQueryFindsOneEntity() { - setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, - "existsTop1ByName", 1, "id", null); - Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("name")).thenReturn(Optional.of("Name")); - - // Mock out specific DynamoDBOperations behavior expected by this method - ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); - ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); -// Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); -// Mockito.when(mockUserScanResults.size()).thenReturn(1); - Mockito.when(mockUserScanResults.isEmpty()).thenReturn(false); - Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())).thenReturn( - mockUserScanResults); - - // Execute the query - Object[] parameters = new Object[] { "someName" }; - Object o = partTreeDynamoDBQuery.execute(parameters); - - // Assert that we obtain the expected single result - assertEquals(true, o); - - // Assert that we scanned DynamoDB for the correct class - assertEquals(classCaptor.getValue(), User.class); - - // Assert that we have only one filter condition, for the name of the - // property - Map filterConditions = scanCaptor.getValue().getScanFilter(); - assertEquals(1, filterConditions.size()); - Condition filterCondition = filterConditions.get("Name"); - assertNotNull(filterCondition); - - assertEquals(ComparisonOperator.EQ.name(), filterCondition.getComparisonOperator()); - - // Assert we only have one attribute value for this filter condition - assertEquals(1, filterCondition.getAttributeValueList().size()); - - // Assert that there the attribute value type for this attribute value - // is String, - // and its value is the parameter expected - assertEquals("someName", filterCondition.getAttributeValueList().get(0).getS()); - - // Assert that all other attribute value types other than String type - // are null - assertNull(filterCondition.getAttributeValueList().get(0).getSS()); - assertNull(filterCondition.getAttributeValueList().get(0).getN()); - assertNull(filterCondition.getAttributeValueList().get(0).getNS()); - assertNull(filterCondition.getAttributeValueList().get(0).getB()); - assertNull(filterCondition.getAttributeValueList().get(0).getBS()); - - // Verify that the expected DynamoDBOperations method was called - Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); - } + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenExistsQueryFindsNoEntity() { + setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, + "existsByName", 1, "id", null); + Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("name")).thenReturn(Optional.of("Name")); + + // Mock out specific DynamoDBOperations behavior expected by this method + ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + // Mockito.when(mockUserScanResults.size()).thenReturn(0); + Mockito.when(mockUserScanResults.isEmpty()).thenReturn(true); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); + + // Execute the query + Object[] parameters = new Object[]{"someName"}; + Object o = partTreeDynamoDBQuery.execute(parameters); + + // Assert that we obtain the expected single result + assertEquals(false, o); + + // Assert that we scanned DynamoDB for the correct class + assertEquals(User.class, classCaptor.getValue()); + + // Assert that we have only one filter condition, for the name of the + // property + Map filterConditions = scanCaptor.getValue().getScanFilter(); + assertEquals(1, filterConditions.size()); + Condition filterCondition = filterConditions.get("Name"); + assertNotNull(filterCondition); + + assertEquals(ComparisonOperator.EQ.name(), filterCondition.getComparisonOperator()); + + // Assert we only have one attribute value for this filter condition + assertEquals(1, filterCondition.getAttributeValueList().size()); + + // Assert that there the attribute value type for this attribute value + // is String, + // and its value is the parameter expected + assertEquals("someName", filterCondition.getAttributeValueList().get(0).getS()); + + // Assert that all other attribute value types other than String type + // are null + assertNull(filterCondition.getAttributeValueList().get(0).getSS()); + assertNull(filterCondition.getAttributeValueList().get(0).getN()); + assertNull(filterCondition.getAttributeValueList().get(0).getNS()); + assertNull(filterCondition.getAttributeValueList().get(0).getB()); + assertNull(filterCondition.getAttributeValueList().get(0).getBS()); + + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenExistsQueryFindsOneEntity() { + setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, + "existsByName", 1, "id", null); + Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("name")).thenReturn(Optional.of("Name")); + + // Mock out specific DynamoDBOperations behavior expected by this method + ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + // Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); + // Mockito.when(mockUserScanResults.size()).thenReturn(1); + Mockito.when(mockUserScanResults.isEmpty()).thenReturn(false); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); + + // Execute the query + Object[] parameters = new Object[]{"someName"}; + Object o = partTreeDynamoDBQuery.execute(parameters); + + // Assert that we obtain the expected single result + assertEquals(true, o); + + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), User.class); + + // Assert that we have only one filter condition, for the name of the + // property + Map filterConditions = scanCaptor.getValue().getScanFilter(); + assertEquals(1, filterConditions.size()); + Condition filterCondition = filterConditions.get("Name"); + assertNotNull(filterCondition); + + assertEquals(ComparisonOperator.EQ.name(), filterCondition.getComparisonOperator()); + + // Assert we only have one attribute value for this filter condition + assertEquals(1, filterCondition.getAttributeValueList().size()); + + // Assert that there the attribute value type for this attribute value + // is String, + // and its value is the parameter expected + assertEquals("someName", filterCondition.getAttributeValueList().get(0).getS()); + + // Assert that all other attribute value types other than String type + // are null + assertNull(filterCondition.getAttributeValueList().get(0).getSS()); + assertNull(filterCondition.getAttributeValueList().get(0).getN()); + assertNull(filterCondition.getAttributeValueList().get(0).getNS()); + assertNull(filterCondition.getAttributeValueList().get(0).getB()); + assertNull(filterCondition.getAttributeValueList().get(0).getBS()); + + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenExistsQueryFindsMultipleEntities() { + setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, + "existsByName", 1, "id", null); + Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("name")).thenReturn(Optional.of("Name")); + + // Mock out specific DynamoDBOperations behavior expected by this method + ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + // Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); + // Mockito.when(mockUserScanResults.get(1)).thenReturn(mockUser); + // Mockito.when(mockUserScanResults.size()).thenReturn(2); + Mockito.when(mockUserScanResults.isEmpty()).thenReturn(false); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); + + // Execute the query + Object[] parameters = new Object[]{"someName"}; + Object o = partTreeDynamoDBQuery.execute(parameters); + + // Assert that we obtain the expected single result + assertEquals(true, o); + + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), User.class); + + // Assert that we have only one filter condition, for the name of the + // property + Map filterConditions = scanCaptor.getValue().getScanFilter(); + assertEquals(1, filterConditions.size()); + Condition filterCondition = filterConditions.get("Name"); + assertNotNull(filterCondition); + + assertEquals(ComparisonOperator.EQ.name(), filterCondition.getComparisonOperator()); + + // Assert we only have one attribute value for this filter condition + assertEquals(1, filterCondition.getAttributeValueList().size()); + + // Assert that there the attribute value type for this attribute value + // is String, + // and its value is the parameter expected + assertEquals("someName", filterCondition.getAttributeValueList().get(0).getS()); + + // Assert that all other attribute value types other than String type + // are null + assertNull(filterCondition.getAttributeValueList().get(0).getSS()); + assertNull(filterCondition.getAttributeValueList().get(0).getN()); + assertNull(filterCondition.getAttributeValueList().get(0).getNS()); + assertNull(filterCondition.getAttributeValueList().get(0).getB()); + assertNull(filterCondition.getAttributeValueList().get(0).getBS()); + + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenExistsWithLimitQueryFindsNoEntity() { + setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, + "existsTop1ByName", 1, "id", null); + Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("name")).thenReturn(Optional.of("Name")); + + // Mock out specific DynamoDBOperations behavior expected by this method + ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + // Mockito.when(mockUserScanResults.size()).thenReturn(0); + Mockito.when(mockUserScanResults.isEmpty()).thenReturn(true); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); + + // Execute the query + Object[] parameters = new Object[]{"someName"}; + Object o = partTreeDynamoDBQuery.execute(parameters); + + // Assert that we obtain the expected single result + assertEquals(false, o); + + // Assert that we scanned DynamoDB for the correct class + assertEquals(User.class, classCaptor.getValue()); + + // Assert that we have only one filter condition, for the name of the + // property + Map filterConditions = scanCaptor.getValue().getScanFilter(); + assertEquals(1, filterConditions.size()); + Condition filterCondition = filterConditions.get("Name"); + assertNotNull(filterCondition); + + assertEquals(ComparisonOperator.EQ.name(), filterCondition.getComparisonOperator()); + + // Assert we only have one attribute value for this filter condition + assertEquals(1, filterCondition.getAttributeValueList().size()); + + // Assert that there the attribute value type for this attribute value + // is String, + // and its value is the parameter expected + assertEquals("someName", filterCondition.getAttributeValueList().get(0).getS()); + + // Assert that all other attribute value types other than String type + // are null + assertNull(filterCondition.getAttributeValueList().get(0).getSS()); + assertNull(filterCondition.getAttributeValueList().get(0).getN()); + assertNull(filterCondition.getAttributeValueList().get(0).getNS()); + assertNull(filterCondition.getAttributeValueList().get(0).getB()); + assertNull(filterCondition.getAttributeValueList().get(0).getBS()); + + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void testExecute_WhenExistsWithLimitQueryFindsOneEntity() { + setupCommonMocksForThisRepositoryMethod(mockUserEntityMetadata, mockDynamoDBUserQueryMethod, User.class, + "existsTop1ByName", 1, "id", null); + Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("name")).thenReturn(Optional.of("Name")); + + // Mock out specific DynamoDBOperations behavior expected by this method + ArgumentCaptor scanCaptor = ArgumentCaptor.forClass(DynamoDBScanExpression.class); + ArgumentCaptor classCaptor = ArgumentCaptor.forClass(Class.class); + // Mockito.when(mockUserScanResults.get(0)).thenReturn(mockUser); + // Mockito.when(mockUserScanResults.size()).thenReturn(1); + Mockito.when(mockUserScanResults.isEmpty()).thenReturn(false); + Mockito.when(mockDynamoDBOperations.scan(classCaptor.capture(), scanCaptor.capture())) + .thenReturn(mockUserScanResults); + + // Execute the query + Object[] parameters = new Object[]{"someName"}; + Object o = partTreeDynamoDBQuery.execute(parameters); + + // Assert that we obtain the expected single result + assertEquals(true, o); + + // Assert that we scanned DynamoDB for the correct class + assertEquals(classCaptor.getValue(), User.class); + + // Assert that we have only one filter condition, for the name of the + // property + Map filterConditions = scanCaptor.getValue().getScanFilter(); + assertEquals(1, filterConditions.size()); + Condition filterCondition = filterConditions.get("Name"); + assertNotNull(filterCondition); + + assertEquals(ComparisonOperator.EQ.name(), filterCondition.getComparisonOperator()); + + // Assert we only have one attribute value for this filter condition + assertEquals(1, filterCondition.getAttributeValueList().size()); + + // Assert that there the attribute value type for this attribute value + // is String, + // and its value is the parameter expected + assertEquals("someName", filterCondition.getAttributeValueList().get(0).getS()); + + // Assert that all other attribute value types other than String type + // are null + assertNull(filterCondition.getAttributeValueList().get(0).getSS()); + assertNull(filterCondition.getAttributeValueList().get(0).getN()); + assertNull(filterCondition.getAttributeValueList().get(0).getNS()); + assertNull(filterCondition.getAttributeValueList().get(0).getB()); + assertNull(filterCondition.getAttributeValueList().get(0).getBS()); + + // Verify that the expected DynamoDBOperations method was called + Mockito.verify(mockDynamoDBOperations).scan(classCaptor.getValue(), scanCaptor.getValue()); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityMetadataSupportUnitTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityMetadataSupportUnitTest.java index 6be5e574..3c002c5e 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityMetadataSupportUnitTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBEntityMetadataSupportUnitTest.java @@ -25,18 +25,16 @@ @RunWith(MockitoJUnitRunner.class) @SuppressWarnings("unused") public class DynamoDBEntityMetadataSupportUnitTest { - + @Test - public void testGetMarshallerForProperty_WhenAnnotationIsOnField_AndReturnsDynamoDBMarshaller() - { + public void testGetMarshallerForProperty_WhenAnnotationIsOnField_AndReturnsDynamoDBMarshaller() { DynamoDBEntityMetadataSupport support = new DynamoDBEntityMetadataSupport<>(User.class); DynamoDBMarshaller fieldAnnotation = support.getMarshallerForProperty("joinYear"); Assert.assertNotNull(fieldAnnotation); } @Test - public void testGetMarshallerForProperty_WhenAnnotationIsOnMethod_AndReturnsDynamoDBMarshaller() - { + public void testGetMarshallerForProperty_WhenAnnotationIsOnMethod_AndReturnsDynamoDBMarshaller() { DynamoDBEntityMetadataSupport support = new DynamoDBEntityMetadataSupport<>(User.class); DynamoDBMarshaller methodAnnotation = support.getMarshallerForProperty("leaveDate"); Assert.assertNotNull(methodAnnotation); diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractorImplUnitTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractorImplUnitTest.java index 52e31e74..beb590e7 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractorImplUnitTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractorImplUnitTest.java @@ -28,18 +28,16 @@ @RunWith(MockitoJUnitRunner.class) @SuppressWarnings("unused") public class DynamoDBHashAndRangeKeyMethodExtractorImplUnitTest { - - private DynamoDBHashAndRangeKeyMethodExtractor playlistIdMetadata; + + private DynamoDBHashAndRangeKeyMethodExtractor playlistIdMetadata; private DynamoDBHashAndRangeKeyMethodExtractor idClassWithNoHashOrRangeKeyMethodMetadata; private DynamoDBHashAndRangeKeyMethodExtractor idClassWithOnlyHashKeyMethodMetadata; private DynamoDBHashAndRangeKeyMethodExtractor idClassWithOnlyRangeKeyMethodMetadata; private DynamoDBHashAndRangeKeyMethodExtractor idClassWitMultipleAnnotatedHashKeysMetadata; private DynamoDBHashAndRangeKeyMethodExtractor idClassWitMultipleAnnotatedRangeKeysMetadata; - @Test - public void testConstruct_WhenHashKeyMethodExists_WhenRangeKeyMethodExists() - { + public void testConstruct_WhenHashKeyMethodExists_WhenRangeKeyMethodExists() { playlistIdMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl(PlaylistId.class); Method hashKeyMethod = playlistIdMetadata.getHashKeyMethod(); Assert.assertNotNull(hashKeyMethod); @@ -47,99 +45,117 @@ public void testConstruct_WhenHashKeyMethodExists_WhenRangeKeyMethodExists() Method rangeKeyMethod = playlistIdMetadata.getRangeKeyMethod(); Assert.assertNotNull(rangeKeyMethod); Assert.assertEquals("getPlaylistName", rangeKeyMethod.getName()); - - Assert.assertEquals(PlaylistId.class,playlistIdMetadata.getJavaType()); - + + Assert.assertEquals(PlaylistId.class, playlistIdMetadata.getJavaType()); + } - - @Test(expected=IllegalArgumentException.class) - public void testConstruct_WhenHashKeyMethodExists_WhenRangeKeyMethodDoesNotExist() - { - idClassWithOnlyHashKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl(IdClassWithOnlyAnnotatedHashKeyMethod.class); - + + @Test(expected = IllegalArgumentException.class) + public void testConstruct_WhenHashKeyMethodExists_WhenRangeKeyMethodDoesNotExist() { + idClassWithOnlyHashKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl( + IdClassWithOnlyAnnotatedHashKeyMethod.class); + } - - @Test(expected=IllegalArgumentException.class) - public void testConstruct_WhenHashKeyMethodDoesNotExist_WhenRangeKeyMethodExists() - { - idClassWithOnlyRangeKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl(IdClassWithOnlyAnnotatedRangeKeyMethod.class); + + @Test(expected = IllegalArgumentException.class) + public void testConstruct_WhenHashKeyMethodDoesNotExist_WhenRangeKeyMethodExists() { + idClassWithOnlyRangeKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl( + IdClassWithOnlyAnnotatedRangeKeyMethod.class); } - - - @Test(expected=IllegalArgumentException.class) - public void testConstruct_WhenMultipleHashKeyMethodsExist() - { - idClassWitMultipleAnnotatedHashKeysMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl(IdClassWithMulitpleAnnotatedHashKeyMethods.class); - + + @Test(expected = IllegalArgumentException.class) + public void testConstruct_WhenMultipleHashKeyMethodsExist() { + idClassWitMultipleAnnotatedHashKeysMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl( + IdClassWithMulitpleAnnotatedHashKeyMethods.class); + } - - - @Test(expected=IllegalArgumentException.class) - public void testGetConstruct_WhenMultipleRangeKeyMethodsExist() - { - idClassWitMultipleAnnotatedRangeKeysMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl(IdClassWithMulitpleAnnotatedRangeKeyMethods.class); + @Test(expected = IllegalArgumentException.class) + public void testGetConstruct_WhenMultipleRangeKeyMethodsExist() { + idClassWitMultipleAnnotatedRangeKeysMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl( + IdClassWithMulitpleAnnotatedRangeKeyMethods.class); } - - @Test(expected=IllegalArgumentException.class) - public void testConstruct_WhenNeitherHashKeyOrRangeKeyMethodExist() - { - idClassWithNoHashOrRangeKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl(IdClassWithNoAnnotatedMethods.class); - + + @Test(expected = IllegalArgumentException.class) + public void testConstruct_WhenNeitherHashKeyOrRangeKeyMethodExist() { + idClassWithNoHashOrRangeKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl( + IdClassWithNoAnnotatedMethods.class); + } - - private class IdClassWithNoAnnotatedMethods { - - public String getHashKey(){ return null;} - public String getRangeKey(){ return null;} + + public String getHashKey() { + return null; + } + public String getRangeKey() { + return null; + } } - + private class IdClassWithOnlyAnnotatedHashKeyMethod { - + @DynamoDBHashKey - public String getHashKey(){ return null;} - public String getRangeKey(){ return null;} + public String getHashKey() { + return null; + } + public String getRangeKey() { + return null; + } } - + private class IdClassWithOnlyAnnotatedRangeKeyMethod { - - public String getHashKey(){ return null;} - + + public String getHashKey() { + return null; + } + @DynamoDBRangeKey - public String getRangeKey(){ return null;} + public String getRangeKey() { + return null; + } } - + private class IdClassWithMulitpleAnnotatedHashKeyMethods { - + @DynamoDBHashKey - public String getHashKey(){ return null;} - + public String getHashKey() { + return null; + } + @DynamoDBHashKey - public String getOtherHashKey(){ return null;} - + public String getOtherHashKey() { + return null; + } + @DynamoDBRangeKey - public String getRangeKey(){ return null;} + public String getRangeKey() { + return null; + } } - + private class IdClassWithMulitpleAnnotatedRangeKeyMethods { - + @DynamoDBHashKey - public String getHashKey(){ return null;} - + public String getHashKey() { + return null; + } + @DynamoDBRangeKey - public String getOtherRangeKey(){ return null;} - + public String getOtherRangeKey() { + return null; + } + @DynamoDBRangeKey - public String getRangeKey(){ return null;} + public String getRangeKey() { + return null; + } } - } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformationImplUnitTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformationImplUnitTest.java index 45a7523c..6fa1b11e 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformationImplUnitTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashAndRangeKeyEntityInformationImplUnitTest.java @@ -32,187 +32,172 @@ @RunWith(MockitoJUnitRunner.class) @SuppressWarnings("unused") public class DynamoDBIdIsHashAndRangeKeyEntityInformationImplUnitTest { - - private DynamoDBIdIsHashAndRangeKeyEntityInformationImpl dynamoDBPlaylistEntityInformation; - + + private DynamoDBIdIsHashAndRangeKeyEntityInformationImpl dynamoDBPlaylistEntityInformation; + @Mock - private DynamoDBHashAndRangeKeyExtractingEntityMetadata mockPlaylistEntityMetadata; - + private DynamoDBHashAndRangeKeyExtractingEntityMetadata mockPlaylistEntityMetadata; + @Mock - private DynamoDBHashAndRangeKeyExtractingEntityMetadata mockUserEntityMetadata; + private DynamoDBHashAndRangeKeyExtractingEntityMetadata mockUserEntityMetadata; @Mock private Object mockHashKey; - + @Mock private Object mockRangeKey; - + @SuppressWarnings("rawtypes") @Mock private HashAndRangeKeyExtractor mockHashAndRangeKeyExtractor; - + @Mock private User mockUserPrototype; - + @Mock private Playlist mockPlaylistPrototype; - + @Mock private PlaylistId mockPlaylistId; - + @SuppressWarnings("rawtypes") @Mock private DynamoDBMarshaller mockPropertyMarshaller; - + @SuppressWarnings("unchecked") @Before - public void setup() - { - Mockito.when(mockPlaylistEntityMetadata.getHashAndRangeKeyExtractor(PlaylistId.class)).thenReturn(mockHashAndRangeKeyExtractor); + public void setup() { + Mockito.when(mockPlaylistEntityMetadata.getHashAndRangeKeyExtractor(PlaylistId.class)) + .thenReturn(mockHashAndRangeKeyExtractor); Mockito.when(mockHashAndRangeKeyExtractor.getHashKey(mockPlaylistId)).thenReturn(mockHashKey); Mockito.when(mockHashAndRangeKeyExtractor.getRangeKey(mockPlaylistId)).thenReturn(mockRangeKey); - + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropertyName()).thenReturn("playlistHashKeyPropertyName"); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("somePlaylistHashKey")).thenReturn(mockPlaylistPrototype); - Mockito.when(mockPlaylistEntityMetadata.getMarshallerForProperty("marshalledProperty")).thenReturn(mockPropertyMarshaller); - Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("overriddenProperty")).thenReturn(Optional.of("modifiedPropertyName")); - + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("somePlaylistHashKey")) + .thenReturn(mockPlaylistPrototype); + Mockito.when(mockPlaylistEntityMetadata.getMarshallerForProperty("marshalledProperty")) + .thenReturn(mockPropertyMarshaller); + Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("overriddenProperty")) + .thenReturn(Optional.of("modifiedPropertyName")); + Mockito.when(mockPlaylistEntityMetadata.isHashKeyProperty("nonHashKeyProperty")).thenReturn(false); - Mockito.when(mockPlaylistEntityMetadata.isCompositeHashAndRangeKeyProperty("compositeIdProperty")).thenReturn(true); - Mockito.when(mockPlaylistEntityMetadata.isCompositeHashAndRangeKeyProperty("nonCompositeIdProperty")).thenReturn(false); - - dynamoDBPlaylistEntityInformation = new DynamoDBIdIsHashAndRangeKeyEntityInformationImpl<>(Playlist.class,mockPlaylistEntityMetadata); + Mockito.when(mockPlaylistEntityMetadata.isCompositeHashAndRangeKeyProperty("compositeIdProperty")) + .thenReturn(true); + Mockito.when(mockPlaylistEntityMetadata.isCompositeHashAndRangeKeyProperty("nonCompositeIdProperty")) + .thenReturn(false); + + dynamoDBPlaylistEntityInformation = new DynamoDBIdIsHashAndRangeKeyEntityInformationImpl<>(Playlist.class, + mockPlaylistEntityMetadata); } - - @Test(expected=IllegalArgumentException.class) - public void testConstruct_WhenEntityDoesNotHaveFieldAnnotatedWithId_ThrowsIllegalArgumentException() - { - DynamoDBIdIsHashAndRangeKeyEntityInformationImpl dynamoDBUserEntityInformation = new DynamoDBIdIsHashAndRangeKeyEntityInformationImpl(User.class,mockUserEntityMetadata); + + @Test(expected = IllegalArgumentException.class) + public void testConstruct_WhenEntityDoesNotHaveFieldAnnotatedWithId_ThrowsIllegalArgumentException() { + DynamoDBIdIsHashAndRangeKeyEntityInformationImpl dynamoDBUserEntityInformation = new DynamoDBIdIsHashAndRangeKeyEntityInformationImpl( + User.class, mockUserEntityMetadata); } - - + @Test - public void testGetId_WhenHashKeyMethodSameAsIdType_InvokesHashKeyMethod_AndReturnedIdIsAssignableToIdType_AndIsValueExpected() - { + public void testGetId_WhenHashKeyMethodSameAsIdType_InvokesHashKeyMethod_AndReturnedIdIsAssignableToIdType_AndIsValueExpected() { Playlist playlist = new Playlist(); playlist.setUserName("someUserName"); playlist.setPlaylistName("somePlaylistName"); PlaylistId id = dynamoDBPlaylistEntityInformation.getId(playlist); Assert.assertEquals("someUserName", id.getUserName()); - Assert.assertEquals("somePlaylistName",id.getPlaylistName()); + Assert.assertEquals("somePlaylistName", id.getPlaylistName()); } - - - + @Test - public void testGetJavaType_WhenEntityIsInstanceWithHashAndRangeKey_ReturnsEntityClass() - { - Assert.assertEquals(Playlist.class,dynamoDBPlaylistEntityInformation.getJavaType()); + public void testGetJavaType_WhenEntityIsInstanceWithHashAndRangeKey_ReturnsEntityClass() { + Assert.assertEquals(Playlist.class, dynamoDBPlaylistEntityInformation.getJavaType()); } - - + @Test - public void testGetIdType_WhenEntityIsInstanceWithHashAndRangeKey_ReturnsReturnTypeOfIdMethod() - { - Assert.assertEquals(PlaylistId.class,dynamoDBPlaylistEntityInformation.getIdType()); + public void testGetIdType_WhenEntityIsInstanceWithHashAndRangeKey_ReturnsReturnTypeOfIdMethod() { + Assert.assertEquals(PlaylistId.class, dynamoDBPlaylistEntityInformation.getIdType()); } - - - - // The following tests ensure that invarient methods such as those always retuning constants, or - // that delegate to metadata, behave the same irrespective of the setup of the EntityInformation + + // The following tests ensure that invarient methods such as those always + // retuning constants, or + // that delegate to metadata, behave the same irrespective of the setup of the + // EntityInformation @Test - public void testIsRangeKeyAware_ReturnsTrue() - { - Assert.assertTrue(dynamoDBPlaylistEntityInformation.isRangeKeyAware()); + public void testIsRangeKeyAware_ReturnsTrue() { + Assert.assertTrue(dynamoDBPlaylistEntityInformation.isRangeKeyAware()); } - - + @Test - public void testGetHashKeyGivenId_WhenIdMethodFoundOnEntity_DelegatesToHashAndRangeKeyExtractorWithGivenIdValue() - { - Object hashKey = dynamoDBPlaylistEntityInformation.getHashKey(mockPlaylistId); + public void testGetHashKeyGivenId_WhenIdMethodFoundOnEntity_DelegatesToHashAndRangeKeyExtractorWithGivenIdValue() { + Object hashKey = dynamoDBPlaylistEntityInformation.getHashKey(mockPlaylistId); Assert.assertNotNull(hashKey); - Assert.assertEquals(mockHashKey,hashKey); + Assert.assertEquals(mockHashKey, hashKey); } - @Test - public void testGetRangeKeyGivenId_WhenIdMethodFoundOnEntity_DelegatesToHashAndRangeKeyExtractorWithGivenIdValue() - { - Object rangeKey = dynamoDBPlaylistEntityInformation.getRangeKey(mockPlaylistId); + public void testGetRangeKeyGivenId_WhenIdMethodFoundOnEntity_DelegatesToHashAndRangeKeyExtractorWithGivenIdValue() { + Object rangeKey = dynamoDBPlaylistEntityInformation.getRangeKey(mockPlaylistId); Assert.assertNotNull(rangeKey); - Assert.assertEquals(mockRangeKey,rangeKey); + Assert.assertEquals(mockRangeKey, rangeKey); } - - + @Test - public void testGetPrototypeEntityForHashKey_DelegatesToDynamoDBEntityMetadata_IrrespectiveOfEntityInformationSetup() - { + public void testGetPrototypeEntityForHashKey_DelegatesToDynamoDBEntityMetadata_IrrespectiveOfEntityInformationSetup() { Playlist playlistPrototypeEntity = new Playlist(); - Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someHashKey")).thenReturn(playlistPrototypeEntity); - - Object returnedPlaylistEntity = dynamoDBPlaylistEntityInformation.getHashKeyPropotypeEntityForHashKey("someHashKey"); - + Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropotypeEntityForHashKey("someHashKey")) + .thenReturn(playlistPrototypeEntity); + + Object returnedPlaylistEntity = dynamoDBPlaylistEntityInformation + .getHashKeyPropotypeEntityForHashKey("someHashKey"); + Assert.assertEquals(playlistPrototypeEntity, returnedPlaylistEntity); Mockito.verify(mockPlaylistEntityMetadata).getHashKeyPropotypeEntityForHashKey("someHashKey"); - + } - @Test - public void testGetHashKeyPropertyName_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() - { + public void testGetHashKeyPropertyName_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() { Assert.assertEquals("playlistHashKeyPropertyName", dynamoDBPlaylistEntityInformation.getHashKeyPropertyName()); } - + @Test - public void testGetHashKeyPrototypeEntityForHashKey_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() - { + public void testGetHashKeyPrototypeEntityForHashKey_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() { - - Object hashKeyPrototype2 = dynamoDBPlaylistEntityInformation.getHashKeyPropotypeEntityForHashKey("somePlaylistHashKey"); + Object hashKeyPrototype2 = dynamoDBPlaylistEntityInformation + .getHashKeyPropotypeEntityForHashKey("somePlaylistHashKey"); Assert.assertEquals(mockPlaylistPrototype, hashKeyPrototype2); } - @Test - public void testGetMarshallerForProperty_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() - { - DynamoDBMarshaller marshaller1 = dynamoDBPlaylistEntityInformation.getMarshallerForProperty("marshalledProperty"); + public void testGetMarshallerForProperty_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() { + DynamoDBMarshaller marshaller1 = dynamoDBPlaylistEntityInformation + .getMarshallerForProperty("marshalledProperty"); Assert.assertEquals(mockPropertyMarshaller, marshaller1); } - + @Test - public void testGetOverriddenAttributeName_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() - { + public void testGetOverriddenAttributeName_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() { - - Optional propertyName2 = dynamoDBPlaylistEntityInformation.getOverriddenAttributeName("overriddenProperty"); + Optional propertyName2 = dynamoDBPlaylistEntityInformation + .getOverriddenAttributeName("overriddenProperty"); Assert.assertEquals(Optional.of("modifiedPropertyName"), propertyName2); } - + @Test - public void testGetIsHashKeyProperty_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() - { + public void testGetIsHashKeyProperty_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() { Assert.assertFalse(dynamoDBPlaylistEntityInformation.isHashKeyProperty("nonHashKeyProperty")); Assert.assertFalse(dynamoDBPlaylistEntityInformation.isHashKeyProperty("nonHashKeyProperty")); } - + @Test - public void testGetIsCompositeIdProperty_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() - { - + public void testGetIsCompositeIdProperty_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() { + Assert.assertTrue(dynamoDBPlaylistEntityInformation.isCompositeHashAndRangeKeyProperty("compositeIdProperty")); - Assert.assertFalse(dynamoDBPlaylistEntityInformation.isCompositeHashAndRangeKeyProperty("nonCompositeIdProperty")); + Assert.assertFalse( + dynamoDBPlaylistEntityInformation.isCompositeHashAndRangeKeyProperty("nonCompositeIdProperty")); } - - - } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashKeyEntityInformationImplUnitTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashKeyEntityInformationImplUnitTest.java index 9688b7d3..d10252f2 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashKeyEntityInformationImplUnitTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBIdIsHashKeyEntityInformationImplUnitTest.java @@ -32,181 +32,174 @@ @RunWith(MockitoJUnitRunner.class) @SuppressWarnings("unused") public class DynamoDBIdIsHashKeyEntityInformationImplUnitTest { - - private DynamoDBIdIsHashKeyEntityInformationImpl dynamoDBPlaylistEntityInformation; - - private DynamoDBIdIsHashKeyEntityInformationImpl dynamoDBUserEntityInformation; - + + private DynamoDBIdIsHashKeyEntityInformationImpl dynamoDBPlaylistEntityInformation; + + private DynamoDBIdIsHashKeyEntityInformationImpl dynamoDBUserEntityInformation; + @Mock - private DynamoDBHashAndRangeKeyExtractingEntityMetadata mockPlaylistEntityMetadata; - + private DynamoDBHashAndRangeKeyExtractingEntityMetadata mockPlaylistEntityMetadata; + @Mock private DynamoDBHashKeyExtractingEntityMetadata mockUserEntityMetadata; @Mock private Object mockHashKey; - + @Mock private User mockUserPrototype; - + @Mock private Playlist mockPlaylistPrototype; - + @SuppressWarnings("rawtypes") @Mock private DynamoDBMarshaller mockPropertyMarshaller; - + @SuppressWarnings("unchecked") @Before - public void setup() - { + public void setup() { Mockito.when(mockUserEntityMetadata.getHashKeyPropertyName()).thenReturn("userHashKeyPropertyName"); Mockito.when(mockPlaylistEntityMetadata.getHashKeyPropertyName()).thenReturn("playlistHashKeyPropertyName"); - Mockito.when(mockUserEntityMetadata.getMarshallerForProperty("marshalledProperty")).thenReturn(mockPropertyMarshaller); - Mockito.when(mockPlaylistEntityMetadata.getMarshallerForProperty("marshalledProperty")).thenReturn(mockPropertyMarshaller); - Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("overriddenProperty")).thenReturn(Optional.of("modifiedPropertyName")); - Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("overriddenProperty")).thenReturn(Optional.of("modifiedPropertyName")); + Mockito.when(mockUserEntityMetadata.getMarshallerForProperty("marshalledProperty")) + .thenReturn(mockPropertyMarshaller); + Mockito.when(mockPlaylistEntityMetadata.getMarshallerForProperty("marshalledProperty")) + .thenReturn(mockPropertyMarshaller); + Mockito.when(mockUserEntityMetadata.getOverriddenAttributeName("overriddenProperty")) + .thenReturn(Optional.of("modifiedPropertyName")); + Mockito.when(mockPlaylistEntityMetadata.getOverriddenAttributeName("overriddenProperty")) + .thenReturn(Optional.of("modifiedPropertyName")); Mockito.when(mockUserEntityMetadata.isHashKeyProperty("hashKeyProperty")).thenReturn(true); Mockito.when(mockPlaylistEntityMetadata.isHashKeyProperty("nonHashKeyProperty")).thenReturn(false); - dynamoDBPlaylistEntityInformation = new DynamoDBIdIsHashKeyEntityInformationImpl<>(Playlist.class,mockPlaylistEntityMetadata); - dynamoDBUserEntityInformation = new DynamoDBIdIsHashKeyEntityInformationImpl<>(User.class,mockUserEntityMetadata); + dynamoDBPlaylistEntityInformation = new DynamoDBIdIsHashKeyEntityInformationImpl<>(Playlist.class, + mockPlaylistEntityMetadata); + dynamoDBUserEntityInformation = new DynamoDBIdIsHashKeyEntityInformationImpl<>(User.class, + mockUserEntityMetadata); } - + @Test - public void testGetId_WhenHashKeyTypeSameAsIdType_InvokesHashKeyMethod_AndReturnedIdIsAssignableToIdType_AndIsValueExpected() - { + public void testGetId_WhenHashKeyTypeSameAsIdType_InvokesHashKeyMethod_AndReturnedIdIsAssignableToIdType_AndIsValueExpected() { User user = new User(); user.setId("someUserId"); String id = dynamoDBUserEntityInformation.getId(user); Assert.assertEquals("someUserId", id); } - - @Test(expected=ClassCastException.class) - public void testGetId_WhenHashKeyMethodNotSameAsIdType_InvokesHashKeyMethod_AndReturnedIdIsNotAssignableToIdType() - { + + @Test(expected = ClassCastException.class) + public void testGetId_WhenHashKeyMethodNotSameAsIdType_InvokesHashKeyMethod_AndReturnedIdIsNotAssignableToIdType() { Playlist playlist = new Playlist(); playlist.setUserName("someUserName"); playlist.setPlaylistName("somePlaylistName"); PlaylistId id = dynamoDBPlaylistEntityInformation.getId(playlist); } - + @Test - public void testGetHashKeyGivenId_WhenHashKeyTypeSameAsIdType_ReturnsId() - { - Object hashKey = dynamoDBUserEntityInformation.getHashKey("someUserId"); + public void testGetHashKeyGivenId_WhenHashKeyTypeSameAsIdType_ReturnsId() { + Object hashKey = dynamoDBUserEntityInformation.getHashKey("someUserId"); Assert.assertNotNull(hashKey); - Assert.assertEquals("someUserId",hashKey); + Assert.assertEquals("someUserId", hashKey); } - - @Test(expected=IllegalArgumentException.class) - public void testGetHashKeyGivenId_WhenHashKeyTypeNotSameAsIdType_ThrowsIllegalArgumentException() - { + + @Test(expected = IllegalArgumentException.class) + public void testGetHashKeyGivenId_WhenHashKeyTypeNotSameAsIdType_ThrowsIllegalArgumentException() { PlaylistId id = new PlaylistId(); - Object hashKey = dynamoDBPlaylistEntityInformation.getHashKey(id); + Object hashKey = dynamoDBPlaylistEntityInformation.getHashKey(id); Assert.assertNotNull(hashKey); - Assert.assertEquals(id,hashKey); + Assert.assertEquals(id, hashKey); } - + @Test - public void testGetJavaType_WhenEntityIsInstanceWithHashAndRangeKey_ReturnsEntityClass() - { - Assert.assertEquals(Playlist.class,dynamoDBPlaylistEntityInformation.getJavaType()); + public void testGetJavaType_WhenEntityIsInstanceWithHashAndRangeKey_ReturnsEntityClass() { + Assert.assertEquals(Playlist.class, dynamoDBPlaylistEntityInformation.getJavaType()); } - + @Test - public void testGetJavaType_WhenEntityIsInstanceWithHashKeyOnly_ReturnsEntityClass() - { - Assert.assertEquals(User.class,dynamoDBUserEntityInformation.getJavaType()); + public void testGetJavaType_WhenEntityIsInstanceWithHashKeyOnly_ReturnsEntityClass() { + Assert.assertEquals(User.class, dynamoDBUserEntityInformation.getJavaType()); } - + @Test - public void testGetIdType_WhenEntityIsInstanceWithHashAndRangeKey_ReturnsReturnTypeOfHashKeyMethod() - { - Assert.assertEquals(String.class,dynamoDBPlaylistEntityInformation.getIdType()); + public void testGetIdType_WhenEntityIsInstanceWithHashAndRangeKey_ReturnsReturnTypeOfHashKeyMethod() { + Assert.assertEquals(String.class, dynamoDBPlaylistEntityInformation.getIdType()); } - + @Test - public void testGetIdType_WhenEntityIsInstanceWithHashKeyOnly_ReturnsReturnTypeOfHashKeyMethod() - { - Assert.assertEquals(String.class,dynamoDBUserEntityInformation.getIdType()); - } - - - // The following tests ensure that invarient methods such as those always retuning constants, or - // that delegate to metadata, behave the same irrespective of the setup of the EntityInformation - - + public void testGetIdType_WhenEntityIsInstanceWithHashKeyOnly_ReturnsReturnTypeOfHashKeyMethod() { + Assert.assertEquals(String.class, dynamoDBUserEntityInformation.getIdType()); + } + + // The following tests ensure that invarient methods such as those always + // retuning constants, or + // that delegate to metadata, behave the same irrespective of the setup of the + // EntityInformation + @Test - public void testGetRangeKey_ReturnsNull_IrrespectiveOfEntityInformationSetup() - { - Object userRangeKey = dynamoDBUserEntityInformation.getRangeKey("someUserId"); + public void testGetRangeKey_ReturnsNull_IrrespectiveOfEntityInformationSetup() { + Object userRangeKey = dynamoDBUserEntityInformation.getRangeKey("someUserId"); Assert.assertNull(userRangeKey); - - Object playlistRangeKey = dynamoDBPlaylistEntityInformation.getRangeKey(new PlaylistId()); + + Object playlistRangeKey = dynamoDBPlaylistEntityInformation.getRangeKey(new PlaylistId()); Assert.assertNull(playlistRangeKey); } - + @Test - public void testIsRangeKeyAware_ReturnsFalse_IrrespectiveOfEntityInformationSetup() - { - Assert.assertFalse(dynamoDBUserEntityInformation.isRangeKeyAware()); - - Assert.assertFalse(dynamoDBPlaylistEntityInformation.isRangeKeyAware()); - } - - + public void testIsRangeKeyAware_ReturnsFalse_IrrespectiveOfEntityInformationSetup() { + Assert.assertFalse(dynamoDBUserEntityInformation.isRangeKeyAware()); + + Assert.assertFalse(dynamoDBPlaylistEntityInformation.isRangeKeyAware()); + } + @Test - public void testGetHashKeyPropertyName_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() - { + public void testGetHashKeyPropertyName_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() { Assert.assertEquals("userHashKeyPropertyName", dynamoDBUserEntityInformation.getHashKeyPropertyName()); Assert.assertEquals("playlistHashKeyPropertyName", dynamoDBPlaylistEntityInformation.getHashKeyPropertyName()); } @Test - public void testGetMarshallerForProperty_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() - { - DynamoDBMarshaller marshaller1 = dynamoDBPlaylistEntityInformation.getMarshallerForProperty("marshalledProperty"); + public void testGetMarshallerForProperty_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() { + DynamoDBMarshaller marshaller1 = dynamoDBPlaylistEntityInformation + .getMarshallerForProperty("marshalledProperty"); Assert.assertEquals(mockPropertyMarshaller, marshaller1); - - DynamoDBMarshaller marshaller2 = dynamoDBUserEntityInformation.getMarshallerForProperty("marshalledProperty"); + + DynamoDBMarshaller marshaller2 = dynamoDBUserEntityInformation + .getMarshallerForProperty("marshalledProperty"); Assert.assertEquals(mockPropertyMarshaller, marshaller2); } - + @Test - public void testGetIsHashKeyProperty_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() - { + public void testGetIsHashKeyProperty_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() { Assert.assertTrue(dynamoDBUserEntityInformation.isHashKeyProperty("hashKeyProperty")); Assert.assertTrue(dynamoDBUserEntityInformation.isHashKeyProperty("hashKeyProperty")); - + Assert.assertFalse(dynamoDBPlaylistEntityInformation.isHashKeyProperty("nonHashKeyProperty")); Assert.assertFalse(dynamoDBPlaylistEntityInformation.isHashKeyProperty("nonHashKeyProperty")); } - + @Test - public void testGetIsCompositeIdProperty_ReturnsFalse_IrrespectiveOfEntityInformationSetup() - { + public void testGetIsCompositeIdProperty_ReturnsFalse_IrrespectiveOfEntityInformationSetup() { Assert.assertFalse(dynamoDBUserEntityInformation.isCompositeHashAndRangeKeyProperty("compositeIdProperty")); Assert.assertFalse(dynamoDBUserEntityInformation.isCompositeHashAndRangeKeyProperty("compositeIdProperty")); - - Assert.assertFalse(dynamoDBPlaylistEntityInformation.isCompositeHashAndRangeKeyProperty("nonCompositeIdProperty")); - Assert.assertFalse(dynamoDBPlaylistEntityInformation.isCompositeHashAndRangeKeyProperty("nonCompositeIdProperty")); + + Assert.assertFalse( + dynamoDBPlaylistEntityInformation.isCompositeHashAndRangeKeyProperty("nonCompositeIdProperty")); + Assert.assertFalse( + dynamoDBPlaylistEntityInformation.isCompositeHashAndRangeKeyProperty("nonCompositeIdProperty")); } - + @Test - public void testGetOverriddenAttributeName_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() - { - Optional propertyName1 = dynamoDBUserEntityInformation.getOverriddenAttributeName("overriddenProperty"); + public void testGetOverriddenAttributeName_DelegatesToEntityMetadata_IrrespectiveOfEntityInformationSetup() { + Optional propertyName1 = dynamoDBUserEntityInformation.getOverriddenAttributeName("overriddenProperty"); Assert.assertEquals(Optional.of("modifiedPropertyName"), propertyName1); - Optional propertyName2 = dynamoDBPlaylistEntityInformation.getOverriddenAttributeName("overriddenProperty"); + Optional propertyName2 = dynamoDBPlaylistEntityInformation + .getOverriddenAttributeName("overriddenProperty"); Assert.assertEquals(Optional.of("modifiedPropertyName"), propertyName2); } - } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryBeanTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryBeanTest.java index df5461ff..41f71f6e 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryBeanTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryBeanTest.java @@ -35,56 +35,56 @@ @RunWith(MockitoJUnitRunner.class) public class DynamoDBRepositoryFactoryBeanTest { - @Mock - private ApplicationContext applicationContext; - @Mock - private DynamoDBOperations dynamoDBOperations; - @Mock - private DynamoDBMapperConfig dynamoDBMapperConfig; - @Mock - private AmazonDynamoDB amazonDynamoDB; + @Mock + private ApplicationContext applicationContext; + @Mock + private DynamoDBOperations dynamoDBOperations; + @Mock + private DynamoDBMapperConfig dynamoDBMapperConfig; + @Mock + private AmazonDynamoDB amazonDynamoDB; - private DynamoDBRepositoryFactoryBean underTest; + private DynamoDBRepositoryFactoryBean underTest; - public interface UserRepository extends Repository { + public interface UserRepository extends Repository { - } + } - @Before - public void setUp() { - underTest = spy(new DynamoDBRepositoryFactoryBean(UserRepository.class)); - underTest.setApplicationContext(applicationContext); - underTest.setDynamoDBMapperConfig(dynamoDBMapperConfig); - } + @Before + public void setUp() { + underTest = spy(new DynamoDBRepositoryFactoryBean(UserRepository.class)); + underTest.setApplicationContext(applicationContext); + underTest.setDynamoDBMapperConfig(dynamoDBMapperConfig); + } - @Test - public void testDynamoDBOperations() { - try { - underTest.getPersistentEntity(); - fail(); - } catch (NullPointerException /*IllegalStateException*/ ise) { - assertTrue(true); - } + @Test + public void testDynamoDBOperations() { + try { + underTest.getPersistentEntity(); + fail(); + } catch (NullPointerException /* IllegalStateException */ ise) { + assertTrue(true); + } - underTest.setDynamoDBOperations(dynamoDBOperations); - underTest.afterPropertiesSet(); + underTest.setDynamoDBOperations(dynamoDBOperations); + underTest.afterPropertiesSet(); - assertNotNull(underTest.getPersistentEntity()); - } + assertNotNull(underTest.getPersistentEntity()); + } - @Test - public void testAmazonDynamoDB() { - try { - underTest.getPersistentEntity(); - fail(); - } catch (NullPointerException /*IllegalStateException*/ ise) { - assertTrue(true); - } + @Test + public void testAmazonDynamoDB() { + try { + underTest.getPersistentEntity(); + fail(); + } catch (NullPointerException /* IllegalStateException */ ise) { + assertTrue(true); + } - underTest.setAmazonDynamoDB(amazonDynamoDB); - underTest.afterPropertiesSet(); + underTest.setAmazonDynamoDB(amazonDynamoDB); + underTest.afterPropertiesSet(); + + assertNotNull(underTest.getPersistentEntity()); + } - assertNotNull(underTest.getPersistentEntity()); - } - } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryTest.java index 3dba6786..184e1ad3 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBRepositoryFactoryTest.java @@ -22,26 +22,26 @@ public class DynamoDBRepositoryFactoryTest { - @Test - public void testVersionNullNull() { - assertFalse(DynamoDBRepositoryFactory.isCompatible(null, null)); - } - - @Test - public void testVersionNullValue() { - assertFalse(DynamoDBRepositoryFactory.isCompatible(null, "1.0.")); - assertFalse(DynamoDBRepositoryFactory.isCompatible("1.0", null)); - } - - @Test - public void testVersionCompatible() { - assertTrue(DynamoDBRepositoryFactory.isCompatible("1.0", "1.0")); - assertTrue(DynamoDBRepositoryFactory.isCompatible("1.0.0.0.1", "1.0..0.0.1")); - - assertFalse(DynamoDBRepositoryFactory.isCompatible("1.1", "1.0")); - assertFalse(DynamoDBRepositoryFactory.isCompatible("1.0", "2.0")); - - assertTrue(DynamoDBRepositoryFactory.isCompatible("1.0.0-SR", "1.0.0-SR")); - } + @Test + public void testVersionNullNull() { + assertFalse(DynamoDBRepositoryFactory.isCompatible(null, null)); + } + + @Test + public void testVersionNullValue() { + assertFalse(DynamoDBRepositoryFactory.isCompatible(null, "1.0.")); + assertFalse(DynamoDBRepositoryFactory.isCompatible("1.0", null)); + } + + @Test + public void testVersionCompatible() { + assertTrue(DynamoDBRepositoryFactory.isCompatible("1.0", "1.0")); + assertTrue(DynamoDBRepositoryFactory.isCompatible("1.0.0.0.1", "1.0..0.0.1")); + + assertFalse(DynamoDBRepositoryFactory.isCompatible("1.1", "1.0")); + assertFalse(DynamoDBRepositoryFactory.isCompatible("1.0", "2.0")); + + assertTrue(DynamoDBRepositoryFactory.isCompatible("1.0.0-SR", "1.0.0-SR")); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanAnnotationPermissionTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanAnnotationPermissionTest.java index f1baee73..acb045b9 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanAnnotationPermissionTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/EnableScanAnnotationPermissionTest.java @@ -30,71 +30,70 @@ public class EnableScanAnnotationPermissionTest { - @EnableScan - public interface SampleRepository { - List findAll(); - } - - public interface SampleNoScanRepository { - List findAll(); - } - - @EnableScanCount - public interface SampleMethodRepository { - - @EnableScan - int someMethodThatsIgnored(); - - @EnableScan - int count(); - - @EnableScan - void deleteAll(); - - @EnableScan - List findAll(); - @EnableScan - Page findAll(Pageable pageable); - - } - - - @Before - public void setUp() { - - } - - @Test - public void testSampleRepository() { - EnableScanAnnotationPermissions underTest = new EnableScanAnnotationPermissions(SampleRepository.class); - - assertTrue(underTest.isCountUnpaginatedScanEnabled()); - assertTrue(underTest.isDeleteAllUnpaginatedScanEnabled()); - assertTrue(underTest.isFindAllPaginatedScanEnabled()); - assertFalse(underTest.isFindAllUnpaginatedScanCountEnabled()); - assertTrue(underTest.isFindAllUnpaginatedScanEnabled()); - } - - @Test - public void testSampleNoScanRepository() { - EnableScanAnnotationPermissions underTest = new EnableScanAnnotationPermissions(SampleMethodRepository.class); - - assertTrue(underTest.isCountUnpaginatedScanEnabled()); - assertTrue(underTest.isDeleteAllUnpaginatedScanEnabled()); - assertTrue(underTest.isFindAllPaginatedScanEnabled()); - assertTrue(underTest.isFindAllUnpaginatedScanCountEnabled()); - assertTrue(underTest.isFindAllUnpaginatedScanEnabled()); - } - - @Test - public void testSampleMethodRepository() { - EnableScanAnnotationPermissions underTest = new EnableScanAnnotationPermissions(SampleNoScanRepository.class); - - assertFalse(underTest.isCountUnpaginatedScanEnabled()); - assertFalse(underTest.isDeleteAllUnpaginatedScanEnabled()); - assertFalse(underTest.isFindAllPaginatedScanEnabled()); - assertFalse(underTest.isFindAllUnpaginatedScanCountEnabled()); - assertFalse(underTest.isFindAllUnpaginatedScanEnabled()); - } + @EnableScan + public interface SampleRepository { + List findAll(); + } + + public interface SampleNoScanRepository { + List findAll(); + } + + @EnableScanCount + public interface SampleMethodRepository { + + @EnableScan + int someMethodThatsIgnored(); + + @EnableScan + int count(); + + @EnableScan + void deleteAll(); + + @EnableScan + List findAll(); + @EnableScan + Page findAll(Pageable pageable); + + } + + @Before + public void setUp() { + + } + + @Test + public void testSampleRepository() { + EnableScanAnnotationPermissions underTest = new EnableScanAnnotationPermissions(SampleRepository.class); + + assertTrue(underTest.isCountUnpaginatedScanEnabled()); + assertTrue(underTest.isDeleteAllUnpaginatedScanEnabled()); + assertTrue(underTest.isFindAllPaginatedScanEnabled()); + assertFalse(underTest.isFindAllUnpaginatedScanCountEnabled()); + assertTrue(underTest.isFindAllUnpaginatedScanEnabled()); + } + + @Test + public void testSampleNoScanRepository() { + EnableScanAnnotationPermissions underTest = new EnableScanAnnotationPermissions(SampleMethodRepository.class); + + assertTrue(underTest.isCountUnpaginatedScanEnabled()); + assertTrue(underTest.isDeleteAllUnpaginatedScanEnabled()); + assertTrue(underTest.isFindAllPaginatedScanEnabled()); + assertTrue(underTest.isFindAllUnpaginatedScanCountEnabled()); + assertTrue(underTest.isFindAllUnpaginatedScanEnabled()); + } + + @Test + public void testSampleMethodRepository() { + EnableScanAnnotationPermissions underTest = new EnableScanAnnotationPermissions(SampleNoScanRepository.class); + + assertFalse(underTest.isCountUnpaginatedScanEnabled()); + assertFalse(underTest.isDeleteAllUnpaginatedScanEnabled()); + assertFalse(underTest.isFindAllPaginatedScanEnabled()); + assertFalse(underTest.isFindAllUnpaginatedScanCountEnabled()); + assertFalse(underTest.isFindAllUnpaginatedScanEnabled()); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBCrudRepositoryTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBCrudRepositoryTest.java index f55b991e..4c507a47 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBCrudRepositoryTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBCrudRepositoryTest.java @@ -50,7 +50,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; - /** * Unit tests for {@link DynamoDBSimpleIdRepository}. * @@ -80,7 +79,6 @@ public class SimpleDynamoDBCrudRepositoryTest { private SimpleDynamoDBCrudRepository repoForEntityWithOnlyHashKey; private SimpleDynamoDBCrudRepository repoForEntityWithHashAndRangeKey; - @Before public void setUp() { @@ -94,7 +92,7 @@ public void setUp() { when(entityWithSimpleIdInformation.getJavaType()).thenReturn(User.class); when(entityWithSimpleIdInformation.getHashKey(1l)).thenReturn(1l); - + when(mockEnableScanPermissions.isFindAllUnpaginatedScanEnabled()).thenReturn(true); when(mockEnableScanPermissions.isDeleteAllUnpaginatedScanEnabled()).thenReturn(true); when(mockEnableScanPermissions.isCountUnpaginatedScanEnabled()).thenReturn(true); @@ -105,9 +103,9 @@ public void setUp() { when(entityWithCompositeIdInformation.isRangeKeyAware()).thenReturn(true); repoForEntityWithOnlyHashKey = new SimpleDynamoDBCrudRepository<>(entityWithSimpleIdInformation, - dynamoDBOperations,mockEnableScanPermissions); - repoForEntityWithHashAndRangeKey = new SimpleDynamoDBCrudRepository<>( - entityWithCompositeIdInformation, dynamoDBOperations,mockEnableScanPermissions); + dynamoDBOperations, mockEnableScanPermissions); + repoForEntityWithHashAndRangeKey = new SimpleDynamoDBCrudRepository<>(entityWithCompositeIdInformation, + dynamoDBOperations, mockEnableScanPermissions); when(dynamoDBOperations.load(User.class, 1l)).thenReturn(testUser); when(dynamoDBOperations.load(Playlist.class, "michael", "playlist1")).thenReturn(testPlaylist); @@ -146,8 +144,7 @@ public void deleteIterable() { @Test public void deleteAll() { - when(dynamoDBOperations.scan(eq(User.class), any(DynamoDBScanExpression.class))) - .thenReturn(findAllResultMock); + when(dynamoDBOperations.scan(eq(User.class), any(DynamoDBScanExpression.class))).thenReturn(findAllResultMock); repoForEntityWithOnlyHashKey.deleteAll(); verify(dynamoDBOperations).batchDelete(findAllResultMock); @@ -155,8 +152,7 @@ public void deleteAll() { @Test public void testFindAll() { - when(dynamoDBOperations.scan(eq(User.class), any(DynamoDBScanExpression.class))) - .thenReturn(findAllResultMock); + when(dynamoDBOperations.scan(eq(User.class), any(DynamoDBScanExpression.class))).thenReturn(findAllResultMock); List actual = repoForEntityWithOnlyHashKey.findAll(); @@ -164,7 +160,8 @@ public void testFindAll() { } /** - /** + * /** + * * @see DATAJPA-177 */ @Test(expected = EmptyResultDataAccessException.class) @@ -205,7 +202,7 @@ public void testCount() { @Test public void findOneEntityWithOnlyHashKey() { Optional user = repoForEntityWithOnlyHashKey.findById(1l); - Mockito.verify(dynamoDBOperations).load(User.class,1l); + Mockito.verify(dynamoDBOperations).load(User.class, 1l); assertEquals(testUser, user.get()); } @@ -268,7 +265,8 @@ public void testBatchSaveFailure() { when(dynamoDBOperations.batchSave(anyIterable())).thenReturn(failures); expectedException.expect(BatchWriteException.class); - expectedException.expectMessage("Saving of entities failed!; nested exception is java.lang.Exception: First exception"); + expectedException + .expectMessage("Saving of entities failed!; nested exception is java.lang.Exception: First exception"); repoForEntityWithOnlyHashKey.saveAll(entities); } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBPagingAndSortingRepositoryUnitTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBPagingAndSortingRepositoryUnitTest.java index c0bad90e..3cb7415d 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBPagingAndSortingRepositoryUnitTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/SimpleDynamoDBPagingAndSortingRepositoryUnitTest.java @@ -53,7 +53,7 @@ public class SimpleDynamoDBPagingAndSortingRepositoryUnitTest { private Playlist testPlaylist; private PlaylistId testPlaylistId; - + @Mock EnableScanPermissions mockEnableScanPermissions; @@ -76,17 +76,16 @@ public void setUp() { when(entityWithOnlyHashKeyInformation.getJavaType()).thenReturn(User.class); when(entityWithOnlyHashKeyInformation.getHashKey(1l)).thenReturn(1l); - - + when(entityWithHashAndRangeKeyInformation.getJavaType()).thenReturn(Playlist.class); when(entityWithHashAndRangeKeyInformation.getHashKey(testPlaylistId)).thenReturn("michael"); when(entityWithHashAndRangeKeyInformation.getRangeKey(testPlaylistId)).thenReturn("playlist1"); when(entityWithHashAndRangeKeyInformation.isRangeKeyAware()).thenReturn(true); repoForEntityWithOnlyHashKey = new SimpleDynamoDBPagingAndSortingRepository<>(entityWithOnlyHashKeyInformation, - dynamoDBOperations,mockEnableScanPermissions); + dynamoDBOperations, mockEnableScanPermissions); repoForEntityWithHashAndRangeKey = new SimpleDynamoDBPagingAndSortingRepository<>( - entityWithHashAndRangeKeyInformation, dynamoDBOperations,mockEnableScanPermissions); + entityWithHashAndRangeKeyInformation, dynamoDBOperations, mockEnableScanPermissions); when(dynamoDBOperations.load(User.class, 1l)).thenReturn(testUser); when(dynamoDBOperations.load(Playlist.class, "michael", "playlist1")).thenReturn(testPlaylist); @@ -105,10 +104,9 @@ public void throwsExceptionIfEntityWithOnlyHashKeyToDeleteDoesNotExist() { @Test public void findOneEntityWithOnlyHashKey() { Optional user = repoForEntityWithOnlyHashKey.findById(1l); - Mockito.verify(dynamoDBOperations).load(User.class,1l); + Mockito.verify(dynamoDBOperations).load(User.class, 1l); assertEquals(testUser, user.get()); } - @Test public void findOneEntityWithHashAndRangeKey() { diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/utils/DynamoDBLocalResource.java b/src/test/java/org/socialsignin/spring/data/dynamodb/utils/DynamoDBLocalResource.java index 99f6f85b..11d4d0c3 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/utils/DynamoDBLocalResource.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/utils/DynamoDBLocalResource.java @@ -24,9 +24,9 @@ @Configuration public class DynamoDBLocalResource implements TestExecutionListener { - @Bean - public AmazonDynamoDB amazonDynamoDB() { - return DynamoDBEmbedded.create().amazonDynamoDB(); - } + @Bean + public AmazonDynamoDB amazonDynamoDB() { + return DynamoDBEmbedded.create().amazonDynamoDB(); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/utils/DynamoDBResource.java b/src/test/java/org/socialsignin/spring/data/dynamodb/utils/DynamoDBResource.java index 1697ad83..67f64e03 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/utils/DynamoDBResource.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/utils/DynamoDBResource.java @@ -25,24 +25,24 @@ import org.springframework.util.Assert; /** - * Clue {@link Configuration} class for all integration tests. - * It exposes the {@link AmazonDynamoDB} pre-configured to use the - * launched local DynamoDB by Maven's integration-test. + * Clue {@link Configuration} class for all integration tests. It exposes the + * {@link AmazonDynamoDB} pre-configured to use the launched local DynamoDB by + * Maven's integration-test. */ @Configuration public class DynamoDBResource { - private static final String DYNAMODB_PORT_PROPERTY = "dynamodb.port"; - private static final String PORT = System.getProperty(DYNAMODB_PORT_PROPERTY); + private static final String DYNAMODB_PORT_PROPERTY = "dynamodb.port"; + private static final String PORT = System.getProperty(DYNAMODB_PORT_PROPERTY); - @Bean - public AmazonDynamoDB amazonDynamoDB() { - Assert.notNull(PORT, "System property '" + DYNAMODB_PORT_PROPERTY + " not set!"); + @Bean + public AmazonDynamoDB amazonDynamoDB() { + Assert.notNull(PORT, "System property '" + DYNAMODB_PORT_PROPERTY + " not set!"); - AmazonDynamoDBClientBuilder builder = AmazonDynamoDBClientBuilder.standard(); - builder.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("AWS-Key", ""))); - builder.withEndpointConfiguration( - new AwsClientBuilder.EndpointConfiguration(String.format("http://localhost:%s", PORT), "us-east-1")); + AmazonDynamoDBClientBuilder builder = AmazonDynamoDBClientBuilder.standard(); + builder.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("AWS-Key", ""))); + builder.withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration(String.format("http://localhost:%s", PORT), "us-east-1")); - return builder.build(); - } + return builder.build(); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/utils/SortHandlerTest.java b/src/test/java/org/socialsignin/spring/data/dynamodb/utils/SortHandlerTest.java index 5ffc36b0..d4cc95d0 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/utils/SortHandlerTest.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/utils/SortHandlerTest.java @@ -23,44 +23,45 @@ import org.springframework.data.domain.Sort; public class SortHandlerTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); + @Rule + public ExpectedException expectedException = ExpectedException.none(); - private SortHandler underTest = new SortHandler() {}; + private SortHandler underTest = new SortHandler() { + }; - @Test - public void testThrowUnsupportedSortException() { - expectedException.expect(UnsupportedOperationException.class); - - underTest.throwUnsupportedSortOperationException(); - } + @Test + public void testThrowUnsupportedSortException() { + expectedException.expect(UnsupportedOperationException.class); - @Test - public void testEnsureNoSortUnsorted() { - underTest.ensureNoSort(Sort.unsorted()); - } + underTest.throwUnsupportedSortOperationException(); + } - @Test - public void testEnsureNoSortSorted() { - expectedException.expect(UnsupportedOperationException.class); + @Test + public void testEnsureNoSortUnsorted() { + underTest.ensureNoSort(Sort.unsorted()); + } - underTest.ensureNoSort(Sort.by("property")); - } + @Test + public void testEnsureNoSortSorted() { + expectedException.expect(UnsupportedOperationException.class); - @Test - public void testEnsureNoSortUnpaged() { - underTest.ensureNoSort(Pageable.unpaged()); - } + underTest.ensureNoSort(Sort.by("property")); + } - @Test - public void TestEnsureNoSortPagedUnsorted() { - underTest.ensureNoSort(PageRequest.of(0, 1, Sort.unsorted())); - } + @Test + public void testEnsureNoSortUnpaged() { + underTest.ensureNoSort(Pageable.unpaged()); + } - @Test - public void TestEnsureNoSortPagedSorted() { - expectedException.expect(UnsupportedOperationException.class); + @Test + public void TestEnsureNoSortPagedUnsorted() { + underTest.ensureNoSort(PageRequest.of(0, 1, Sort.unsorted())); + } - underTest.ensureNoSort(PageRequest.of(0, 1, Sort.by("property"))); - } + @Test + public void TestEnsureNoSortPagedSorted() { + expectedException.expect(UnsupportedOperationException.class); + + underTest.ensureNoSort(PageRequest.of(0, 1, Sort.by("property"))); + } } diff --git a/src/test/java/org/socialsignin/spring/data/dynamodb/utils/TableCreationListener.java b/src/test/java/org/socialsignin/spring/data/dynamodb/utils/TableCreationListener.java index 472b2194..376ae538 100644 --- a/src/test/java/org/socialsignin/spring/data/dynamodb/utils/TableCreationListener.java +++ b/src/test/java/org/socialsignin/spring/data/dynamodb/utils/TableCreationListener.java @@ -35,84 +35,83 @@ public class TableCreationListener extends AbstractTestExecutionListener { - public static CreateTableResult createTable(AmazonDynamoDB ddb, Class domainType) { - DynamoDBMapper mapper = new DynamoDBMapper(ddb); - - ProvisionedThroughput pt = new ProvisionedThroughput(10L, 10L); - - CreateTableRequest ctr = mapper.generateCreateTableRequest(domainType); - ctr.setProvisionedThroughput(pt); - if (ctr.getGlobalSecondaryIndexes() != null) { - ctr.getGlobalSecondaryIndexes().forEach(gsi -> { - gsi.setProjection(new Projection().withProjectionType(ProjectionType.ALL)); - gsi.setProvisionedThroughput(pt); - }); - } - - CreateTableResult ctResponse = ddb.createTable(ctr); - - do { - try { - Thread.sleep(1 * 1000L); - } catch (InterruptedException e) { - throw new RuntimeException("Couldn't wait detect table " + ctr.getTableName()); - } - } - while (!ddb.describeTable(ctr.getTableName()).getTable().getTableStatus().equals("ACTIVE")); - - return ctResponse; - } - - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.TYPE) - @Documented - public @interface DynamoDBCreateTable { - Class[] entityClasses(); - } - - protected Class[] getEntityClasses() { - return new Class[0]; - } - - private void createExpliclitEntities(TestContext testContext) { - BeanFactory bf = testContext.getApplicationContext().getAutowireCapableBeanFactory(); - - AmazonDynamoDB ddb = bf.getBean(AmazonDynamoDB.class); - - Arrays.stream(getEntityClasses()).forEach(clazz -> createTable(ddb, clazz)); - } - - @Override - public void beforeTestClass(TestContext testContext) { - createExpliclitEntities(testContext); - createAnnotationEntities(testContext); - } - - private void createAnnotationEntities(TestContext testContext) { - - Class testClass = testContext.getTestClass(); - if (testClass.isAnnotationPresent(DynamoDBCreateTable.class)) { - - DynamoDBCreateTable createTableAnnotation = testClass.getAnnotation(DynamoDBCreateTable.class); - - AmazonDynamoDB ddb = getAmazonDynamoDB(testContext); - - for (Class entityClass : createTableAnnotation.entityClasses()) { - createTable(ddb, entityClass); - } - } - } - - @Override - public void afterTestClass(TestContext testContext) throws Exception { - getAmazonDynamoDB(testContext).shutdown(); - } - - private BeanFactory getBeanFactory(TestContext testContext) { - return testContext.getApplicationContext().getAutowireCapableBeanFactory(); - } - - private AmazonDynamoDB getAmazonDynamoDB(TestContext testContext) { - return getBeanFactory(testContext).getBean(AmazonDynamoDB.class); - } + public static CreateTableResult createTable(AmazonDynamoDB ddb, Class domainType) { + DynamoDBMapper mapper = new DynamoDBMapper(ddb); + + ProvisionedThroughput pt = new ProvisionedThroughput(10L, 10L); + + CreateTableRequest ctr = mapper.generateCreateTableRequest(domainType); + ctr.setProvisionedThroughput(pt); + if (ctr.getGlobalSecondaryIndexes() != null) { + ctr.getGlobalSecondaryIndexes().forEach(gsi -> { + gsi.setProjection(new Projection().withProjectionType(ProjectionType.ALL)); + gsi.setProvisionedThroughput(pt); + }); + } + + CreateTableResult ctResponse = ddb.createTable(ctr); + + do { + try { + Thread.sleep(1 * 1000L); + } catch (InterruptedException e) { + throw new RuntimeException("Couldn't wait detect table " + ctr.getTableName()); + } + } while (!ddb.describeTable(ctr.getTableName()).getTable().getTableStatus().equals("ACTIVE")); + + return ctResponse; + } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + @Documented + public @interface DynamoDBCreateTable { + Class[] entityClasses(); + } + + protected Class[] getEntityClasses() { + return new Class[0]; + } + + private void createExpliclitEntities(TestContext testContext) { + BeanFactory bf = testContext.getApplicationContext().getAutowireCapableBeanFactory(); + + AmazonDynamoDB ddb = bf.getBean(AmazonDynamoDB.class); + + Arrays.stream(getEntityClasses()).forEach(clazz -> createTable(ddb, clazz)); + } + + @Override + public void beforeTestClass(TestContext testContext) { + createExpliclitEntities(testContext); + createAnnotationEntities(testContext); + } + + private void createAnnotationEntities(TestContext testContext) { + + Class testClass = testContext.getTestClass(); + if (testClass.isAnnotationPresent(DynamoDBCreateTable.class)) { + + DynamoDBCreateTable createTableAnnotation = testClass.getAnnotation(DynamoDBCreateTable.class); + + AmazonDynamoDB ddb = getAmazonDynamoDB(testContext); + + for (Class entityClass : createTableAnnotation.entityClasses()) { + createTable(ddb, entityClass); + } + } + } + + @Override + public void afterTestClass(TestContext testContext) throws Exception { + getAmazonDynamoDB(testContext).shutdown(); + } + + private BeanFactory getBeanFactory(TestContext testContext) { + return testContext.getApplicationContext().getAutowireCapableBeanFactory(); + } + + private AmazonDynamoDB getAmazonDynamoDB(TestContext testContext) { + return getBeanFactory(testContext).getBean(AmazonDynamoDB.class); + } }